From e6ae5810a330ee755b5a8bbe9181703dad25aae2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:03:28 -0800 Subject: [PATCH 001/288] fix(web): preserve reading position when side panels resize (#41184) Co-authored-by: 137 <113233555+caezium@users.noreply.github.com> --- ...rPromptEditorTiptap.input.browser.test.tsx | 48 +++++++ .../components/ComposerPromptEditorTiptap.tsx | 6 + .../chat/MessagesTimeline.browser.test.tsx | 42 ++++++ .../src/components/chat/MessagesTimeline.tsx | 13 ++ apps/web/src/lib/preserveReadingPosition.ts | 115 ++++++++++++++++ ...de-panel-preserves-reading-position.e2e.ts | 124 ++++++++++++++++++ 6 files changed, 348 insertions(+) create mode 100644 apps/web/src/lib/preserveReadingPosition.ts create mode 100644 scripts/scenarios/side-panel-preserves-reading-position.e2e.ts diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ff5b426c0bf3f..230603dfe46dd 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -682,6 +682,54 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it.each(["none", "caret", "selection"] as const)( + "keeps the reading position when a draft rewraps (focus: %s)", + async (focus) => { + const focused = focus !== "none"; + const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat( + 100, + ); + const style = document.head.appendChild(document.createElement("style")); + style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }"; + using _style = { [Symbol.dispose]: () => style.remove() }; + await using screen = await mountEditor(value); + const { editor } = screen; + const scroller = editor.view.dom; + await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500)); + if (focused) await focusAt(editor, 2000); + scroller.scrollTop = 300; + scroller.dispatchEvent(new Event("scroll")); + const box = scroller.getBoundingClientRect(); + const position = editor.view.posAtCoords({ + left: box.left + box.width / 2, + top: box.top + 25, + })!; + const before = editor.view.coordsAtPos(position.pos).top - box.top; + if (focused) await focusAt(editor, position.pos); + if (focus === "selection") { + editor.commands.setTextSelection({ from: position.pos, to: position.pos + 20 }); + } + document.dispatchEvent(new Event("selectionchange")); + const selection = editor.state.selection.toJSON(); + for (const width of [420, 700]) { + // The panel toggle shortcut reaches the focused editor before the width changes. + if (focused) { + scroller.dispatchEvent( + new KeyboardEvent("keydown", { key: "b", ctrlKey: true, altKey: true, bubbles: true }), + ); + } + scroller.style.width = `${width}px`; + await vi.waitFor(() => { + const after = + editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(25); + }); + expect(editor.state.selection.toJSON()).toEqual(selection); + expect(editor.view.hasFocus()).toBe(focused); + } + }, +); + it("does not outline the line under a click made with the node-select modifier held", async () => { await using screen = await mountEditor("ship it"); const { editor } = screen; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 634b7a9389e93..8ce568c117dce 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -64,6 +64,7 @@ import { pastedPathQueryLength, } from "~/composer-logic"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction"; import { collapseShownMarkdownSource, @@ -1765,6 +1766,11 @@ function ComposerPromptEditorTiptapInner( if (replacements.length > 0) replaceSkillChips(editor, replacements); }, [editor, literalText, modelKeys, skills]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes + useLayoutEffect(() => { + if (editor) return preserveReadingPosition(editor.view.dom); + }, [editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index d15a26ca43db0..bce13bb454379 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -626,6 +626,48 @@ describe("MessagesTimeline messages", () => { await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); }); + it("keeps the visible sentence in a long message when the chat width changes", async () => { + setup(); + const size = { width: window.innerWidth, height: window.innerHeight }; + onTestFinished(() => page.viewport(size.width, size.height)); + await page.viewport(1200, 1400); + const props = { ...baseProps(), liveFollowEnabled: false }; + const paragraphs = Array.from( + { length: 30 }, + (_, index) => + `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`, + ); + await using screen = await renderTimeline( + [message(paragraphs.join("\n\n"), { role: "assistant" })], + props, + ); + screen.container.style.width = "900px"; + const viewport = props.listRef.current!.getScrollableNode()!; + const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element(); + await vi.waitFor(() => { + expect(viewport.scrollHeight).toBeGreaterThan(1000); + expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); + }); + await props.listRef.current!.scrollToOffset({ + offset: + viewport.scrollTop + + target.getBoundingClientRect().top - + viewport.getBoundingClientRect().top - + 24, + animated: false, + }); + viewport.dispatchEvent(new Event("scroll")); + const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(before - 24)).toBeLessThan(2); + for (const width of [500, 900]) { + screen.container.style.width = `${width}px`; + await vi.waitFor(() => { + const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(30); + }); + } + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 207f719c8e6e9..42409464aca7a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -26,6 +26,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { useStableCallback } from "~/hooks/useStableCallback"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; @@ -1261,6 +1262,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; + const shouldPreserveReadingPosition = useStableCallback( + () => + !liveFollowEnabled && + !anchoredEndSpace && + !findActive && + !citationPositioning && + !restoringThreadPosition, + ); // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1276,6 +1285,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; + const stopPreservingReadingPosition = scrollNode + ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition) + : undefined; const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1304,6 +1316,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ scheduleContentSizeChanged(); return () => { stopListeningToContentSize?.(); + stopPreservingReadingPosition?.(); stopRememberingRelease?.(); stopDisclosureReveal?.(); if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame); diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts new file mode 100644 index 0000000000000..2c6f576519911 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -0,0 +1,115 @@ +import { observeResize } from "./observeResize"; + +/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ +export function preserveReadingPosition( + scroller: HTMLElement, + enabled: () => boolean = () => true, +): () => void { + let width = scroller.clientWidth; + let anchor: { range: Range; top: number } | null = null; + let frame: number | null = null; + + const capture = () => { + if (frame !== null || scroller.clientWidth !== width) return; + anchor = null; + if (!enabled() || scroller.scrollTop === 0) return; + const box = scroller.getBoundingClientRect(); + const selection = + scroller.isContentEditable && document.activeElement === scroller + ? document.getSelection() + : null; + if (selection?.isCollapsed && selection.rangeCount > 0) { + const range = selection.getRangeAt(0).cloneRange(); + const rect = range.getBoundingClientRect(); + if ( + scroller.contains(range.startContainer) && + rect.top >= box.top && + rect.bottom <= box.bottom + ) { + anchor = { range, top: rect.top - box.top }; + return; + } + } + // A point near the top captures text rather than the paragraph's bounding box. + const x = box.left + box.width / 2; + // The first point can land in paragraph spacing. Look only within the first few lines. + for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { + const y = box.top + inset; + const position = document.caretPositionFromPoint?.(x, y); + const range = document.createRange(); + if (position) { + range.setStart(position.offsetNode, position.offset); + } else { + const fallback = document.caretRangeFromPoint?.(x, y); + if (!fallback) continue; + range.setStart(fallback.startContainer, fallback.startOffset); + } + range.collapse(true); + if ( + !scroller.contains(range.startContainer) || + range.startContainer.nodeType !== Node.TEXT_NODE + ) + continue; + const top = range.getBoundingClientRect().top - box.top; + if (top >= 0 && top < scroller.clientHeight) { + anchor = { range, top }; + break; + } + } + }; + const restore = () => { + if ( + !enabled() || + !anchor || + anchor.range.startContainer.nodeType !== Node.TEXT_NODE || + !scroller.contains(anchor.range.startContainer) + ) + return; + const delta = + anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; + if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; + }; + const stop = observeResize(scroller, () => { + const nextWidth = scroller.clientWidth; + if (nextWidth === width) { + capture(); + return; + } + width = nextWidth; + restore(); + if (frame !== null) cancelAnimationFrame(frame); + // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. + frame = requestAnimationFrame(() => { + restore(); + frame = null; + capture(); + }); + }); + scroller.addEventListener("scroll", capture, { passive: true }); + scroller.addEventListener("input", capture); + const captureSelection = () => { + if (document.activeElement === scroller) capture(); + }; + if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); + const interrupt = () => { + if (frame !== null) cancelAnimationFrame(frame); + anchor = null; + // Scrolling wins over a pending resize correction; the next frame captures the reader's new place. + frame = requestAnimationFrame(() => { + frame = null; + width = scroller.clientWidth; + capture(); + }); + }; + scroller.addEventListener("wheel", interrupt, { passive: true }); + scroller.addEventListener("touchmove", interrupt, { passive: true }); + return () => { + stop(); + if (frame !== null) cancelAnimationFrame(frame); + scroller.removeEventListener("scroll", capture); + scroller.removeEventListener("input", capture); + document.removeEventListener("selectionchange", captureSelection); + scroller.removeEventListener("wheel", interrupt); + scroller.removeEventListener("touchmove", interrupt); + }; +} diff --git a/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts new file mode 100644 index 0000000000000..5a86da06aae41 --- /dev/null +++ b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts @@ -0,0 +1,124 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const text = Array.from( + { length: 70 }, + (_, index) => + `Sentence ${index + 1}. Opening a side panel should keep the sentence being read visible while the text wraps to the available width. `, +).join(""); + +test( + "Opening a side panel preserves the visible text in the conversation and draft", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Reading position", + messages: ["Start"], + model: "multi-turn", + }); + await browser.setViewport({ width: 1440, height: 1000 }); + await t3.open(thread); + await screen.getByRole("button", "Toggle thread details panel").tap(); + await screen.getByRole("textbox").fill(text); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("second fixture turn complete", { exact: false }).waitFor(); + await screen.getByRole("button", "Show full message").tap(); + + const position = (draft: boolean, place: boolean) => + browser.evaluate( + async ({ draft, place }) => { + const scroller = document.querySelector( + draft ? ".composer-tiptap" : ".messages-timeline-scroll", + )!; + const content = draft + ? scroller + : Array.from(scroller.querySelectorAll("[data-user-message-body]")).find( + (body) => (body.textContent?.length ?? 0) >= 3000, + ); + if (!content) throw new Error("The long message is not rendered"); + const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT); + let node = walker.nextNode(); + while (node && (node.textContent?.length ?? 0) < 3000) node = walker.nextNode(); + if (!node) throw new Error("The long paragraph is not rendered"); + const range = document.createRange(); + range.setStart(node, 2500); + range.collapse(true); + if (place) { + scroller.blur(); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + } + await new Promise((resolve) => + requestAnimationFrame(() => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, + { draft, place }, + ); + + const point = await browser.evaluate(() => { + const box = document.querySelector(".messages-timeline-scroll")!.getBoundingClientRect(); + return { x: box.left + box.width / 2, y: box.top + 150 }; + }); + await browser.mouse.move(point.x, point.y); + await browser.mouse.wheel(0, -800); + // The wheel's native scroll completes asynchronously before positioning the fixture text. + await browser.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve(null))), + ), + ); + let timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) + throw new Error(`The conversation did not settle at the reading position: ${timelineBefore}`); + await app.screenshot("conversation-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const timelineAfter = await position(false, false); + await app.screenshot("conversation-panel-open"); + await screen.getByRole("button", "Toggle right panel").tap(); + + await screen.getByRole("textbox").fill(text); + const draftBefore = await position(true, true); + if (Math.abs(draftBefore - 48) > 2) + throw new Error("The draft did not settle at the reading position"); + await app.screenshot("draft-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const draftAfter = await position(true, false); + await app.screenshot("draft-panel-open"); + + // The panel shortcut is pressed inside the focused draft, with a caret and then a selection. + const shortcutShifts: number[] = []; + for (const length of [0, 20]) { + const shortcutBefore = await browser.evaluate((length) => { + const scroller = document.querySelector(".composer-tiptap")!; + scroller.focus(); + const node = document.createTreeWalker(scroller, NodeFilter.SHOW_TEXT).nextNode()!; + document.getSelection()!.setBaseAndExtent(node, 2500, node, 2500 + length); + const range = document.createRange(); + range.setStart(node, 2500); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, length); + await browser.keyboard.press("Control+Alt+B"); + shortcutShifts.push(Math.abs((await position(true, false)) - shortcutBefore)); + await app.screenshot(length === 0 ? "draft-caret-shortcut" : "draft-selection-shortcut"); + } + + expect( + Math.max( + Math.abs(timelineAfter - timelineBefore), + Math.abs(draftAfter - draftBefore), + ...shortcutShifts, + ), + ).toBeLessThan(30); + }, +); From 192ef9b7b204c09f1ec1e78255e4d2429d27b682 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:07:23 -0600 Subject: [PATCH 002/288] fix(web): preserve alpha channel when previewing WhiteIsZero TIFF images (#41196) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 89 ++++++++++--------- .../components/files/imageDecode.worker.ts | 6 +- 2 files changed, 53 insertions(+), 42 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index e96b165d5db0e..076f2c7ee32df 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -499,48 +499,55 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and rejects oversized metadata before decoding", async () => { - const tags = [ - [256, 2], - [257, 1], - [258, 8], - [259, 1], - [262, 0], - [273, 134], - [277, 1], - [278, 1], - [279, 2], - [284, 1], - ]; - const bytes = new ArrayBuffer(136); - const view = new DataView(bytes); - view.setUint16(0, 0x4949); - view.setUint16(2, 42, true); - view.setUint32(4, 8, true); - view.setUint16(8, tags.length, true); - tags.forEach(([tag, value], index) => { - const offset = 10 + index * 12; - view.setUint16(offset, tag!, true); - view.setUint16(offset + 2, 4, true); - view.setUint32(offset + 4, 1, true); - view.setUint32(offset + 8, value!, true); - }); - view.setUint8(135, 255); - const src = URL.createObjectURL(new Blob([bytes])); - try { - const blob = await decodeImagePreview(src, false, new AbortController().signal); - const bitmap = await createImageBitmap(blob); - const canvas = new OffscreenCanvas(2, 1); - const context = canvas.getContext("2d")!; - context.drawImage(bitmap, 0, 0); - expect([...context.getImageData(0, 0, 2, 1).data]).toEqual([ - 255, 255, 255, 255, 0, 0, 0, 255, - ]); - bitmap.close(); - } finally { - URL.revokeObjectURL(src); + it("keeps WhiteIsZero TIFF brightness and alpha and rejects oversized metadata before decoding", async () => { + let bytes = new ArrayBuffer(0); + for (const { pixels, expected } of [ + { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, + { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, + ]) { + const samples = pixels.length / 2; + const start = samples === 2 ? 146 : 134; + const tags = [ + [256, 2], + [257, 1], + [258, 8], + [259, 1], + [262, 0], + [273, start], + [277, samples], + [278, 1], + [279, pixels.length], + [284, 1], + ...(samples === 2 ? [[338, 2]] : []), + ]; + bytes = new ArrayBuffer(start + pixels.length); + const view = new DataView(bytes); + view.setUint16(0, 0x4949); + view.setUint16(2, 42, true); + view.setUint32(4, 8, true); + view.setUint16(8, tags.length, true); + tags.forEach(([tag, value], index) => { + const offset = 10 + index * 12; + view.setUint16(offset, tag!, true); + view.setUint16(offset + 2, 4, true); + view.setUint32(offset + 4, 1, true); + view.setUint32(offset + 8, value!, true); + }); + new Uint8Array(bytes, start).set(pixels); + const src = URL.createObjectURL(new Blob([bytes])); + try { + const blob = await decodeImagePreview(src, false, new AbortController().signal); + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(2, 1); + const context = canvas.getContext("2d")!; + context.drawImage(bitmap, 0, 0); + expect([...context.getImageData(0, 0, 2, 1).data]).toEqual(expected); + bitmap.close(); + } finally { + URL.revokeObjectURL(src); + } } - view.setUint32(14, 1_000_000, true); + new DataView(bytes).setUint32(14, 1_000_000, true); const invalid = URL.createObjectURL(new Blob([bytes])); try { await expect( diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index f19174b62af35..9ddcfdbfb3e98 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -190,6 +190,9 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const rgba = new Uint8ClampedArray(image.width * image.height * 4); const scale = image.bitsPerSample === 16 ? 257 : 1; const palette = image.palette; + const alpha = image.alpha; + // The tiff decoder inverts every WhiteIsZero sample, alpha included. + const invertAlpha = alpha && image.type === 0; for (let pixel = 0; pixel < image.width * image.height; pixel++) { const index = pixel * image.components; if (palette) { @@ -203,7 +206,8 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const gray = image.data[index]! / scale; rgba.fill(gray, pixel * 4, pixel * 4 + 3); } - rgba[pixel * 4 + 3] = image.alpha ? image.data[index + image.components - 1]! / scale : 255; + const value = alpha ? image.data[index + image.components - 1]! / scale : 255; + rgba[pixel * 4 + 3] = invertAlpha ? 255 - value : value; } const canvas = new OffscreenCanvas(image.width, image.height); const context = canvas.getContext("2d"); From b50e76981188cf82965fdaa547b4f737c3f27836 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:08:24 -0800 Subject: [PATCH 003/288] fix(server): workflow event types appear only while Workflows is on (#41202) --- apps/server/src/mcp/McpHttpServer.ts | 17 ++++++++++++++--- apps/server/src/mcp/McpInvocationContext.ts | 9 +++++++++ .../src/milestones/MilestoneEvents.test.ts | 17 +++++++++++++++-- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index ab1f7b003c566..be41f8630b7dd 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -291,8 +291,13 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { Effect.map((settings) => ({ linkedEnvironments: settings.linkedEnvironmentsEnabled, agentFeedback: settings.agentFeedback.mode, + workflows: settings.workflowsEnabled, + })), + Effect.orElseSucceed(() => ({ + linkedEnvironments: false, + agentFeedback: "off" as const, + workflows: false, })), - Effect.orElseSucceed(() => ({ linkedEnvironments: false, agentFeedback: "off" as const })), ); const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); @@ -366,7 +371,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const asked = withModeLimit(withSenderThread(invocation, request), request); if (asked === undefined) return invalidModeLimit; const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling); - const { linkedEnvironments, agentFeedback } = yield* settingsFlags; + const { linkedEnvironments, agentFeedback, workflows } = yield* settingsFlags; if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff; const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin)); const forge = @@ -377,6 +382,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { ...limited, linkedEnvironments, agentFeedback, + workflows, origin, ...(forge === undefined ? {} : { forge }), }; @@ -1549,8 +1555,13 @@ export const layerMilestoneEvents = Layer.effectDiscard( for (const options of events.threads) { yield* McpServer.registerEvent({ ...options, annotations }); } + // Listed only while Labs → Workflows is on, since no run can reach them otherwise. + const workflowAnnotations = Context.make( + McpSchema.EnabledWhen, + McpInvocationContext.hiddenUnlessWorkflowEvents, + ); for (const options of events.workflows) { - yield* McpServer.registerEvent({ ...options, annotations }); + yield* McpServer.registerEvent({ ...options, annotations: workflowAnnotations }); } }), ).pipe( diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index f1a070e86b9e3..0ba10af2d8c45 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -155,6 +155,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ + readonly workflows?: boolean; /** * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot * see the URL they were configured with, so links they must fetch carry it. Unset in-process. @@ -237,6 +239,13 @@ export const hiddenWhileFeedbackOff = (): boolean => { return scope?.agentFeedback !== undefined && scope.agentFeedback !== "off"; }; +/** `McpSchema.EnabledWhen` for workflow event types: outside clients only, while Workflows is on. */ +export const hiddenUnlessWorkflowEvents = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope !== undefined && scope.thread === undefined && scope.workflows === true; +}; + /** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */ export const hiddenWithoutForge = (): boolean => { const fiber = Fiber.getCurrent(); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index 06e7763023841..49f6c1c5c6b5a 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -128,7 +128,7 @@ type JsonRpcResponse = { readonly error?: { readonly code: number; readonly data?: unknown }; }; -const serve = Effect.gen(function* () { +const serveWith = Effect.fnUntraced(function* (settings: { readonly workflowsEnabled: boolean }) { const revoked = yield* Deferred.make(); const deliveries = yield* Queue.unbounded(); const replies = new Set(); @@ -164,7 +164,7 @@ const serve = Effect.gen(function* () { }), ), ), - Layer.provide(ServerSettings.layerTest()), + Layer.provide(ServerSettings.layerTest(settings)), Layer.provide( Layer.mock(SessionStore.SessionStore)({ cookieName: "t3-session", @@ -285,6 +285,7 @@ const serve = Effect.gen(function* () { subscribe, }; }); +const serve = serveWith({ workflowsEnabled: true }); const layerTest = Layer.mergeAll( MilestoneHub.layer, @@ -330,6 +331,18 @@ it.effect("advertises the extension and lists each milestone type to outside cli }).pipe(Effect.scoped, Effect.provide(layerTest)), ); +it.effect("lists workflow event types only while Labs → Workflows is on", () => + Effect.gen(function* () { + const { call } = yield* serveWith({ workflowsEnabled: false }); + const { events } = (yield* call("events/list")).result!; + const names = (events as ReadonlyArray<{ name: string }>).map((event) => event.name); + expect(names).toHaveLength(6); + expect(names.some((name) => name.startsWith("workflow."))).toBe(false); + const poll = yield* call("events/poll", { name: "workflow.run_ended", cursor: null }); + expect(poll.error).toBeDefined(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + it.effect("polls from now, then pages forward and says when a cursor fell behind", () => Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; From dc2f73af48dbb5f5983c2fca2bd520b70a56f5da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:09:00 -0800 Subject: [PATCH 004/288] fix(server): worktree launches name their branch while the worktree is created (#36904) Co-authored-by: Claude Opus 5.5 --- .../ThreadLaunchService.test.ts | 37 +++++++++++++++++++ .../orchestration-v2/ThreadLaunchService.ts | 25 ++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2d5d1c5824dde..9bc617e48823b 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -3233,6 +3233,43 @@ it.effect("starts the agent of a new worktree thread only after its branch is re }), ); +it.effect("names a new worktree thread's branch while its worktree is being created", () => + Effect.gen(function* () { + const branchNameStarted = yield* Deferred.make(); + const renamedTo = yield* Deferred.make(); + const harness = makeHarness({ + generateBranchName: () => + Deferred.succeed(branchNameStarted, undefined).pipe( + Effect.as({ branch: "generated-branch" }), + ), + createWorktree: (input) => + Deferred.await(branchNameStarted).pipe( + Effect.as({ + worktree: { + path: "/repo-worktrees/feature", + refName: input.newRefName, + headSha: "abc", + }, + } as never), + ), + renameBranch: (input) => + Deferred.succeed(renamedTo, input.newBranch).pipe(Effect.as({ branch: input.newBranch })), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* launches.launch( + launchInput({ + command: "launch:name-during-checkout", + thread: "thread:name-during-checkout", + message: "Start", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + assert.equal(yield* Deferred.await(renamedTo), "generated-branch"); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("tells the thread when its worktree branch could not be renamed", () => Effect.gen(function* () { const harness = makeHarness({ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index ce22ad783e0e6..9262695987cbf 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -571,6 +571,7 @@ const make = Effect.gen(function* () { let runReleased = false; // Stop background renames before forgetting worktrees; completed renames record them again. let branchRename: Fiber.Fiber | null = null; + let stopBranchName: Effect.Effect = Effect.void; if (input.workspaceStrategy.type === "worktree") { yield* setupTracker.begin({ threadId, @@ -662,6 +663,19 @@ const make = Effect.gen(function* () { input.workspaceStrategy.type === "existing_worktree" ? input.workspaceStrategy.worktreePath : null; + // The agent waits for this LLM call; start it now so it overlaps fetch, checkout and setup. + const branchName = + reused === undefined && + initialMessage !== undefined && + (input.workspaceStrategy.type === "worktree" || worktreePath !== null) && + branch !== null && + (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch)) + ? yield* generateBranchNameFor( + worktreePath ?? project.workspaceRoot, + initialMessage, + ).pipe(Effect.forkIn(preparationScope)) + : null; + if (branchName !== null) stopBranchName = Fiber.interrupt(branchName); if (input.workspaceStrategy.type === "worktree") { const taskPlan = yield* taskFolders .plan({ projectId: project.id, repositories: input.workspaceStrategy.repositories }) @@ -898,7 +912,11 @@ const make = Effect.gen(function* () { ) { const oldBranch = branch; const worktreeCwd = worktreePath; - branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe( + const generatedName = + branchName === null + ? generateBranchNameFor(worktreeCwd, initialMessage) + : Fiber.join(branchName); + branchRename = yield* generatedName.pipe( Effect.flatMap(({ branch: newBranch, exactName }) => Effect.suspend( (): Effect.Effect< @@ -995,6 +1013,8 @@ const make = Effect.gen(function* () { ), Effect.forkIn(preparationScope), ); + } else { + yield* stopBranchName; } if (runId !== null && worktreePath !== null) { @@ -1113,6 +1133,8 @@ const make = Effect.gen(function* () { Effect.onError((cause) => Effect.gen(function* () { const cancelled = Cause.hasInterruptsOnly(cause); + // Not yet handed to a rename, so nothing will use the name. + if (branchRename === null) yield* stopBranchName; yield* setupTracker.finish( threadId, cancelled ? "cancelled" : "failed", @@ -1128,6 +1150,7 @@ const make = Effect.gen(function* () { ((cancelled && !runReleased) || !workspaceRecorded) ) { if (branchRename !== null) yield* Fiber.interrupt(branchRename); + yield* stopBranchName; const removedPath = createdWorktreePath; const removedBranch = createdBranch; const removedTaskFolder = createdTaskFolder; From 9d3054a7bbc0ab02330a03d5735f4adf72a4e887 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:22:28 -0600 Subject: [PATCH 005/288] fix(cli): expand ~ paths passed to t3 project add --track (#41199) Co-authored-by: Julius Marminge --- apps/server/src/cli/project.test.ts | 7 ++++++- apps/server/src/cli/project.ts | 5 ++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 21c3e1caa1943..6dfd723e7084a 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2AppThread, type ProjectId, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -139,6 +140,7 @@ it.effect( // Repositories inside the folder are found; `--track` adds one from outside it. const shared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-shared-")); + const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); yield* runCli([ @@ -147,12 +149,15 @@ it.effect( workspaceRoot, "--track", `${shared}${NodePath.sep}`, + "--track", + `~/${NodePath.basename(homeShared)}`, "--base-dir", baseDir, - ]); + ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); assert.deepEqual((yield* readProjects(baseDir)).projects[0]?.trackedFolders, [ { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, + { path: homeShared, name: NodePath.basename(homeShared) }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index d2e84e0d4f4f5..1fa7cc0f3f264 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -7,6 +7,8 @@ import { type ProjectSnapshot, ProjectId, } from "@t3tools/contracts"; +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -395,9 +397,10 @@ const projectAddCommand = Command.make("add", { (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot, ); const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; const named = flags.track .map((folder) => { - const resolved = path.resolve(folder); + const resolved = path.resolve(expandHomePath(folder, home)); return { path: resolved, name: (path.basename(resolved) || resolved).slice(0, 128).trim(), From 4aed1194fe32a11e4f40bc805ae606abadedf43e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:35:32 -0800 Subject: [PATCH 006/288] fix(server): html_preview as root names the sandbox opt-out (#41206) --- apps/server/src/htmlRender/HtmlRender.test.ts | 27 +++++++++++++++++++ apps/server/src/preview/PreviewBrowserHost.ts | 3 +++ 2 files changed, 30 insertions(+) diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index 4ef5d1d1db58e..e1ba0742f3c90 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -522,6 +522,33 @@ fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => { expect(error.message).toContain(`browser setup --base-dir ${baseDir}`); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.live("reports a root server's sandbox refusal as a root error", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-fake-browser-", + }); + const executable = path.join(directory, "chrome-headless-shell"); + const refusal = + "[1123/040735.447156:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:103] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.\n"; + yield* fileSystem.writeFileString( + executable, + `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(refusal)});\nprocess.exit(1);\n`, + { mode: 0o755 }, + ); + + const error = yield* HtmlRender.HtmlRender.use((htmlRender) => + htmlRender.preview({ html: "

hello

" }), + ).pipe( + Effect.flip, + Effect.provide(layerHtmlRender(executable)), + Effect.provideService(HostProcess.UserId, 0), + ); + expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserRootError); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }, ); diff --git a/apps/server/src/preview/PreviewBrowserHost.ts b/apps/server/src/preview/PreviewBrowserHost.ts index 0952dbaf944cd..6241ef9060238 100644 --- a/apps/server/src/preview/PreviewBrowserHost.ts +++ b/apps/server/src/preview/PreviewBrowserHost.ts @@ -8,6 +8,8 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; export const SETUP_SUBCOMMAND = "browser setup"; export const NO_SANDBOX_SIGNATURE = "No usable sandbox"; +/** What chrome-headless-shell prints itself when started sandboxed as root. */ +const ROOT_SANDBOX_SIGNATURE = "Running as root without --no-sandbox"; export const sandboxDisabled = (env: Readonly>) => env.T3CODE_SERVER_BROWSER_SANDBOX === "0"; @@ -92,6 +94,7 @@ export const diagnoseLaunchFailure = Effect.fn("PreviewBrowserHost.diagnoseLaunc readonly setupCommand: string; }) { const { setupCommand } = input; + if (input.output.includes(ROOT_SANDBOX_SIGNATURE)) return new PreviewBrowserRootError(); if (input.output.includes(NO_SANDBOX_SIGNATURE)) { // Playwright reports Chrome's refusal to sandbox as root as a sandbox failure too. return (yield* HostProcess.UserId) === 0 From d775f66a1578e25e95366346da576a6bdf7a3147 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 20:36:22 -0800 Subject: [PATCH 007/288] chore: vouch jschachter (#41215) --- .github/VOUCHED.td | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 5c0f9e1f74a2a..a2981329cda25 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -46,6 +46,7 @@ github:jamesx0416 github:jappyjan github:jasonLaster github:JoeEverest +github:jschachter github:justsomelegs github:kridaydave github:lgwacker From 7e5a4398f58df267ac4ca983bdf7fb2366081f85 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:40:39 -0600 Subject: [PATCH 008/288] fix(server): parse unordered HTML favicon rel tokens (#41203) Co-authored-by: Julius Marminge --- .../src/project/ProjectFaviconResolver.test.ts | 14 +++++++++++++- apps/server/src/project/ProjectFaviconResolver.ts | 6 ++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index d00147991cf5d..d4cc22efd220a 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -219,6 +219,18 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(yield* resolver.resolvePath(paddedCwd)).toBe( (yield* Path.Path).join(paddedCwd, "brand", "custom.svg"), ); + + const tokenListCwd = yield* makeTempDir; + yield* writeTextFile( + tokenListCwd, + "index.html", + ``, + ); + yield* writeTextFile(tokenListCwd, "touch.svg", "touch"); + yield* writeTextFile(tokenListCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(tokenListCwd)).toBe( + (yield* Path.Path).join(tokenListCwd, "brand.svg"), + ); }), ); @@ -248,7 +260,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, - { rel: "icon", href: "/brand/logo.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 4554c308b4c19..497538634ae73 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -77,9 +77,11 @@ const ICON_SOURCE_FILES = [ ] as const; const HTML_LINK_RE = /]*>/gi; -const HTML_ICON_REL_RE = /\brel=["'](?:icon|shortcut icon)["']/i; +// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link. +const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`; +const HTML_ICON_REL_RE = new RegExp(String.raw`\brel=${ICON_REL_VALUE}`, "i"); const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; -const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i; +const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( From 71d1830e52d8e4bcb2b81dead36ce449ef8db5c3 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 21:02:49 -0800 Subject: [PATCH 009/288] fix(server): token analytics label new models from Codex and Claude catalogs (#41214) Co-authored-by: Claude Opus 5.5 --- .../src/feedback/FeedbackService.test.ts | 1 + .../src/telemetry/ProviderDimensions.test.ts | 19 +++++- .../src/telemetry/ProviderDimensions.ts | 67 ++++++++++--------- .../telemetry/ProviderUsageAnalytics.test.ts | 52 ++++++++++++-- 4 files changed, 100 insertions(+), 39 deletions(-) diff --git a/apps/server/src/feedback/FeedbackService.test.ts b/apps/server/src/feedback/FeedbackService.test.ts index cdc7a7984e6f7..be632b62c5fc2 100644 --- a/apps/server/src/feedback/FeedbackService.test.ts +++ b/apps/server/src/feedback/FeedbackService.test.ts @@ -314,6 +314,7 @@ const harness = Effect.gen(function* () { { instanceId, driver: "codex", + auth: { status: "authenticated" }, models: [{ slug: "gpt-5.5", isCustom: false }], } as unknown as ServerProvider, ]), diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 00e59c11228cb..3959d7dc78e4b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -7,15 +7,20 @@ const provider = ( instanceId: string, driver: string, models: ReadonlyArray<{ slug: string; isCustom: boolean }>, + auth: Record = {}, ) => ({ instanceId: ProviderInstanceId.make(instanceId), driver, + auth: { status: "authenticated", ...auth }, models, }) as unknown as ServerProvider; const providers = [ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), + provider("azure-codex", "codex", [{ slug: "gpt-acme-finetune", isCustom: false }], { + endpoint: "https://acme.example.com", + }), provider("claudeAgent", "claudeAgent", [ { slug: "claude-opus-5-5", isCustom: false }, { slug: "my-private-finetune", isCustom: true }, @@ -37,13 +42,17 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, and unknown models and instance names", () => { +it("omits custom, user-configured, endpoint-served, and unknown models and instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", providers, caller: thread("claudeAgent", "my-private-finetune"), - targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], + targets: [ + thread("opencode", "ollama/acme-internal"), + thread("removed-instance", "gpt-5.5"), + thread("azure-codex", "gpt-acme-finetune"), + ], outcome: { outcome: "ok" }, }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ callerProvider, @@ -64,6 +73,12 @@ it("omits custom, user-configured, and unknown models and instance names", () => targetProvider: "unknown", targetModel: undefined, }, + { + callerProvider: "claudeAgent", + callerModel: undefined, + targetProvider: "codex", + targetModel: undefined, + }, ]); }); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 49faea7e688c0..497f1e660131b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -6,19 +6,6 @@ import type { import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts"; -/** - * Drivers whose model catalogs are published by the vendor. Other drivers - * (OpenCode, Pi, ACP agents) list models from the user's own configuration, - * such as local Ollama tags, so their model names stay out of analytics. - */ -const VENDOR_CATALOG_DRIVERS: ReadonlySet = new Set([ - "codex", - "claudeAgent", - "cursor", - "grok", - "antigravity", -]); - export interface ProviderDimensions { readonly provider: string; readonly model?: string; @@ -27,7 +14,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are * user-defined, so only the driver kind is reported. The model is reported - * only when it comes from a vendor catalog and is not a user-added custom model. + * only when the selected instance's vendor catalog lists it. */ export function providerDimensions( providers: ReadonlyArray, @@ -35,17 +22,15 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = provider.models.find((candidate) => candidate.slug === selection.model); - return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom - ? { provider: provider.driver, model: model.slug } - : { provider: provider.driver }; + const model = vendorCatalogEntry(provider, [selection.model]); + return model === undefined + ? { provider: provider.driver } + : { provider: provider.driver, model: model.slug }; } const DATED_SNAPSHOT = /-\d{8}$/u; -// The bundled manifest is reviewed in this repo. Codex lists whatever its configured -// model provider serves, so only the manifest vouches for Codex and Claude. Cursor, Grok, -// and Antigravity list their vendor's catalog, which ships models before the manifest does. +// The bundled manifest is reviewed in this repo. Vendor catalogs ship models before it does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -53,13 +38,39 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ), ); -const REGISTRY_LABEL_DRIVERS: ReadonlySet = new Set(["cursor", "grok", "antigravity"]); + +// Drivers whose model lists come from the vendor. OpenCode, Pi, and ACP agents list the +// user's own configuration, such as local Ollama tags. Codex and Claude also list +// early-access code names, so only slugs in the vendor's public family vouch for them. +const VENDOR_CATALOGS: ReadonlyMap = new Map([ + ["cursor", undefined], + ["grok", undefined], + ["antigravity", undefined], + ["codex", /^gpt-/u], + ["claudeAgent", /^claude-/u], +]); + +// A custom endpoint or gateway serves whatever names its owner chose. +const isVendorRouted = (auth: ServerProvider["auth"]) => + auth.endpoint === undefined && auth.type !== "customEndpoint" && auth.type !== "bedrock"; + +function vendorCatalogEntry(provider: ServerProvider, candidates: ReadonlyArray) { + if (!VENDOR_CATALOGS.has(provider.driver) || !isVendorRouted(provider.auth)) return undefined; + const family = VENDOR_CATALOGS.get(provider.driver); + return provider.models.find( + (entry) => + !entry.isCustom && + (family === undefined || family.test(entry.slug)) && + (candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true), + ); +} /** * The vendor catalog slug that a native or routed model id names, such as * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and the Cursor, Grok, and Antigravity catalogs, including user-added ones, - * return undefined. + * manifest and vendor-routed provider catalogs, including user-added ones and + * names a custom endpoint serves, return undefined. */ export function catalogModelLabel( providers: ReadonlyArray, @@ -72,13 +83,7 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - if (!REGISTRY_LABEL_DRIVERS.has(provider.driver)) continue; - const match = provider.models.find( - (entry) => - !entry.isCustom && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), - ); + const match = vendorCatalogEntry(provider, candidates); if (match !== undefined) return match.slug; } return undefined; diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 249ec86f3724c..0ce417e9a2c8b 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -26,9 +26,28 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Codex lists whatever its configured model provider serves, including private deployments. - { driver: "codex", models: [{ slug: "gpt-6-sol" }, { slug: "acme-azure-deployment" }] }, - { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, + // Vendor-routed Codex lists OpenAI's catalog, including early-access code names. + { + driver: "codex", + models: [{ slug: "gpt-6-sol" }, { slug: "gpt-6.2-sol" }, { slug: "nova-alpha" }], + }, + // A custom endpoint serves whatever its owner chose, including private deployments. + { + instanceId: "azure-codex", + driver: "codex", + auth: { endpoint: "https://acme.example.com" }, + models: [{ slug: "acme-azure-deployment" }, { slug: "gpt-acme-finetune" }], + }, + { + driver: "claudeAgent", + models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }, { slug: "claude-opus-6" }], + }, + { + instanceId: "claude-gateway", + driver: "claudeAgent", + auth: { type: "customEndpoint" }, + models: [{ slug: "claude-ops-internal" }], + }, { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, // Antigravity ships models before the bundled manifest lists them. { @@ -39,10 +58,21 @@ const providers = [ ], }, ].map( - ({ driver, models }) => + ({ + instanceId, + driver, + auth, + models, + }: { + instanceId?: string; + driver: string; + auth?: Record; + models: ReadonlyArray<{ slug: string; aliases?: ReadonlyArray }>; + }) => ({ - instanceId: ProviderInstanceId.make(driver), + instanceId: ProviderInstanceId.make(instanceId ?? driver), driver, + auth: { status: "authenticated", ...auth }, models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); @@ -336,10 +366,20 @@ describe("provider usage reporting", () => { expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); }); - it("reports Antigravity catalog models the bundled manifest does not list", () => { + it("reports vendor catalog models the bundled manifest does not list", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); expect(label("gemini-4-unlisted")).toBeUndefined(); + expect(label("gpt-6.2-sol")).toBe("gpt-6.2-sol"); + expect(label("claude-opus-6")).toBe("claude-opus-6"); + for (const hidden of [ + "nova-alpha", + "acme-azure-deployment", + "gpt-acme-finetune", + "claude-ops-internal", + ]) { + expect(label(hidden)).toBeUndefined(); + } }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { From 887e3a569ff3b72328c47efd7b17271bfcb44789 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:02:52 -0600 Subject: [PATCH 010/288] =?UTF-8?q?fix(web):=20file=20picker=20highlights?= =?UTF-8?q?=20stay=20on=20the=20typed=20letters=20after=20=C4=B0=20(#41216?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Julius Marminge --- .../files/ProjectFilePicker.logic.test.ts | 14 ++++++++++++++ .../components/files/ProjectFilePicker.logic.ts | 13 ++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts index f112ba97ab5d6..47efe8f58c44f 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts @@ -37,4 +37,18 @@ describe("getProjectFilePickerMatches", () => { [0, 1, 2], ); }); + + it("maps highlights back to original characters when lowercasing expands them", () => { + const entries = [{ kind: "file", path: "icons/İ-logo.svg" }] as const; + const indices = (query: string) => { + const match = getProjectFilePickerMatches(entries, query)[0]; + return [match?.nameMatchIndices, match?.pathMatchIndices]; + }; + + assert.deepEqual(indices("logo"), [ + [2, 3, 4, 5], + [8, 9, 10, 11], + ]); + assert.deepEqual(indices("İ"), [[0], [0, 6]]); + }); }); diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.ts b/apps/web/src/components/files/ProjectFilePicker.logic.ts index 87fa4212eb384..a19e8b4a1e8d5 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.ts @@ -19,12 +19,23 @@ function findMatchIndices(value: string, query: string): number[] | null { if (!query) return []; const normalizedValue = value.toLowerCase(); + // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back. + const sourceSpans: Array = []; + if (normalizedValue.length !== value.length) { + let sourceOffset = 0; + for (const char of value) { + const span = [sourceOffset, sourceOffset + char.length] as const; + for (let n = char.toLowerCase().length; n > 0; n -= 1) sourceSpans.push(span); + sourceOffset = span[1]; + } + } const indices: number[] = []; let queryIndex = 0; for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) { if (normalizedValue[valueIndex] !== query[queryIndex]) continue; - indices.push(valueIndex); + const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1]; + for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); queryIndex += 1; if (queryIndex === query.length) return indices; } From 58aa80dcdf98594a2f98ee04b331ae23ca461fa3 Mon Sep 17 00:00:00 2001 From: miley Date: Mon, 23 Nov 2026 07:05:59 +0200 Subject: [PATCH 011/288] fix(server): T3's own git commands no longer start Git's auto maintenance (#41200) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 5 ++++- apps/server/src/vcs/GitVcsDriverCore.ts | 17 +++-------------- apps/server/src/vcs/VcsProcess.ts | 18 +++++++++++++++++- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b3ad640db4c7a..d64c0ec5cbb5b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6053,7 +6053,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { fetch: "statusDetailsRemote" }, // Storage cleanup's merge check fetches the default branch on every sweep. { fetch: "fetchRemoteTrackingBranch" }, - ] as const)("does not start Git auto-maintenance from background $fetch fetches", ({ fetch }) => + // Startup pulls each project's default branch. + { fetch: "pullCurrentBranch" }, + ] as const)("does not start Git auto-maintenance from $fetch", ({ fetch }) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -6079,6 +6081,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const driver = yield* GitVcsDriver.GitVcsDriver; if (fetch === "statusDetailsRemote") yield* driver.statusDetailsRemote(cwd); + else if (fetch === "pullCurrentBranch") yield* driver.pullCurrentBranch(cwd); else yield* driver.fetchRemoteTrackingBranch({ cwd, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index f863f01bdb40a..9ee53e4e90ac3 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -47,11 +47,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; -import { - explicitBareRepositoryEnv, - gitConfigEnv, - unsetInheritedRepositoryEnv, -} from "./VcsProcess.ts"; +import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts"; import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; @@ -1095,7 +1091,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...input.env, ...trace2Monitor.env, }; - const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) }; + const env = { ...baseEnv, ...serverGitConfigEnv(baseEnv, hostPlatform) }; const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) }; const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); const spawnError = (cause: unknown) => @@ -1558,17 +1554,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) { const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps - // this poll from starting `git gc --auto`. When that gc fails, for example on a repository - // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*` - // behind each time, so a background poll could fill the disk. const fetchArgs = (mode: "--dry-run" | "--quiet") => [ "--git-dir", gitCommonDir, "fetch", mode, "--no-tags", - "--no-auto-gc", // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail. "--no-write-fetch-head", "--", @@ -6531,13 +6522,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchRemoteTrackingBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"] = Effect.fn("fetchRemoteTrackingBranch")(function* (input) { - // Storage cleanup runs this every sweep: like the status fetch, a killed fetch strands a - // `tmp_pack_*` and a failing `gc --auto` repeats each time, so allow time and skip gc. + // Storage cleanup runs this every sweep, and a killed fetch strands a `tmp_pack_*`. const args = [ "fetch", "--quiet", "--no-tags", - "--no-auto-gc", "--", input.remoteName, `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index 91e21e8f07a97..28b46c8c5482a 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -140,6 +140,22 @@ export const gitConfigEnv = ( export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => gitConfigEnv(env, "safe.bareRepository", "explicit", platform); +// A failing `gc --auto` (say, missing objects) reruns after every fetch and strands a full-size +// `tmp_pack_*` each time, so T3's frequent background Git calls could fill the disk. +const SERVER_GIT_CONFIG = [ + ["safe.bareRepository", "explicit"], + ["maintenance.auto", "false"], + ["gc.auto", "0"], +] as const; + +export const serverGitConfigEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => { + const added: NodeJS.ProcessEnv = {}; + for (const [key, value] of SERVER_GIT_CONFIG) { + Object.assign(added, gitConfigEnv({ ...env, ...added }, key, value, platform)); + } + return added; +}; + const REPOSITORY_SELECTORS = new Set([ "GIT_DIR", "GIT_WORK_TREE", @@ -248,7 +264,7 @@ export const make = Effect.gen(function* () { // LANGUAGE leaves LC_CTYPE, which hooks inherit, alone. ...(input.command === "git" ? { LANGUAGE: "C" } : {}), ...input.env, - ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform), + ...serverGitConfigEnv({ ...process.env, ...input.env }, hostPlatform), }, timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES, From 73bb8ece1fd03501327fe20412e13a0b73e374f8 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:08:16 -0600 Subject: [PATCH 012/288] fix(web): accept TIFF files containing standard IFD tag type 13 (SubIFDs) (#41228) Co-authored-by: Julius Marminge --- .../files/AttachmentFilePreview.browser.test.tsx | 9 +++++---- apps/web/src/components/files/imageDecode.worker.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 076f2c7ee32df..9316935ba2df0 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -499,14 +499,14 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and alpha and rejects oversized metadata before decoding", async () => { + it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs tags and rejects oversized metadata before decoding", async () => { let bytes = new ArrayBuffer(0); for (const { pixels, expected } of [ { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, ]) { const samples = pixels.length / 2; - const start = samples === 2 ? 146 : 134; + const start = samples === 2 ? 158 : 146; const tags = [ [256, 2], [257, 1], @@ -518,6 +518,7 @@ describe("bounded binary previews", () => { [278, 1], [279, pixels.length], [284, 1], + [330, 0, 13], ...(samples === 2 ? [[338, 2]] : []), ]; bytes = new ArrayBuffer(start + pixels.length); @@ -526,10 +527,10 @@ describe("bounded binary previews", () => { view.setUint16(2, 42, true); view.setUint32(4, 8, true); view.setUint16(8, tags.length, true); - tags.forEach(([tag, value], index) => { + tags.forEach(([tag, value, type = 4], index) => { const offset = 10 + index * 12; view.setUint16(offset, tag!, true); - view.setUint16(offset + 2, 4, true); + view.setUint16(offset + 2, type, true); view.setUint32(offset + 4, 1, true); view.setUint32(offset + 8, value!, true); }); diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index 9ddcfdbfb3e98..9cd3140308612 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -25,7 +25,7 @@ function validateTiffMetadata(bytes: ArrayBuffer) { const tag = view.getUint16(entry, littleEndian); const type = view.getUint16(entry + 2, littleEndian); const values = view.getUint32(entry + 4, littleEndian); - const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8][type]; + const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4][type]; if (!width) throw new PreviewError({ code: "tiff-metadata-type" }); const length = values * width; const start = length > 4 ? view.getUint32(entry + 8, littleEndian) : entry + 8; From 6cfc3bf0d55819c4395aebce96df4e9c28575795 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:11:12 -0800 Subject: [PATCH 013/288] fix(shared): reject keybindings with a dangling or extra '+' (#41231) --- apps/server/src/keybindings.test.ts | 12 ++++++++++++ packages/shared/src/keybindings.ts | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 7e846811e1440..44048330c3ae2 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -182,6 +182,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => { { key: "mod+j", command: "terminal.toggle" }, { key: "mod+shift+d+o", command: "terminal.new" }, { key: "mod+x", command: "invalid.command" }, + { key: "mod+", command: "sidebar.toggle" }, + { key: "mod+a+++", command: "sidebar.toggle" }, ]), ); @@ -205,6 +207,16 @@ it.layer(NodeServices.layer)("keybindings", (it) => { index: 2, message: configState.issues[1]?.message ?? "", }, + { + kind: "keybindings.invalid-entry", + index: 3, + message: configState.issues[2]?.message ?? "", + }, + { + kind: "keybindings.invalid-entry", + index: 4, + message: configState.issues[3]?.message ?? "", + }, ]); }).pipe(Effect.provide(layerKeybindings())), ); diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 9a67264d8bd1f..29bb71d5f6f1a 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -167,8 +167,10 @@ export function parseKeybindingShortcut(value: string): KeybindingShortcut | nul trailingEmptyCount += 1; tokens.pop(); } - if (trailingEmptyCount > 0) { + if (trailingEmptyCount === 2) { tokens.push("+"); + } else if (trailingEmptyCount !== 0) { + return null; } if (tokens.some((token) => token.length === 0)) { return null; From 12f19b83c0653f2ede65c39ef3367d2704be4230 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:12:23 -0800 Subject: [PATCH 014/288] fix(github): a remote host URL rejects no longer breaks GitHub resolution (#41232) --- .../server/gitHubRepositoryResolution.test.ts | 24 +++++++++++++++++++ .../src/server/gitHubRepositoryResolution.ts | 4 +++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts index 3447c3a1be2ab..2fd05d1dd0719 100644 --- a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts +++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts @@ -168,6 +168,30 @@ describe("gitHubApiHostForRemote", () => { ); assert.strictEqual(gitHubApiHostForRemote("git@gitlab.com:a/b.git"), null); }); + + it("ignores a secondary remote whose host is not a valid URL host", () => { + for (const url of [ + "git@nas.08:team/repo.git", + "git@08:team/repo.git", + "git@node.256:team/repo.git", + "git@[2001:db8::1]:team/repo.git", + ]) { + const remotes = [ + "origin\tgit@github.com:pingdotgg/t3code.git (fetch)", + `backup\t${url} (fetch)`, + ].join("\n"); + assert.deepStrictEqual( + resolveGitHubRepository({ + remotes, + resolved: "", + hostHint: undefined, + defaultHost: "github.com", + }), + { host: "github.com", locator: { host: "github.com", owner: "pingdotgg", name: "t3code" } }, + url, + ); + } + }); }); describe("github.com- SSH aliases", () => { diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts index e42e428d9d997..cfd36b6c02765 100644 --- a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts +++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts @@ -166,7 +166,9 @@ function apiHostForSshAlias(host: string): string | null | undefined { export function gitHubApiHostForRemote(remoteUrl: string): string | null { const remote = parseGitRemoteHost(remoteUrl); if (remote === null) return null; - const host = new URL(`https://${remote.host}`).host.toLowerCase(); + const parsed = URL.parse(`https://${remote.host}`); + if (parsed === null) return null; + const host = parsed.host.toLowerCase(); if (isSshRemoteUrl(remoteUrl)) { const aliased = apiHostForSshAlias(host); if (aliased !== undefined) return aliased; From 21e7fc1545068b9cc95ed646f080b793b15f27d8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:12:51 -0800 Subject: [PATCH 015/288] feat(scripts): a server metrics run catches CPU, memory and first-request regressions (#41159) Co-authored-by: Claude Opus 5.5 --- docs/internals/performance-regressions.md | 23 + package.json | 1 + scripts/scenarios/shell.ts | 2 +- scripts/server-metrics-report.ts | 339 ++++++ scripts/server-metrics.test.ts | 158 +++ scripts/server-metrics.ts | 1137 +++++++++++++++++++++ 6 files changed, 1659 insertions(+), 1 deletion(-) create mode 100644 scripts/server-metrics-report.ts create mode 100644 scripts/server-metrics.test.ts create mode 100644 scripts/server-metrics.ts diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 25ecabd80c5a4..e67ff30a85e6a 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -97,6 +97,29 @@ catalog digests and status deltas gets the provider list of its first config in provider with 250 slash commands and 200 skills. The lists load with the first cwd snapshot, and a machine refresh sends back an empty provider list. +## Server process metrics + +`node scripts/server-metrics.ts run --out ` starts a checkout's server against throwaway +state, a fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and +heap at rest, with quiet Claude threads and with 5 streaming, plus how long a new thread takes to +reach the API. Only the server process is measured. + +- Compare refs with `ab `, not with two files from different times. It + alternates the two on one machine, and `compare` flags a metric only when the bootstrap interval + of the median difference clears both the threshold and the noise floor. Single runs on a busy + machine differ by more than most regressions. +- Read per-thread cost from `scaling`, a fit over 5 to 20 open threads. It separates what each + open thread costs from the fixed cost of the server, which the absolute numbers mix. +- `--soak ` reports heap and RSS slopes in MB per hour and the constructors that grew. + A rising heap floor is a leak; a high but flat one is not. +- The quiet and streaming windows save a CPU and an allocation profile, so a regression comes with + the functions that cost it. + +Run it on macOS and Windows too, and on Linux with `--no-agent-scope`. Only Linux has agent +scopes, so other platforms take per-process paths a Linux server with a systemd user manager never +runs. A one-second `ps -A` poll per Claude session cost 0.1.11 about 18% of a core with 20 open +threads on macOS and went unnoticed on Linux. + ## Event store and startup Sequence cursors must seek an index rather than scan retained history. The application sequence diff --git a/package.json b/package.json index 9f1d2bee11b58..190d7e25cc3ec 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "tc": "vp run -r --cache --concurrency-limit 4 typecheck", "check:changed": "node scripts/check-changed.ts", "report:renders": "node scripts/render-metrics.ts", + "report:server": "node scripts/server-metrics.ts", "lint": "vp lint --report-unused-disable-directives", "i18n:untranslated": "node scripts/i18n-untranslated.ts", "knip": "knip --preprocessor ./scripts/knip-schemas.ts", diff --git a/scripts/scenarios/shell.ts b/scripts/scenarios/shell.ts index 40e3b224fa694..32adbe1920a8c 100644 --- a/scripts/scenarios/shell.ts +++ b/scripts/scenarios/shell.ts @@ -52,7 +52,7 @@ export const run = Effect.fn("scenario.run")( ); if (!(options.allowExit ?? [0]).includes(exitCode)) { return yield* new ScenarioError({ - message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${stderr.trim().slice(-600)}`, + message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${(stderr.trim() || stdout.trim()).slice(-600)}`, }); } return { stdout, stderr, exitCode: Number(exitCode) }; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts new file mode 100644 index 0000000000000..c024e9737ef46 --- /dev/null +++ b/scripts/server-metrics-report.ts @@ -0,0 +1,339 @@ +// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare. +import * as Schema from "effect/Schema"; + +const Window = Schema.Struct({ + cpuPct: Schema.Number, + wakeupsPerSec: Schema.NullOr(Schema.Number), + rssPeakMB: Schema.Number, + rssMB: Schema.Number, + heapAfterGcMB: Schema.Number, +}); +export type Window = typeof Window.Type; +const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number }); +const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread }); +export type FirstWord = typeof FirstWord.Type; +const Scaling = Schema.Struct({ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + wakeupsPerThread: Schema.NullOr(Schema.Number), + /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ + points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))), +}); +const Soak = Schema.Struct({ + minutes: Schema.Number, + heapMBPerHour: Schema.Number, + rssMBPerHour: Schema.Number, +}); + +/** One pass over the scenarios. */ +export const Measured = Schema.Struct({ + startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), + rest: Schema.optional(Window), + firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), + quiet: Schema.optional(Window), + scaling: Schema.optional(Scaling), + streaming: Schema.optional(Window), + soak: Schema.optional(Soak), +}); +export type Measured = typeof Measured.Type; + +const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number }); +export type Hotspot = typeof Hotspot.Type; +const ProfileSummary = Schema.Struct({ + cpuMs: Schema.Array(Hotspot), + allocatedMB: Schema.Array(Hotspot), +}); +export type ProfileSummary = typeof ProfileSummary.Type; +export const HeapGrowth = Schema.Struct({ + constructor: Schema.String, + count: Schema.Number, + MB: Schema.Number, +}); + +export const ServerMetrics = Schema.Struct({ + meta: Schema.Record( + Schema.String, + Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), + ), + runs: Schema.Array(Measured), + /** Top CPU self time (ms) and allocated MB by function, from the last run. */ + profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), + soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), +}); +export type ServerMetrics = typeof ServerMetrics.Type; + +export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; + +/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */ +export function parsePsCpuTime(text: string) { + const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); + if (match === null) return Number.NaN; + const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match; + return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds); +} + +/** + * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay + * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else. + */ +export function parseRunSelection(input: { + readonly only: string; + readonly threads: string; + readonly soak: number; + readonly scenarios: ReadonlyArray; +}): + | { readonly only: ReadonlyArray; readonly threads: ReadonlyArray } + | { readonly error: string } { + const only = input.only.split(",").filter(Boolean); + const unknown = only.filter((name) => !input.scenarios.includes(name)); + if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` }; + const threads = input.threads + .split(",") + .map((count) => (count.trim() === "" ? Number.NaN : Number(count))); + if ( + threads.some( + (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), + ) + ) { + return { error: "--threads takes ascending counts such as 0,5,10,20" }; + } + if (!Number.isInteger(input.soak) || input.soak < 0) + return { error: "--soak takes minutes, 0 for none" }; + return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads }; +} + +export function spread(values: ReadonlyArray) { + const sorted = values.toSorted((a, b) => a - b); + const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; + return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; +} + +/** Least-squares slope of y over x. */ +export function slope(points: ReadonlyArray) { + const n = points.length; + if (n < 2) return 0; + const mx = points.reduce((sum, [x]) => sum + x, 0) / n; + const my = points.reduce((sum, [, y]) => sum + y, 0) / n; + let numerator = 0; + let denominator = 0; + for (const [x, y] of points) { + numerator += (x - mx) * (y - my); + denominator += (x - mx) ** 2; + } + return denominator === 0 ? 0 : numerator / denominator; +} + +/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ +export function flatten(measured: Measured): Map { + const values = new Map(); + const visit = (value: unknown, path: string) => { + if (typeof value === "number") values.set(path, value); + else if (value && typeof value === "object") { + for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); + } + }; + visit(measured, ""); + return values; +} + +function noiseFloor(metric: string) { + if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; + if (metric.startsWith("soak.")) return 20; + if (metric.endsWith("cpuPct")) return 1; + if (metric.endsWith("wakeupsPerSec")) return 20; + if (metric.endsWith("MB")) return 15; + return 300; +} + +const median = (values: ReadonlyArray) => { + const sorted = values.toSorted((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +}; + +/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ +export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyArray) { + let seed = 0x5eed; + const random = () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; + const resample = (values: ReadonlyArray) => + median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); + const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( + (x, y) => x - y, + ); + return [differences[49]!, differences[1_949]!] as const; +} + +export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { + const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); + } + } + return values; + }; + const a = collect(before); + const b = collect(after); + const lines = [ + "### Server metrics (lower is better)", + "", + `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, + "", + "| metric | before | after | change | 95% interval | |", + "| :-- | --: | --: | --: | --: | :-- |", + ]; + const regressed: string[] = []; + const improved: string[] = []; + let compared = 0; + for (const metric of new Set([...a.keys(), ...b.keys()])) { + if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; + const x = a.get(metric); + const y = b.get(metric); + if (!x || !y) { + lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); + continue; + } + compared++; + const mx = median(x); + const my = median(y); + // A change counts only past both the relative threshold and the absolute noise floor. + const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const repeated = x.length > 1 && y.length > 1; + const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; + const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; + if (verdict === "worse") regressed.push(metric); + if (verdict === "better") improved.push(metric); + const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; + const shown = Number.isFinite(percent) + ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` + : "new"; + const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : ""; + lines.push( + `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, + ); + } + return { table: lines.join("\n"), regressed, improved, compared }; +} + +const CallFrame = Schema.Struct({ + functionName: Schema.String, + url: Schema.String, + lineNumber: Schema.Number, +}); +type CallFrame = typeof CallFrame.Type; +export const CpuProfile = Schema.Struct({ + nodes: Schema.Array( + Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }), + ), + samples: Schema.optional(Schema.Array(Schema.Number)), + startTime: Schema.Number, + endTime: Schema.Number, +}); +interface HeapProfileNode { + readonly callFrame: CallFrame; + readonly selfSize: number; + readonly children: ReadonlyArray; +} +const HeapProfileNode: Schema.Codec = Schema.Struct({ + callFrame: CallFrame, + selfSize: Schema.Number, + children: Schema.Array(Schema.suspend(() => HeapProfileNode)), +}); +export const HeapProfile = Schema.Struct({ head: HeapProfileNode }); + +const shortUrl = (url: string) => + url + .replace(/^file:\/\//, "") + .split(/[\\/]/) + .slice(-3) + .join("/"); +const frameName = (frame: CallFrame) => + `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); +const top = (totals: Map, digits: number): Hotspot[] => + [...totals] + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([frame, value]) => ({ frame, value: round(value, digits) })); + +/** Top CPU self time in ms and allocated MB, by function. */ +export function summarizeProfiles( + cpu: typeof CpuProfile.Type, + heap: typeof HeapProfile.Type, +): ProfileSummary { + const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); + const cpuTotals = new Map(); + for (const node of cpu.nodes) { + if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; + const name = frameName(node.callFrame); + cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); + } + const allocations = new Map(); + const visit = (node: HeapProfileNode) => { + const name = frameName(node.callFrame); + allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); + for (const child of node.children) visit(child); + }; + visit(heap.head); + return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; +} + +export const HeapSnapshot = Schema.Struct({ + snapshot: Schema.Struct({ + meta: Schema.Struct({ + node_fields: Schema.Array(Schema.String), + node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + }), + }), + nodes: Schema.Array(Schema.Number), + strings: Schema.Array(Schema.String), +}); + +/** Self size by constructor from a V8 heap snapshot. */ +export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { + const fields = snapshot.snapshot.meta.node_fields; + const typeNames = snapshot.snapshot.meta.node_types[0]; + const types = Array.isArray(typeNames) ? typeNames : []; + const typeAt = fields.indexOf("type"); + const nameAt = fields.indexOf("name"); + const sizeAt = fields.indexOf("self_size"); + const totals = new Map(); + for (let index = 0; index < snapshot.nodes.length; index += fields.length) { + const type = types[snapshot.nodes[index + typeAt]!] ?? "?"; + const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? ""; + const name = + type === "object" + ? label.slice(0, 80) + : type === "closure" + ? `(closure) ${label.slice(0, 60)}` + : `(${type.replace(/^(concatenated|sliced) /, "")})`; + const entry = totals.get(name) ?? { count: 0, bytes: 0 }; + entry.count++; + entry.bytes += snapshot.nodes[index + sizeAt]!; + totals.set(name, entry); + } + return totals; +} + +/** The constructors whose heap grew most from one snapshot to the next. */ +export function heapGrowth( + before: ReturnType, + after: ReturnType, +) { + return [...after] + .map(([name, { count, bytes }]) => ({ + constructor: name, + count: count - (before.get(name)?.count ?? 0), + bytes: bytes - (before.get(name)?.bytes ?? 0), + })) + .filter((entry) => entry.bytes > 0) + .toSorted((a, b) => b.bytes - a.bytes) + .slice(0, 25) + .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts new file mode 100644 index 0000000000000..fe87cbbd39c68 --- /dev/null +++ b/scripts/server-metrics.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + compareMetrics, + heapGrowth, + parsePsCpuTime, + parseRunSelection, + slope, + type ServerMetrics, +} from "./server-metrics-report.ts"; + +type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; +const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; +const quietRuns = (...runs: Quiet[]) => + ({ + meta, + runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })), + }) satisfies ServerMetrics; +const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; +const cpuRuns = (...values: number[]) => + quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); + +describe("compareMetrics", () => { + it.each([ + ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], + ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, [], []], + ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, [], []], + ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"], []], + [ + "an improvement past the floors", + { cpuPct: 0.1, wakeupsPerSec: 7, rssPeakMB: 400 }, + [], + ["quiet.rssPeakMB"], + ], + ])("one run each: %s", (_name, change, regressed, improved) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); + }); + + it("shows a metric missing on one side as n/a, not as a change", () => { + const before = quietRuns({ ...base, wakeupsPerSec: null }); + const result = compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 50 })); + expect(result.regressed).toEqual([]); + expect(result.table).toContain("| quiet.wakeupsPerSec | – | 50 | n/a | | |"); + }); + + it("flags repeated runs only when the whole interval clears the limit", () => { + const steady = cpuRuns(26.1, 27.4, 25.8); + const fixed = cpuRuns(2.2, 2.5, 2.1); + expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + // The medians differ by 2.8 points, past the floor, but a resampled median can match. + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + }); + + it("counts how many metrics both sides share", () => { + const startupOnly: ServerMetrics = { meta, runs: [{ startup: { readyMs: 9_000 } }] }; + expect(compareMetrics(startupOnly, quietRuns(base)).compared).toBe(0); + expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(5); + }); +}); + +describe("heapGrowth", () => { + it("lists only constructors that grew, small growth included", () => { + const before = new Map([ + ["Shrank", { count: 10, bytes: 5_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 1, bytes: 1_000 }], + ]); + const after = new Map([ + ["Shrank", { count: 5, bytes: 1_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 2, bytes: 1_500 }], + ["New", { count: 4, bytes: 3_000_000 }], + ]); + expect(heapGrowth(before, after)).toEqual([ + { constructor: "New", count: 4, MB: 3 }, + { constructor: "Grew", count: 1, MB: 0 }, + ]); + }); +}); + +describe("slope", () => { + it("fits the cost per thread", () => { + const points: Array = [ + [0, 175], + [5, 180], + [10, 185], + [20, 195], + ]; + expect(slope(points)).toBeCloseTo(1); + }); +}); + +describe("parsePsCpuTime", () => { + it.each([ + ["0:00.00", 0], + ["1:02.50", 62.5], + ["1:00:00.00", 3600], + ["2-01:00:00", 2 * 86_400 + 3600], + ["1-02:03", Number.NaN], + ["::", Number.NaN], + ["", Number.NaN], + ["1:2:3:4", Number.NaN], + ])("%s", (text, seconds) => { + expect(parsePsCpuTime(text)).toBe(seconds); + }); +}); + +describe("parseRunSelection", () => { + const scenarios = ["rest", "quiet", "streaming"]; + it.each([ + [ + "the default thread counts", + { only: "", threads: "0,5,10,20", soak: 0 }, + { only: [], threads: [0, 5, 10, 20] }, + ], + [ + "descending thread counts", + { only: "", threads: "5,20,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "an empty thread count", + { only: "", threads: "0,,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "named scenarios", + { only: "rest,quiet", threads: "0", soak: 0 }, + { only: ["rest", "quiet"], threads: [0] }, + ], + [ + "an unknown scenario", + { only: "rest,idle", threads: "0", soak: 0 }, + { error: "unknown scenario: idle" }, + ], + ["a soak alone", { only: "", threads: "0", soak: 10 }, { only: ["none"], threads: [0] }], + [ + "a soak with scenarios", + { only: "rest", threads: "0", soak: 10 }, + { only: ["rest"], threads: [0] }, + ], + [ + "a negative soak", + { only: "", threads: "0", soak: -1 }, + { error: "--soak takes minutes, 0 for none" }, + ], + [ + "an infinite soak", + { only: "", threads: "0", soak: Number.POSITIVE_INFINITY }, + { error: "--soak takes minutes, 0 for none" }, + ], + ])("%s", (_name, input, expected) => { + expect(parseRunSelection({ ...input, scenarios })).toEqual(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts new file mode 100644 index 0000000000000..3a9887f40f5fb --- /dev/null +++ b/scripts/server-metrics.ts @@ -0,0 +1,1137 @@ +#!/usr/bin/env node +// Measures a checkout's server process (CPU, wakeups, memory, time to the API) against a fake +// Anthropic API and the real `claude` CLI. See docs/internals/performance-regressions.md. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http server. +import * as NodeHttp from "node:http"; + +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Random from "effect/Random"; +import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Argument, Command, Flag } from "effect/cli"; +import { HttpClient, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as Socket from "effect/socket/Socket"; + +import { run } from "./scenarios/shell.ts"; +import { + compareMetrics, + CpuProfile, + HeapProfile, + HeapSnapshot, + heapByConstructor, + heapGrowth, + round, + ServerMetrics, + slope, + spread, + parsePsCpuTime, + parseRunSelection, + summarizeProfiles, + type FirstWord, + type Measured, + type ProfileSummary, + type Window, +} from "./server-metrics-report.ts"; + +const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); +const MODEL = "claude-haiku-4-5"; +const SLOW_MARKER = "[[stream-slowly]]"; + +export class MetricsError extends Schema.TaggedError()("MetricsError", { + message: Schema.String, +}) {} + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeJson = (schema: S) => + Schema.decodeUnknownEffect(Schema.fromJsonString(schema)); +const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(ServerMetrics)); + +/** What a command printed, or none when it is missing or failed. */ +const output = (program: string, args: ReadonlyArray, cwd?: string) => + run(program, args, cwd === undefined ? {} : { cwd }).pipe( + Effect.map(({ stdout }) => stdout.trim()), + Effect.option, + ); +const powershell = (script: string) => + output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); + +/** Milliseconds on a monotonic clock, for intervals only. */ +const nowMs = Effect.map(Clock.monotonicTimeNanos, (nanos) => Number(nanos) / 1e6); + +const httpServerOn = (port: number) => + NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" }); + +interface ApiRequest { + readonly at: number; + readonly agent: boolean; + readonly stream: boolean; + readonly marker: string | undefined; +} + +const MessagesRequest = Schema.Struct({ + stream: Schema.optional(Schema.Boolean), + model: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Array(Schema.Unknown)), +}); + +/** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ +const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { + const requests: ApiRequest[] = []; + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.url.includes("count_tokens")) { + return HttpServerResponse.jsonUnsafe({ input_tokens: 100 }); + } + if (!request.url.startsWith("/v1/messages")) { + return HttpServerResponse.jsonUnsafe( + { type: "error", error: { type: "not_found_error" } }, + { status: 404 }, + ); + } + const raw = yield* request.text.pipe(Effect.orElseSucceed(() => "")); + const body = yield* decodeJson(MessagesRequest)(raw).pipe( + Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), + ); + const streamed = body.stream === true; + requests.push({ + at: yield* nowMs, + stream: streamed, + // Title and branch-name jobs carry only their structured-output tool; the agent carries many. + agent: streamed && (body.tools?.length ?? 0) > 1, + marker: /bench-run-(\d+)/.exec(raw)?.[0], + }); + const model = body.model ?? MODEL; + const id = `msg_bench_${requests.length}`; + if (!streamed) { + return HttpServerResponse.jsonUnsafe({ + id, + type: "message", + role: "assistant", + model, + content: [{ type: "text", text: "Bench reply" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 2 }, + }); + } + const event = (name: string, data: object) => + `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; + const slow = raw.includes(SLOW_MARKER); + const words = slow ? 2_000 : 40; + const deltas = Stream.range(0, words - 1).pipe( + Stream.mapEffect((word) => + Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.as( + event("content_block_delta", { + index: 0, + delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` }, + }), + ), + ), + ), + ); + const events = Stream.make( + event("message_start", { + message: { + id, + type: "message", + role: "assistant", + model, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 100, output_tokens: 1 }, + }, + }), + event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), + ).pipe( + Stream.concat(deltas), + Stream.concat( + Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + event("message_stop", {}), + ), + ), + Stream.encodeText, + ); + return HttpServerResponse.stream(events, { + contentType: "text/event-stream", + headers: { "cache-control": "no-cache" }, + }); + }); + // Each run gets its own listener, closed with the run's scope. + const context = yield* Layer.build(httpServerOn(0)); + return yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + if (address._tag === "UnixPathAddress") { + return yield* new MetricsError({ message: "the fake API has no TCP address" }); + } + return { port: address.port, requests }; + }).pipe(Effect.provide(context)); +}); + +/** A Chrome DevTools Protocol session on the server's inspector. */ +const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { + const socket = yield* Socket.makeWebSocket(url); + const reader = yield* socket.reader; + const writer = yield* socket.writer; + const pending = new Map< + number, + { method: string; answer: Deferred.Deferred } + >(); + const chunks: string[] = []; + let nextId = 0; + let closed = false; + const decodeMessage = decodeJson( + Schema.Struct({ + id: Schema.optional(Schema.Number), + result: Schema.optional(Schema.Unknown), + error: Schema.optional(Schema.Struct({ message: Schema.String })), + method: Schema.optional(Schema.String), + params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })), + }), + ); + const text = new TextDecoder(); + yield* reader.pull.pipe( + Effect.flatMap((frames) => + Effect.forEach(frames, (frame) => + decodeMessage(typeof frame === "string" ? frame : text.decode(frame)).pipe( + Effect.flatMap((message) => { + if (message.id !== undefined) { + const waiting = pending.get(message.id); + pending.delete(message.id); + if (!waiting) return Effect.void; + return message.error + ? Deferred.fail( + waiting.answer, + new MetricsError({ message: `${waiting.method}: ${message.error.message}` }), + ) + : Deferred.succeed(waiting.answer, message.result); + } + if (message.method === "HeapProfiler.addHeapSnapshotChunk") { + chunks.push(message.params?.chunk ?? ""); + } + return Effect.void; + }), + Effect.ignore, + ), + ), + ), + Effect.forever, + Effect.ignore, + // A closed connection answers nothing, so every waiting call fails instead of hanging. + Effect.ensuring( + Effect.suspend(() => { + closed = true; + const waiting = [...pending.values()]; + pending.clear(); + return Effect.forEach(waiting, ({ method, answer }) => + Deferred.fail(answer, new MetricsError({ message: `${method}: the inspector closed` })), + ); + }), + ), + Effect.forkScoped, + ); + const send = Effect.fn("serverMetrics.cdp")(function* (method: string, params: object = {}) { + if (closed) return yield* new MetricsError({ message: `${method}: the inspector closed` }); + const id = ++nextId; + const answer = yield* Deferred.make(); + pending.set(id, { method, answer }); + yield* writer.write(encodeJson({ id, method, params })); + return yield* Deferred.await(answer); + }); + const decodeHeapUsage = Schema.decodeUnknownEffect(Schema.Struct({ usedSize: Schema.Number })); + const decodeEvaluated = Schema.decodeUnknownEffect( + Schema.Struct({ result: Schema.Struct({ value: Schema.Number }) }), + ); + const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile })); + const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile })); + return { + // getrusage keeps the switches of threads that already exited, unlike per-thread counters. + contextSwitches: send("Runtime.evaluate", { + expression: + "(() => { const u = process.resourceUsage(); return u.voluntaryContextSwitches + u.involuntaryContextSwitches; })()", + returnByValue: true, + }).pipe( + Effect.flatMap(decodeEvaluated), + Effect.map(({ result }) => result.value), + ), + heapAfterGc: Effect.gen(function* () { + yield* send("HeapProfiler.collectGarbage"); + yield* send("HeapProfiler.collectGarbage"); + return (yield* decodeHeapUsage(yield* send("Runtime.getHeapUsage"))).usedSize; + }), + profile: Effect.fn("serverMetrics.profile")(function* (seconds: number) { + yield* send("Profiler.enable"); + yield* send("Profiler.setSamplingInterval", { interval: 1_000 }); + yield* send("Profiler.start"); + yield* send("HeapProfiler.startSampling", { + samplingInterval: 32_768, + includeObjectsCollectedByMajorGC: true, + includeObjectsCollectedByMinorGC: true, + }); + yield* Effect.sleep(Duration.seconds(seconds)); + const heap = yield* send("HeapProfiler.stopSampling"); + const cpu = yield* send("Profiler.stop"); + yield* send("Profiler.disable"); + return { + summary: summarizeProfiles( + (yield* decodeCpuProfile(cpu)).profile, + (yield* decodeHeapProfile(heap)).profile, + ), + raw: { cpu, heap }, + }; + }), + snapshot: Effect.gen(function* () { + chunks.length = 0; + yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); + const json = chunks.join(""); + chunks.length = 0; + return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + }), + }; +}); + +/** CPU seconds and RSS bytes of one process; a failed or unreadable probe fails the window. */ +const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { + const platform = yield* HostProcess.Platform; + const checked = (cpuSeconds: number, rss: number, probe: string) => + Number.isFinite(cpuSeconds) && Number.isFinite(rss) + ? Effect.succeed({ cpuSeconds, rss }) + : Effect.fail(new MetricsError({ message: `could not read process ${pid}: ${probe}` })); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const stat = (yield* fs.readFileString(`/proc/${pid}/stat`)).split(") ")[1]?.split(" ") ?? []; + const status = yield* fs.readFileString(`/proc/${pid}/status`); + const rss = /VmRSS:\s+(\d+)/.exec(status)?.[1]; + return yield* checked( + (Number(stat[11]) + Number(stat[12])) / 100, + rss === undefined ? Number.NaN : Number(rss) * 1024, + "/proc", + ); + } + if (platform === "win32") { + const line = yield* powershell( + `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, + ); + const [cpu = "", rss = ""] = Option.getOrElse(line, () => "").split(/\s+/); + return yield* checked( + cpu ? Number(cpu) : Number.NaN, + rss ? Number(rss) : Number.NaN, + "Get-Process", + ); + } + const line = yield* output("ps", ["-o", "rss=,time=", "-p", `${pid}`]); + const [rss = "", time = ""] = Option.getOrElse(line, () => "") + .split(/\s+/) + .filter(Boolean); + return yield* checked(parsePsCpuTime(time), rss ? Number(rss) * 1024 : Number.NaN, "ps"); +}); + +/** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ +const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { + const platform = yield* HostProcess.Platform; + const children = new Map(); + const add = (child: number, parent: number) => + children.set(parent, [...(children.get(parent) ?? []), child]); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const parent = Number(stat.split(") ")[1]?.split(" ")[1]); + if (parent) add(Number(entry), parent); + } + } else if (platform === "darwin") { + const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); + for (const line of Option.getOrElse(table, () => "").split("\n")) { + const [child, parent] = line.trim().split(/\s+/).map(Number); + if (child && parent) add(child, parent); + } + } else return []; + const found: number[] = []; + const pending = [pid]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + for (const child of children.get(next) ?? []) { + found.push(child); + pending.push(child); + } + } + return found; +}); + +interface Environment { + readonly home: string; + readonly apiPort: number; + readonly requests: ReadonlyArray; + readonly noAgentScope: boolean; + readonly serverDir: string; +} + +/** A free loopback port: bind 0, read it, let it go. */ +const freePort = Effect.scoped( + Effect.gen(function* () { + const context = yield* Layer.build(httpServerOn(0)); + const { address } = Context.get(context, HttpServer.HttpServer); + return address._tag === "UnixPathAddress" ? 0 : address.port; + }), +); + +/** A fresh server with its own base dir and git project, stopped when the scope closes. */ +const startServer = Effect.fn("serverMetrics.startServer")(function* ( + environment: Environment, + name: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const http = yield* HttpClient.HttpClient; + const platform = yield* HostProcess.Platform; + const node = yield* HostProcess.ExecutablePath; + const hostEnvironment = yield* HostProcess.Environment; + const directory = yield* fs.makeTempDirectory({ + directory: environment.home, + prefix: `${name}-`, + }); + const project = path.join(directory, "project"); + yield* fs.makeDirectory(project); + yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); + for (const args of [ + ["init", "-q", "-b", "main"], + ["add", "."], + ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], + ]) { + yield* run("git", args, { cwd: project }); + } + const baseDir = path.join(directory, "base"); + // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. + yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); + yield* fs.writeFileString( + path.join(baseDir, "userdata/settings.json"), + encodeJson({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), + ); + const dropped = new Set([ + "ANTHROPIC_AUTH_TOKEN", + "T3CODE_HOME", + "CLAUDE_CONFIG_DIR", + ...(environment.noAgentScope ? ["XDG_RUNTIME_DIR"] : []), + ]); + const env: Record = { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined && !dropped.has(entry[0]), + ), + ), + HOME: environment.home, + USERPROFILE: environment.home, + ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.apiPort}`, + ANTHROPIC_API_KEY: "sk-bench", + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", + OTEL_SDK_DISABLED: "true", + T3CODE_DEV_SEED: "0", + }; + const port = yield* freePort; + const started = yield* nowMs; + const child = yield* spawner.spawn( + ChildProcess.make( + node, + [ + "--inspect=127.0.0.1:0", + "src/bin.ts", + "serve", + "--base-dir", + baseDir, + "--port", + `${port}`, + "--host", + "127.0.0.1", + project, + ], + { + cwd: environment.serverDir, + env, + extendEnv: false, + // A server that ignores SIGTERM still stops, so cleanup always reaches the temp dir. + forceKillAfter: Duration.seconds(10), + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + }, + ), + ); + const pid = Number(child.pid); + const stderr = yield* Ref.make(""); + yield* child.stderr.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => Ref.update(stderr, (text) => (text + chunk).slice(-8_000))), + Effect.ignore, + Effect.forkScoped, + ); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const spawned = yield* descendantsOf(pid).pipe(Effect.orElseSucceed(() => [])); + if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]); + else + yield* child + .kill({ killSignal: "SIGTERM", forceKillAfter: Duration.seconds(10) }) + .pipe(Effect.timeout(Duration.seconds(15)), Effect.ignore); + yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore); + if (spawned.length > 0) yield* output("kill", ["-9", ...spawned.map(String)]); + // Windows keeps a file locked for a moment after its process exits. + yield* fs + .remove(directory, { recursive: true }) + .pipe(Effect.retry({ schedule: Schedule.spaced(Duration.millis(500)), times: 20 })); + }).pipe(Effect.ignore), + ); + + const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe( + Effect.timeout(Duration.seconds(1)), + Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }), + Effect.andThen(nowMs), + Effect.map((now) => Math.round(now - started)), + Effect.catch(() => + Effect.flatMap( + Ref.get(stderr), + (text) => new MetricsError({ message: `server never answered:\n${text}` }), + ), + ), + ); + const inspectorUrl = /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(yield* Ref.get(stderr))?.[0]; + if (!inspectorUrl) return yield* new MetricsError({ message: "no inspector URL on stderr" }); + const devtools = yield* inspect(inspectorUrl); + + const cli = (args: ReadonlyArray) => + run(node, ["src/bin.ts", ...args, "--base-dir", baseDir], { + cwd: environment.serverDir, + env, + allowExit: [0, 1, 2], + }); + const added = yield* cli(["project", "add", project]); + if (added.exitCode !== 0) { + return yield* new MetricsError({ + message: `project add failed: ${added.stderr.trim() || added.stdout.trim()}`, + }); + } + + // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. + const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000); + const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) { + // Each counter is divided by the time between its own two reads; a CIM probe can take seconds. + // Windows reports no context switches through getrusage, so wakeups are unknown there. + const countSwitches = platform === "win32" ? Effect.succeed(null) : devtools.contextSwitches; + // A probe can take seconds (CIM on Windows), so each read is timed at its midpoint. + const timed = Effect.fn("serverMetrics.timedRead")(function* ( + read: Effect.Effect, + ) { + const before = yield* nowMs; + const value = yield* read; + return { value, at: (before + (yield* nowMs)) / 2 }; + }); + const firstSwitches = yield* timed(countSwitches); + const firstSample = yield* timed(sample(pid)); + const first = firstSample.value; + const start = firstSample.at; + let rssPeak = first.rss; + while ((yield* nowMs) - start < seconds * 1_000) { + yield* Effect.sleep(sampleEvery); + rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss); + } + const lastSample = yield* timed(sample(pid)); + const last = lastSample.value; + const cpuElapsed = (lastSample.at - start) / 1_000; + const lastSwitches = yield* timed(countSwitches); + const switchesElapsed = (lastSwitches.at - firstSwitches.at) / 1_000; + const switches = + firstSwitches.value === null || lastSwitches.value === null + ? null + : lastSwitches.value - firstSwitches.value; + const heap = yield* devtools.heapAfterGc; + const window: Window = { + cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), + wakeupsPerSec: switches === null ? null : round(switches / switchesElapsed), + rssPeakMB: Math.round(Math.max(rssPeak, last.rss) / 1e6), + rssMB: Math.round((yield* sample(pid)).rss / 1e6), + heapAfterGcMB: round(heap / 1e6), + }; + return window; + }); + + return { + readyMs, + measure, + profile: devtools.profile, + snapshot: devtools.snapshot, + threadStart: (message: string, extra: ReadonlyArray = []) => + cli([ + "thread", + "start", + "--provider", + "claudeAgent", + "--model", + MODEL, + ...extra, + project, + message, + ]), + threadSend: (threadId: string, message: string) => + cli(["thread", "send", "--wait", threadId, message]), + }; +}); + +type Server = Effect.Success>; + +const firstWord = Effect.fn("serverMetrics.firstWord")(function* ( + environment: Environment, + server: Server, + runs: number, + worktree: boolean, +) { + const toRequest: number[] = []; + const toDone: number[] = []; + for (let index = 0; index < runs; index++) { + const marker = `bench-run-${worktree ? 1000 + index : index}`; + const started = yield* nowMs; + const result = yield* server.threadStart(`Say hello. ${marker}`, [ + "--wait", + ...(worktree ? ["--worktree", "main"] : []), + ]); + const done = (yield* nowMs) - started; + if (result.exitCode !== 0) { + return yield* new MetricsError({ + message: `thread start failed: ${result.stderr.trim() || result.stdout.trim()}`, + }); + } + const request = environment.requests.find( + (entry) => entry.agent && entry.marker === marker && entry.at >= started, + ); + if (!request) { + return yield* new MetricsError({ message: `the agent request for ${marker} never arrived` }); + } + toRequest.push(request.at - started); + toDone.push(done); + } + const result: FirstWord = { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; + return result; +}); + +/** Starts threads that each answer once, and returns their ids. */ +const openThreads = Effect.fn("serverMetrics.openThreads")(function* ( + server: Server, + from: number, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => from + index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait"]), + { concurrency: "unbounded" }, + ); + const failed = answers.find((answer) => answer.exitCode !== 0); + if (failed) { + return yield* new MetricsError({ + message: `a thread failed to answer: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + // Without --json, `thread start` prints the new thread's id to stderr, older releases too. + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + if (ids.some((id) => id === undefined)) { + return yield* new MetricsError({ message: "thread start printed no thread id" }); + } + return ids.filter((id) => id !== undefined); +}); + +const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; + +interface RunOptions { + readonly checkout: string; + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: ReadonlyArray; + readonly only: ReadonlyArray; + readonly soakMinutes: number; + /** Where full CPU and allocation profiles go; none are written without it. */ + readonly profileDir: string | undefined; +} + +/** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ +const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); + const api = yield* serveFakeAnthropic(); + const environment: Environment = { + home, + apiPort: api.port, + requests: api.requests, + noAgentScope: options.noAgentScope, + serverDir: path.join(options.checkout, "apps/server"), + }; + const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); + const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; + const profiles: Record = {}; + let soakHeapGrowth: ReturnType | undefined; + const withServer = (name: string, body: (server: Server) => Effect.Effect) => + Effect.scoped(Effect.flatMap(startServer(environment, name), body)); + const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { + const { summary, raw } = yield* server.profile(20); + profiles[name] = summary; + if (options.profileDir === undefined) return; + yield* fs.makeDirectory(options.profileDir, { recursive: true }); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.cpuprofile`), + encodeJson(raw.cpu), + ); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.heapprofile`), + encodeJson(raw.heap), + ); + }); + + if (wanted("startup") || wanted("rest") || wanted("firstWord")) { + yield* withServer("rest", (server) => + Effect.gen(function* () { + measured.startup = { readyMs: server.readyMs }; + if (wanted("rest")) { + yield* Effect.sleep(Duration.seconds(15)); + measured.rest = yield* server.measure(30); + } + if (wanted("firstWord")) { + measured.firstWord = { + inPlace: yield* firstWord(environment, server, options.runs, false), + worktree: yield* firstWord(environment, server, options.runs, true), + }; + } + }), + ); + } + if (wanted("quiet")) { + yield* withServer("quiet", (server) => + Effect.gen(function* () { + const points: Array<{ threads: number; window: Window }> = []; + let open = 0; + for (const threads of options.threads) { + if (threads > open) yield* openThreads(server, open, threads - open); + open = Math.max(open, threads); + yield* Effect.sleep(Duration.seconds(15)); + points.push({ threads, window: yield* server.measure(30) }); + } + const last = points.at(-1); + if (last) measured.quiet = last.window; + // The first thread also loads the provider's modules once, so the fit leaves out 0 threads. + const withThreads = points.filter(({ threads }) => threads > 0); + const fitted = withThreads.length >= 2 ? withThreads : points; + const fit = (pick: (window: Window) => number) => + round(slope(fitted.map(({ threads, window }) => [threads, pick(window)])), 3); + measured.scaling = { + heapMBPerThread: fit((window) => window.heapAfterGcMB), + rssMBPerThread: fit((window) => window.rssMB), + cpuPctPerThread: fit((window) => window.cpuPct), + wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null) + ? fit((window) => window.wakeupsPerSec ?? 0) + : null, + points: points.map(({ threads, window }) => [ + threads, + window.cpuPct, + window.wakeupsPerSec, + window.rssMB, + window.heapAfterGcMB, + ]), + }; + yield* profile(server, "quiet"); + }), + ); + } + if (wanted("streaming")) { + yield* withServer("streaming", (server) => + Effect.gen(function* () { + // Earlier scenarios share the fake API, so only this launch's requests count. + const markers = [0, 1, 2, 3, 4].map((index) => `bench-run-${9_000 + index}`); + const launchedAt = yield* nowMs; + const started = yield* Effect.forEach( + markers, + (marker) => server.threadStart(`Write a long answer. ${SLOW_MARKER} ${marker}`), + { concurrency: "unbounded" }, + ); + if (started.some((answer) => answer.exitCode !== 0)) { + return yield* new MetricsError({ message: "streaming start failed" }); + } + const streaming = () => + new Set( + api.requests + .filter((request) => request.agent && request.stream && request.at >= launchedAt) + .map((request) => request.marker), + ); + for (let attempt = 0; attempt < 300; attempt++) { + if (markers.every((marker) => streaming().has(marker))) break; + yield* Effect.sleep(Duration.millis(100)); + } + if (!markers.every((marker) => streaming().has(marker))) { + return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); + } + yield* Effect.sleep(Duration.seconds(5)); + measured.streaming = yield* server.measure(60); + yield* profile(server, "streaming"); + }), + ); + } + if (options.soakMinutes > 0) { + yield* withServer("soak", (server) => + Effect.gen(function* () { + const threads = yield* openThreads(server, 0, 10); + yield* Effect.sleep(Duration.seconds(60)); + // The snapshot inflates RSS once, so the slopes start after it. + const before = yield* server.snapshot; + const samples: Array<{ hours: number; window: Window }> = []; + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); + const takeSample = Effect.gen(function* () { + samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); + }); + let nextSample = 0; + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if ((yield* elapsed) >= nextSample) { + yield* takeSample; + nextSample += 120_000; + } + const threadId = + threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); + } + yield* takeSample; + const perHour = (pick: (window: Window) => number) => + round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: perHour((window) => window.heapAfterGcMB), + rssMBPerHour: perHour((window) => window.rssMB), + }; + soakHeapGrowth = heapGrowth(before, yield* server.snapshot); + }), + ); + } + return { measured: measured as Measured, profiles, soakHeapGrowth }; +}, Effect.scoped); + +const machineLoad = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") { + return yield* powershell( + "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average", + ); + } + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const load = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(load, (text) => text.split(" ").slice(0, 3).join(" ")); + } + return yield* output("sysctl", ["-n", "vm.loadavg"]); +}).pipe( + Effect.map((load) => + Option.getOrNull(Option.map(load, (text) => text.replace(/[{}]/g, "").trim())), + ), +); + +const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { + const platform = yield* HostProcess.Platform; + const architecture = yield* HostProcess.Architecture; + const environment = yield* HostProcess.Environment; + const node = yield* HostProcess.ExecutablePath; + const claude = yield* output("claude", ["--version"]); + if (Option.isNone(claude)) { + return yield* new MetricsError({ message: "The real `claude` CLI must be on PATH." }); + } + if (options.noAgentScope && platform !== "linux") { + return yield* new MetricsError({ + message: "--no-agent-scope is Linux only; other platforms never have an agent scope.", + }); + } + const cpus = + platform === "win32" + ? Option.fromNullishOr(environment.NUMBER_OF_PROCESSORS) + : yield* output("getconf", ["_NPROCESSORS_ONLN"]); + return { + platform: `${platform}-${architecture}`, + cpus: Option.getOrNull(Option.map(cpus, Number)), + node: Option.getOrNull(yield* output(node, ["--version"])), + claude: claude.value, + commit: Option.getOrNull( + yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), + ), + noAgentScope: options.noAgentScope, + agentScope: + platform === "linux" && + !options.noAgentScope && + !!environment.XDG_RUNTIME_DIR && + Option.isSome(yield* output("sh", ["-c", "command -v systemd-run"])), + loadBefore: yield* machineLoad, + measuredAt: DateTime.formatIso(yield* DateTime.now), + }; +}); + +const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* ( + out: Option.Option, + metrics: ServerMetrics, +) { + const fs = yield* FileSystem.FileSystem; + const json = yield* encodeMetrics(metrics); + if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`); + else yield* Console.log(json); +}); + +/** Prints the comparison and sets exit code 1 when a metric got worse. */ +const report = Effect.fn("serverMetrics.report")(function* ( + before: ServerMetrics, + after: ServerMetrics, + threshold: number, +) { + const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + yield* Console.log(table); + if (compared === 0) { + return yield* new MetricsError({ + message: "the two files share no metric, so nothing was compared", + }); + } + if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); + if (regressed.length === 0) return; + yield* Console.error(`Worse: ${regressed.join(", ")}`); + yield* Effect.sync(() => { + process.exitCode = 1; + }); +}); + +const thresholdFlag = Flag.Int("threshold").pipe( + Flag.withDescription("Percent a metric must move, past its noise floor, to count."), + Flag.withDefault(10), +); +const runFlags = { + noAgentScope: Flag.Boolean("no-agent-scope").pipe( + Flag.withAlias("mac-path"), + Flag.withDefault(false), + Flag.withDescription( + "Linux only: start the server without XDG_RUNTIME_DIR, so it takes the no-agent-scope path macOS and Windows always take.", + ), + ), + runs: Flag.Int("runs").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("firstWord runs in each variant."), + Flag.withDefault(5), + ), + threads: Flag.String("threads").pipe( + Flag.withDescription("Open thread counts the quiet scenario measures."), + Flag.withDefault("0,5,10,20"), + ), + only: Flag.String("only").pipe( + Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), + Flag.optional, + ), + soak: Flag.Int("soak").pipe( + Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + Flag.withDescription( + "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + ), + Flag.withDefault(0), + ), +}; +interface RunFlags { + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: string; + readonly only: Option.Option; + readonly soak: number; +} + +const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( + flags: RunFlags, + checkout: string, + profileDir: string | undefined, +) { + const path = yield* Path.Path; + const selection = parseRunSelection({ + only: Option.getOrElse(flags.only, () => ""), + threads: flags.threads, + soak: flags.soak, + scenarios: SCENARIOS, + }); + if ("error" in selection) return yield* new MetricsError({ message: selection.error }); + const { only, threads } = selection; + const options: RunOptions = { + checkout: path.resolve(checkout), + noAgentScope: flags.noAgentScope, + runs: flags.runs, + threads, + only, + soakMinutes: flags.soak, + profileDir, + }; + return options; +}); + +const runCommand = Command.make( + "run", + { + ...runFlags, + out: Flag.String("out").pipe(Flag.withDescription("JSON file to write."), Flag.optional), + checkout: Flag.String("checkout").pipe( + Flag.withDescription("Checkout whose server to measure, with dependencies installed."), + Flag.optional, + ), + repeat: Flag.Int("repeat").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("Runs to record in one file."), + Flag.withDefault(1), + ), + }, + Effect.fn("serverMetrics.run")(function* (input) { + const path = yield* Path.Path; + const checkout = Option.getOrElse(input.checkout, () => + path.resolve(import.meta.dirname, ".."), + ); + const profileDir = Option.getOrUndefined( + Option.map(input.out, (out) => `${out.replace(/\.json$/, "")}-profiles`), + ); + if (input.repeat < 1) + return yield* new MetricsError({ message: "--repeat must be at least 1" }); + const options = yield* toRunOptions(input, checkout, profileDir); + const meta = yield* metaFor(options); + const runs: Measured[] = []; + let last: Effect.Success> | undefined; + for (let index = 0; index < input.repeat; index++) { + last = yield* runOnce(options); + runs.push(last.measured); + } + yield* writeMetrics(input.out, { + meta: { ...meta, loadAfter: yield* machineLoad }, + runs, + ...(last ? { profiles: last.profiles } : {}), + ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + }); + }), +).pipe( + Command.withDescription( + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", + ), +); + +const abCommand = Command.make( + "ab", + { + ...runFlags, + checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")), + checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")), + rounds: Flag.Int("rounds").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("Rounds; each runs A and B once, alternating which goes first."), + Flag.withDefault(3), + ), + outDir: Flag.String("out-dir").pipe( + Flag.withDescription("Directory for a.json and b.json."), + Flag.withDefault("server-metrics-ab"), + ), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.ab")(function* (input) { + if (input.rounds < 1) + return yield* new MetricsError({ message: "--rounds must be at least 1" }); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const outDir = path.resolve(input.outDir); + yield* fs.makeDirectory(outDir, { recursive: true }); + const sides = [ + yield* toRunOptions(input, input.checkoutA, undefined), + yield* toRunOptions(input, input.checkoutB, undefined), + ] as const; + const metas = [yield* metaFor(sides[0]), yield* metaFor(sides[1])] as const; + const runs: [Measured[], Measured[]] = [[], []]; + for (let round = 0; round < input.rounds; round++) { + // A B, then B A, so a drift in machine load lands on both sides. + for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { + yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`); + runs[side].push((yield* runOnce(sides[side])).measured); + } + } + const loadAfter = yield* machineLoad; + const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] }; + const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] }; + yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); + yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); + yield* report(before, after, input.threshold); + }), +).pipe( + Command.withDescription( + "Run two checkouts alternately on this machine and compare them. Each needs its dependencies installed; the harness comes from this script, so an old release works too.", + ), +); + +const compareCommand = Command.make( + "compare", + { + before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")), + after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.compare")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + yield* report(yield* read(input.before), yield* read(input.after), input.threshold); + }), +).pipe( + Command.withDescription( + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + ), +); + +const serverMetricsCommand = Command.make("server-metrics").pipe( + Command.withDescription( + "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + ), + Command.withSubcommands([runCommand, abCommand, compareCommand]), +); + +if (import.meta.main) { + Command.run(serverMetricsCommand, { version: "0.0.0" }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeHttpClient.layerUndici, + NodeSocket.layerWebSocketConstructor, + ), + ), + NodeRuntime.runMain, + ); +} From 3c84f4b1c4f2fff49f731b9bc863e9b14bae2e0e Mon Sep 17 00:00:00 2001 From: Pulsar Programmer Date: Mon, 23 Nov 2026 00:17:29 -0500 Subject: [PATCH 016/288] fix(ssh): accept Node versions with build metadata (#41171) --- packages/shared/src/semver.test.ts | 3 +++ packages/shared/src/semver.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/semver.test.ts b/packages/shared/src/semver.test.ts index 0dac4f2ab9e0d..b5a3935ebc208 100644 --- a/packages/shared/src/semver.test.ts +++ b/packages/shared/src/semver.test.ts @@ -94,6 +94,9 @@ describe("semver helpers", () => { expect(recreated("0.5.0", "^0")).toBe(true); expect(recreated("0.0.4", "^0.0")).toBe(true); expect(recreated("24.10.0", ">=24.10")).toBe(true); + expect(recreated("24.10.0+vendor.1", ">=24.10")).toBe(true); + expect(recreated("24.10.0+vendor..1", ">=24.10")).toBe(false); + expect(recreated("24.9.9+vendor.1", ">=24.10")).toBe(false); expect(recreated("24.9.9", ">=24.10")).toBe(false); }); }); diff --git a/packages/shared/src/semver.ts b/packages/shared/src/semver.ts index 0a982b9465566..4b6166f40c403 100644 --- a/packages/shared/src/semver.ts +++ b/packages/shared/src/semver.ts @@ -145,7 +145,7 @@ export const satisfiesSemverRange: (rawVersion: string, range: string) => boolea function satisfiesSemverRange(rawVersion, range) { const normalizedVersion = String(rawVersion).trim().replace(/^v/, ""); const versionMatch = normalizedVersion.match( - /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/, + /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, ); if (!versionMatch) { return false; From ad621cc20e9f1712b0e68905ae1949ca36828bf1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:19:15 -0800 Subject: [PATCH 017/288] fix(server): merge-back refuses an archived or deleted parent (#41229) --- .../src/orchestration-v2/Orchestrator.ts | 14 ++++++++++ .../ThreadFork.execution.test.ts | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8a546270a0515..ae06077992d0a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6170,6 +6170,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`, }); } + if (sourceProjection.thread.deletedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.sourceThreadId} was deleted.`, + }); + } + if (targetProjection.thread.deletedAt !== null || targetProjection.thread.archivedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.targetThreadId} is archived or deleted.`, + }); + } // Queued runs cannot consume merge-back context. Refuse under the target's // command lock before a pending transfer can block its ordinary messages. if (targetProjection.runs.some((run) => isActiveRun(run) || run.status === "queued")) { diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 3466fed79f502..457a98487c69d 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1724,6 +1724,34 @@ it.effect("merge-back rejects a second fork's context until the first is consume [first.threadId, "pending"], ], ); + + // Archiving or deleting a parent cascades only to side chats, so the full fork can still merge back. + const mergeNestedInto = (commandId: string) => + orchestrator + .dispatch({ + type: "thread.merge_back", + commandId: CommandId.make(commandId), + sourceThreadId: nested.threadId, + targetThreadId: first.threadId, + sourcePoint: { type: "run", runId: nestedRunId }, + createdBy: "user", + creationSource: "web", + }) + .pipe(Effect.flip); + yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make("merge-back-guard-archive-first"), + threadId: first.threadId, + }); + const intoArchived = yield* mergeNestedInto("merge-back-guard-into-archived"); + assert.equal(intoArchived._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("merge-back-guard-delete-first"), + threadId: first.threadId, + }); + const intoDeleted = yield* mergeNestedInto("merge-back-guard-into-deleted"); + assert.equal(intoDeleted._tag, "OrchestratorDispatchError"); }).pipe(Effect.provide(forkCases[0]!.layer)), ); From df93cabbcc20148aef4565e9b18adef942f39eb3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:20:20 -0800 Subject: [PATCH 018/288] fix(contracts): ForwardCompatibleOptional drops the key for values it cannot read (#41236) --- packages/contracts/src/baseSchemas.test.ts | 10 ++++++++++ packages/contracts/src/baseSchemas.ts | 21 +++++++++++---------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/packages/contracts/src/baseSchemas.test.ts b/packages/contracts/src/baseSchemas.test.ts index beae3731400bc..e6940cc85a76d 100644 --- a/packages/contracts/src/baseSchemas.test.ts +++ b/packages/contracts/src/baseSchemas.test.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { ForwardCompatibleArray, + ForwardCompatibleOptional, ForwardCompatibleUnion, ForwardCompatibleUnionArray, isUnknownUnionMember, @@ -62,6 +63,15 @@ describe("ForwardCompatibleArray", () => { }); }); +describe("ForwardCompatibleOptional", () => { + const Settings = Schema.Struct({ mode: ForwardCompatibleOptional(Schema.Literals(["a", "b"])) }); + const encodeSettings = Schema.encodeUnknownSync(Schema.toCodecJson(Settings)); + + it("encodes back to JSON after dropping a value it cannot read", () => { + expect(encodeSettings(fromWire(Settings)({ mode: "future" }))).toEqual({}); + }); +}); + describe("ForwardCompatibleUnion", () => { const decode = fromWire(ForwardCompatibleUnion(members, "kind")); diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 30df0d53c537f..d8137fc8ca9ec 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -47,16 +47,17 @@ export type IsoDateTime = typeof IsoDateTime.Type; export const ForwardCompatibleOptional = (value: Value) => { const decodeValue = Schema.decodeUnknownOption(value as never); - return Schema.optionalKey( - Schema.Unknown.pipe( - Schema.decodeTo( - Schema.UndefinedOr(value), - SchemaTransformation.transform({ - decode: (raw) => - Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : undefined, - encode: (raw) => raw, - }), - ), + // Unreadable values drop the key: an own undefined property is not JSON and fails RPC encoding. + return Schema.optionalKey(Schema.Unknown).pipe( + Schema.decodeTo( + Schema.optionalKey(Schema.UndefinedOr(value)), + SchemaTransformation.transformOptional({ + decode: (raw) => + Option.isSome(raw) && Option.isSome(decodeValue(raw.value)) + ? Option.some(raw.value as Value["Encoded"]) + : Option.none(), + encode: (raw) => (Option.isSome(raw) && raw.value !== undefined ? raw : Option.none()), + }), ), ); }; From 91c6ecce42cfd8bd04f4ba87b1b9caaaa05b488c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:24:54 -0800 Subject: [PATCH 019/288] fix(acp): agent terminals keep 1.25 MiB of output, not 16 MiB (#41243) Co-authored-by: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 4 +-- .../src/server/runtimeModel.test.ts | 26 ++++++++++++++++--- .../provider-acp/src/server/runtimeModel.ts | 9 ++++--- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d4af4aa10ddd5..8905317d20f5f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -80,6 +80,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { applyAcpAgentTerminalUpdate, + MAX_AGENT_TERMINAL_OUTPUT_CHARS, acpContentBlockDisplayText, embeddedTerminalIdsFromSessionUpdate, extractMcpToolCallIdentity, @@ -2008,9 +2009,6 @@ const emptySnapshotState = (): SnapshotMessageState => ({ const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000; const TOOL_UPDATE_PERSIST_EVERY = 10; -// CommandOutputHub reads the last 256 KiB; retain more so its display cut stays unchanged. -const MAX_AGENT_TERMINAL_OUTPUT_CHARS = 320 * 1024; - // Agents can resend whole calls while streaming arguments. function shouldPersistToolUpdate( context: Pick, diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index ee4a9ca2aa57a..a4fe10a11efe2 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1207,9 +1207,27 @@ describe("AcpRuntimeModel", () => { expect(second.pendingOutputBytes).toBeUndefined(); }); - it("trims full ACP terminal output by a further 1 MiB at a UTF-8 boundary", () => { - const cap = 16 * 1024 * 1024; - const step = 1024 * 1024; + it("retains only the terminal output tail the projection reads", () => { + const projectedChars = 320 * 1024; + let state: ReturnType | undefined; + let full = ""; + for (let index = 0; index < 64; index += 1) { + const text = `${index % 10}`.repeat(64 * 1024 - 1) + "é"; + full += text; + state = applyAcpAgentTerminalUpdate(state, { + sessionUpdate: "terminal_output_chunk", + terminalId: "terminal-tail", + data: Buffer.from(text).toString("base64"), + }); + } + expect(state!.outputBytes).toBeLessThanOrEqual(4 * projectedChars); + expect(state!.outputBytes).toBe(Buffer.byteLength(state!.output)); + expect(state!.output.slice(-projectedChars)).toBe(full.slice(-projectedChars)); + }); + + it("trims full ACP terminal output by a further 256 KiB at a UTF-8 boundary", () => { + const cap = 1280 * 1024; + const step = 256 * 1024; const chunk = (text: string | Uint8Array) => ({ sessionUpdate: "terminal_output_chunk" as const, terminalId: "terminal-cap", @@ -1228,7 +1246,7 @@ describe("AcpRuntimeModel", () => { expect(full.outputBytes).toBe(cap); expect(full.output.length).toBe(cap - 1); - // The cut at one byte past the cap plus 1 MiB falls inside "é", so the whole character goes. + // The cut at one byte past the cap plus 256 KiB falls inside "é", so the whole character goes. const trimmed = applyAcpAgentTerminalUpdate(full, chunk("c")); expect(trimmed.outputBytes).toBe(cap - step - 1); expect(trimmed.output.length).toBe(cap - step - 1); diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index e01ca47772f9e..1306d0a12cf44 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -61,9 +61,12 @@ type AcpAgentTerminalUpdate = Extract< { readonly sessionUpdate: "terminal_update" | "terminal_output_chunk" } >; -const MAX_ACP_TERMINAL_OUTPUT_BYTES = 16 * 1024 * 1024; -const ACP_TERMINAL_OUTPUT_TRIM_BYTES = 1024 * 1024; -const MAX_ACP_TERMINAL_FRAME_BYTES = MAX_ACP_TERMINAL_OUTPUT_BYTES; +// CommandOutputHub reads the last 256 KiB; retain more so its display cut stays unchanged. +export const MAX_AGENT_TERMINAL_OUTPUT_CHARS = 320 * 1024; +// A UTF-16 code unit is at most 3 UTF-8 bytes, so the post-trim floor still holds the projected tail. +const MAX_ACP_TERMINAL_OUTPUT_BYTES = 4 * MAX_AGENT_TERMINAL_OUTPUT_CHARS; +const ACP_TERMINAL_OUTPUT_TRIM_BYTES = 256 * 1024; +const MAX_ACP_TERMINAL_FRAME_BYTES = 16 * 1024 * 1024; function isBase64DataCode(code: number): boolean { return ( From 611410683b3571a6cd2c8f711a6b1cfc01de5a9f Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 23:26:30 -0600 Subject: [PATCH 020/288] feat(cursor): show which step Cursor is in while a turn starts (#41242) Co-authored-by: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 1 + .../src/features/threads/thread-work-log.tsx | 19 +++++- apps/mobile/src/i18n/translations/de.json | 7 +- apps/mobile/src/i18n/translations/en.json | 7 +- apps/mobile/src/i18n/translations/es.json | 7 +- apps/mobile/src/i18n/translations/fr.json | 7 +- apps/mobile/src/i18n/translations/ja.json | 7 +- apps/mobile/src/i18n/translations/ko.json | 7 +- apps/mobile/src/i18n/translations/pt-BR.json | 7 +- apps/mobile/src/i18n/translations/ru.json | 7 +- apps/mobile/src/i18n/translations/sv.json | 7 +- apps/mobile/src/i18n/translations/zh.json | 7 +- apps/mobile/src/lib/threadActivity.ts | 14 +++- apps/web/src/components/ChatView.tsx | 5 ++ .../src/components/chat/MessagesTimeline.tsx | 4 ++ .../components/chat/ProviderStartingIcon.tsx | 67 +++++++++++++++++++ .../components/chat/TimelineWorkGroupRows.tsx | 49 +++++++++++--- .../src/components/chat/timelineRowContext.ts | 2 + apps/web/src/i18n/translations/de.json | 7 +- apps/web/src/i18n/translations/en.json | 7 +- apps/web/src/i18n/translations/es.json | 7 +- apps/web/src/i18n/translations/fr.json | 7 +- apps/web/src/i18n/translations/ja.json | 7 +- apps/web/src/i18n/translations/ko.json | 7 +- apps/web/src/i18n/translations/pt-BR.json | 7 +- apps/web/src/i18n/translations/ru.json | 7 +- apps/web/src/i18n/translations/sv.json | 7 +- apps/web/src/i18n/translations/zh.json | 7 +- packages/client-runtime/src/state/models.ts | 6 ++ .../src/state/threadExecution.test.ts | 16 +++++ .../src/state/threadExecution.ts | 39 +++++++++-- packages/contracts/src/orchestrationV2.ts | 5 ++ .../src/server/CursorAgentSdk.test.ts | 34 ++++++++++ .../src/server/CursorAgentSdk.ts | 59 +++++++++++----- .../CursorAgentSdkProcessRunner.test.ts | 4 ++ .../src/server/CursorAgentSdkProcessRunner.ts | 29 ++++++-- .../src/server/CursorAgentSdkWorker.ts | 6 ++ .../server/CursorAgentSdkWorkerProtocol.ts | 5 ++ .../src/server/adapter.test.ts | 11 +++ .../provider-cursor/src/server/adapter.ts | 29 +++++++- patches/@cursor__sdk@1.4.2.patch | 14 ++-- pnpm-lock.yaml | 8 +-- 42 files changed, 494 insertions(+), 72 deletions(-) create mode 100644 apps/web/src/components/chat/ProviderStartingIcon.tsx diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index a809dc8ea8f3e..005a6fb8f30c1 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -2096,6 +2096,7 @@ function renderFeedEntry( iconSubtleColor={iconSubtleColor} label={entry.label} providerStartingLabel={entry.providerStartingLabel} + providerStartingDriver={entry.providerStartingDriver} /> ); } diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index f0bc00e11385e..a774bf9519c29 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1,3 +1,4 @@ +import { ProviderIcon } from "../../components/ProviderIcon"; import { Button } from "../../components/ui/Button"; import { ThreadSubagentGroup } from "./thread-subagent-group"; import { ProposedPlanCard } from "./ProposedPlanCard"; @@ -214,6 +215,7 @@ function ShimmerWorkContent(props: { readonly environmentId?: EnvironmentId; readonly highlighted: boolean; readonly icon: WorkContentIcon; + readonly iconNode?: ReactNode; readonly iconSubtleColor: ColorValue; readonly label: string; readonly onTextLayout?: ComponentProps["onTextLayout"]; @@ -225,7 +227,9 @@ function ShimmerWorkContent(props: { {props.showIcon ? ( - {props.toolIcon && props.environmentId ? ( + {props.iconNode !== undefined ? ( + props.iconNode + ) : props.toolIcon && props.environmentId ? ( + + + ) + } iconSubtleColor={props.iconSubtleColor} label={label} showIcon diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 10ed053228b10..1116dd8895c6e 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 312e7e4c60bbd..d9c7d08df765b 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 9124637171066..8ceac2b26a722 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index ad9d49d83c52c..a6904b69d7f73 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index b80aeaddbb35a..3ce3515fae73b 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b35b6391337f1..484ab67231b2e 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 037e9559e0aa3..4959be9c365b1 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index a36a2f6e8716b..7987d3d16485a 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6c1040e3eb0b0..38f2f3c80172c 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 7f0cdbac92e7d..e673d0e56ba1b 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 1760b37b49606..e180927aa3c90 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -270,6 +270,8 @@ type ThreadFeedEntryContent = readonly label?: string; /** Shown instead of "Thinking" while the provider has not started a turn. */ readonly providerStartingLabel?: string; + /** The starting provider's driver, whose logo replaces the thinking icon. */ + readonly providerStartingDriver?: string; }; export interface ThreadFeedLatestRun { @@ -280,6 +282,7 @@ export interface ThreadFeedLatestRun { readonly turnEnded?: boolean; readonly providerStartingLabel?: string; readonly providerStartingLabelMsg?: string; + readonly providerStarting?: { readonly driver: string }; } /** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */ @@ -1498,7 +1501,8 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate left.completedAt === right.completedAt && left.turnEnded === right.turnEnded && left.providerStartingLabel === right.providerStartingLabel && - left.providerStartingLabelMsg === right.providerStartingLabelMsg) + left.providerStartingLabelMsg === right.providerStartingLabelMsg && + left.providerStarting?.driver === right.providerStarting?.driver) ); } @@ -1990,6 +1994,7 @@ export function deriveThreadFeedPresentation( latestRun?.providerStartingLabelMsg === undefined ? latestRun?.providerStartingLabel : resolve(latestRun.providerStartingLabelMsg), + latestRun?.providerStarting?.driver, ), ); } @@ -2136,12 +2141,14 @@ function thinkingRow( runId: RunId | null, label: string | null, providerStartingLabel: string | undefined, + providerStartingDriver: string | undefined, ) { if ( cachedThinkingRow?.createdAt !== createdAt || cachedThinkingRow.runId !== runId || (cachedThinkingRow.label ?? null) !== label || - cachedThinkingRow.providerStartingLabel !== providerStartingLabel + cachedThinkingRow.providerStartingLabel !== providerStartingLabel || + cachedThinkingRow.providerStartingDriver !== providerStartingDriver ) { cachedThinkingRow = { type: "thinking", @@ -2150,6 +2157,9 @@ function thinkingRow( runId, ...(label === null ? {} : { label }), ...(providerStartingLabel === undefined ? {} : { providerStartingLabel }), + ...(providerStartingLabel === undefined || providerStartingDriver === undefined + ? {} + : { providerStartingDriver }), }; } return cachedThinkingRow; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 840c337156343..e3b4e9e5f7682 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3650,6 +3650,11 @@ export default function ChatView(props: ChatViewProps) { ? messages(activeActivityRun.providerStartingLabelMsg) : null } + providerStarting={ + activeActivityRun?.providerStartingLabelMsg + ? (activeActivityRun.providerStarting ?? null) + : null + } worktreeSetup={worktreeSetup} onCancelWorktreeSetup={onCancelWorktreeSetupStable} retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 42409464aca7a..aaaba1d4bc921 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,5 +1,6 @@ import { T, useGT, useMessages, Var } from "gt-react"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import { threadErrorText } from "@t3tools/client-runtime/state/threads"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -242,6 +243,7 @@ interface MessagesTimelineProps { activeTurnStartedAt?: string | null; /** Replaces "Thinking" while the active run's provider has not started a turn. */ providerStartingLabel?: string | null; + providerStarting?: NonNullable | null; worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; retryableWorkspacePreparationRunIds?: ReadonlySet; @@ -366,6 +368,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ runlessWorkActive = false, activeTurnStartedAt = null, providerStartingLabel = null, + providerStarting = null, worktreeSetup = null, footer = null, onCancelWorktreeSetup, @@ -1193,6 +1196,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ awaitingUser: awaitingUser !== null, isPreparingWorktree, providerStartingLabel, + providerStarting, latestRunId: latestRun?.runId ?? null, liveAnswerPreview: isWorking && toolCallVisibility === "zen" ? liveAnswerPreview(timelineEntries) : null, diff --git a/apps/web/src/components/chat/ProviderStartingIcon.tsx b/apps/web/src/components/chat/ProviderStartingIcon.tsx new file mode 100644 index 0000000000000..634f1f742f1d6 --- /dev/null +++ b/apps/web/src/components/chat/ProviderStartingIcon.tsx @@ -0,0 +1,67 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type EnvironmentId, + PROVIDER_DISPLAY_NAMES, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; + +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "~/providerInstances"; +import { serverEnvironment } from "~/state/server"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; + +interface ProviderStartingPresentation { + readonly displayName: string; + readonly acpRegistryAgentId: string | undefined; + readonly acpRegistryIconUrl: string | undefined; +} + +// Keyed per instance so provider status pushes don't rerender the live row. +const providerStartingPresentationAtom = Atom.family((key: string) => + Atom.make((get): ProviderStartingPresentation | null => { + const [environmentId, instanceId] = key.split("\u0000") as [string, string]; + const config = get(serverEnvironment.configValueAtom(environmentId as EnvironmentId)); + const provider = config?.providers.find((candidate) => candidate.instanceId === instanceId); + if (!config || !provider) return null; + const [entry] = brandProviderInstanceEntries( + deriveProviderInstanceEntries([provider]), + config.settings, + ); + if (!entry) return null; + const next = { + displayName: entry.displayName, + acpRegistryAgentId: entry.acpRegistryAgentId, + acpRegistryIconUrl: entry.acpRegistryIconUrl, + }; + const previous = Option.getOrNull(get.self()); + return previous && + previous.displayName === next.displayName && + previous.acpRegistryAgentId === next.acpRegistryAgentId && + previous.acpRegistryIconUrl === next.acpRegistryIconUrl + ? previous + : next; + }).pipe(Atom.withLabel("provider-starting-presentation")), +); + +/** The logo of the provider a run is waiting on, shown in place of the thinking icon. */ +export function ProviderStartingIcon(props: { + readonly environmentId: EnvironmentId | null; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; +}) { + const presentation = useAtomValue( + providerStartingPresentationAtom(`${props.environmentId ?? ""}\u0000${props.instanceId}`), + ); + return ( + + ); +} diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index c67c76bf4cca3..253d72fd2649e 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -41,6 +41,7 @@ import { type TimelineWorkEntry, type TimelineRow, } from "./timelineRowContext"; +import { ProviderStartingIcon } from "./ProviderStartingIcon"; import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts"; import { failedToolIconClassName, @@ -443,8 +444,13 @@ export function ThinkingTimelineRow({ row }: { row: Extract; // A failed group keeps this disclosure while an approval waits, but nothing is thinking then. const live = ctx.pendingApprovals.size === 0; @@ -457,6 +463,15 @@ export function ThinkingTimelineRow({ row }: { row: Extract + ) + } active={live} shimmer={live} /> @@ -478,6 +493,7 @@ export function ThinkingTimelineRow({ row }: { row: Extract {showShimmer ? ( - + ) : null} @@ -517,6 +542,7 @@ function LiveActivityRow({ function LiveActivityContent({ label, iconName, + iconNode, toolIcon, failed = false, announceFailure = false, @@ -525,6 +551,7 @@ function LiveActivityContent({ }: { label: ReactNode; iconName: WorkEntryIconName | undefined; + iconNode?: ReactNode; toolIcon?: ToolActivityIcon | undefined; failed?: boolean; announceFailure?: boolean; @@ -551,12 +578,16 @@ function LiveActivityContent({ role={announceFailure ? "img" : undefined} aria-label={announceFailure ? gt("Tool call failed") : undefined} > - + {iconNode ? ( + {iconNode} + ) : ( + + )} ) : null } diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 5ff5c032db981..139379fbeefda 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,5 +1,6 @@ import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import type { ProviderApprovalDecision, ResponseContextRecord, @@ -117,6 +118,7 @@ export interface TimelineRowActivityState { awaitingUser: boolean; isPreparingWorktree: boolean; providerStartingLabel: string | null; + providerStarting: NonNullable | null; latestRunId: RunId | null; backgroundWorktreeSetup: WorktreeSetupSnapshot | null; liveAnswerPreview: string | null; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index aeb4e4497d43e..7900e73186091 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e3e810fe437bc..5bdd7c383d319 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 113f1c5d4cafe..91dbb2b07f50f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 17c01696429a9..f5cf7e62a4744 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index a13377564e7fe..7e3be343b068b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index da68956e5a4d2..ef69858aead11 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a0e88601de24c..5b2f82a27a416 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 890e0b9d7506b..2891cb8165d7c 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 967d0c7eededd..c792d6fb4a981 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5a5128c0a7c8d..cd80e9a35102a 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4b708662839b2..a57483fdd95c5 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -12,6 +12,7 @@ import type { OrchestrationV2ThreadShell, PlanId, ProjectId, + ProviderDriverKind, ProviderInstanceId, RunId, ThreadId, @@ -99,6 +100,11 @@ export interface ThreadRunSummary { readonly providerStartingLabel?: string; /** `providerStartingLabel` as a `msg()` string; display sites resolve this one. */ readonly providerStartingLabelMsg?: string; + /** The starting provider, so clients can show its logo beside the label. */ + readonly providerStarting?: { + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; + }; readonly sourcePlanRef?: { readonly threadId: ThreadId; readonly planId: PlanId; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index d932e2c0395b3..5e7b0b1b8c675 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -415,6 +415,22 @@ describe("thread execution presentation", () => { const starting = { ...v2Projection, runs: [openRun], providerSessions: [session] }; expect(deriveThreadActivityRun(starting)?.providerStartingLabel).toBe("Starting Claude"); + expect(deriveThreadActivityRun(starting)?.providerStarting).toEqual({ + instanceId: openRun.providerInstanceId, + driver: session.driver, + }); + expect( + deriveThreadActivityRun({ + ...starting, + providerSessions: [{ ...session, startupPhase: "plugins" }], + })?.providerStartingLabel, + ).toBe("Loading Claude plugins"); + expect( + deriveThreadActivityRun({ + ...starting, + providerSessions: [{ ...session, startupPhase: "a-later-server's-phase" }], + })?.providerStartingLabel, + ).toBe("Starting Claude"); expect( deriveThreadActivityRun({ ...starting, providerSessions: [] })?.providerStartingLabel, ).toBe("Starting"); diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 7e5ad55dc53b2..7a47960e7b3f3 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -113,19 +113,46 @@ function latestMatchingRun( ); } +// Phases a provider can report while it prepares a turn; an unknown one keeps the plain label. +function providerStartingPhase(phase: string | undefined, provider: string) { + switch (phase) { + case "plugins": + return msg("Loading {provider} plugins", { provider }); + case "mcp": + return msg("Starting {provider} MCP servers", { provider }); + case "hooks": + return msg("Loading {provider} hooks", { provider }); + case "skills": + return msg("Loading {provider} rules and skills", { provider }); + case "connecting": + return msg("Connecting to {provider}", { provider }); + default: + return msg("Starting {provider}", { provider }); + } +} + function providerStarting( projection: ThreadStructure, run: OrchestrationV2ThreadProjection["runs"][number], -): Pick { - const driver = projection.providerSessions.findLast( +): Pick< + ThreadRunSummary, + "providerStartingLabel" | "providerStartingLabelMsg" | "providerStarting" +> { + const session = projection.providerSessions.findLast( (session) => session.providerInstanceId === run.providerInstanceId, - )?.driver; - const name = driver === undefined ? undefined : PROVIDER_DISPLAY_NAMES[driver]; + ); + const name = session === undefined ? undefined : PROVIDER_DISPLAY_NAMES[session.driver]; const label = name === undefined ? msg("Starting", { $context: "a provider is launching" }) - : msg("Starting {provider}", { provider: name }); - return { providerStartingLabel: markedTextEnglish([label]), providerStartingLabelMsg: label }; + : providerStartingPhase(session?.startupPhase, name); + return { + providerStartingLabel: markedTextEnglish([label]), + providerStartingLabelMsg: label, + ...(session === undefined + ? {} + : { providerStarting: { instanceId: run.providerInstanceId, driver: session.driver } }), + }; } function summarizeThreadRun( diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 33961fcf8b82b..c9c8eea937e94 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1114,6 +1114,11 @@ export const OrchestrationV2ProviderSession = Schema.Struct({ }), ).check(Schema.isMaxLength(32)), ).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + /** + * The slow step a provider is in while it starts a turn, such as `plugins`. A string, because + * clients already released reject a literal they do not know; they show the ones they do. + */ + startupPhase: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(64))), createdAt: Schema.DateTimeUtc, updatedAt: Schema.DateTimeUtc, lastError: Schema.NullOr(Schema.String), diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index 94ae5205131e7..3b637b350ffc3 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -404,6 +404,40 @@ describe("CursorAgentSdkRunner", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("reports the SDK's startup phases only to the send that is starting", () => + Effect.gen(function* () { + const publish = (phase: string) => + (Reflect.get(globalThis, Symbol.for("@cursor/sdk.startupPhase")) as Function)(phase); + const startSend = cursorSdkMock.send.getMockImplementation()!; + cursorSdkMock.send.mockImplementationOnce(async (message, options) => { + await Promise.resolve(); + publish("plugins"); + return startSend(message, options); + }); + const phases: Array = []; + const reported = yield* Deferred.make(); + const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; + const session = yield* runner.open({ + operation: "create", + options: {}, + threadId: ThreadId.make("thread-cursor-agent-sdk-phase"), + providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-phase"), + }); + const run = yield* session.send({ + message: "start", + onStartupPhase: (phase) => + Effect.sync(() => phases.push(phase)).pipe( + Effect.andThen(Deferred.succeed(reported, undefined)), + ), + }); + yield* Deferred.await(reported); + publish("mcp"); + yield* run.wait; + + assert.deepStrictEqual(phases, ["plugins"]); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("keeps an agent's background shells and reports each start and end in order", () => Effect.gen(function* () { const start = (conversationId: string, id: number) => { diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index 81b8208a5dda8..3c05771bfaf05 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -9,6 +9,7 @@ import type { SendOptions, SteerAckOutcome, } from "@cursor/sdk"; +import * as NodeAsyncHooks from "node:async_hooks"; import { NonNegativeInt, type OrchestrationV2ProviderSession, @@ -106,6 +107,8 @@ export interface CursorAgentSdkSendInput { * ends, which is often long after the run. */ readonly onBackgroundShell?: (event: CursorBackgroundShellEvent) => Effect.Effect; + /** Runs as the SDK enters each slow step of preparing the run, before the run starts. */ + readonly onStartupPhase?: (phase: string) => Effect.Effect; } interface CursorBackgroundShellRef { @@ -550,6 +553,19 @@ interface CursorBackgroundShell { }; } +// The SDK names no step while it prepares a run, which can take minutes, so the @cursor/sdk patch +// calls this hook as it enters each one. The hook is global: async context finds the send. +const STARTUP_PHASE_HOOK = Symbol.for("@cursor/sdk.startupPhase"); +const startupPhaseListener = new NodeAsyncHooks.AsyncLocalStorage<(phase: string) => void>(); + +function listeningForStartupPhases(listener: (phase: string) => void, start: () => A): A { + const hooks = globalThis as Record; + hooks[STARTUP_PHASE_HOOK] ??= (phase: unknown) => { + if (typeof phase === "string") startupPhaseListener.getStore()?.(phase); + }; + return startupPhaseListener.run(listener, start); +} + // The SDK kills an agent's background shells when its run ends and reports their exit to no one. // The @cursor/sdk patch offers each new one to this hook; true keeps it past the run. const BACKGROUND_SHELL_HOOK = Symbol.for("@cursor/sdk.backgroundShell"); @@ -833,26 +849,33 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu return callbackChain; }; - const startRun = () => - Effect.tryPromise({ - try: () => { - if (sendInput.summarize === true) return agent.summarize(); - const options: SendOptions = { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }; - if (sendInput.resume !== true) return agent.send(sendInput.message, options); - if (agent.resume === undefined) { - throw new Error("This Cursor SDK agent cannot resume."); + const startSdkRun = () => { + if (sendInput.summarize === true) return agent.summarize(); + const options: SendOptions = { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingUpdates.push(update); + return; } - return agent.resume(options); + await dispatchUpdate(update); }, + }; + if (sendInput.resume !== true) return agent.send(sendInput.message, options); + if (agent.resume === undefined) { + throw new Error("This Cursor SDK agent cannot resume."); + } + return agent.resume(options); + }; + const onStartupPhase = sendInput.onStartupPhase; + const startRun = () => + Effect.tryPromise({ + try: () => + onStartupPhase === undefined + ? startSdkRun() + : listeningForStartupPhases((phase) => { + void Effect.runPromiseWith(context)(onStartupPhase(phase)); + }, startSdkRun), catch: (cause) => runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"), }); diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts index 430907b101097..f52a11fb25a87 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts @@ -64,6 +64,7 @@ rl.on("line", (line) => { return; } // Emit an early delta before the send response to verify parent buffering/ordering. + send({ type: "startupPhase", sendId: req.id, phase: "plugins" }); send({ type: "delta", sendId: req.id, update: { type: "text-delta", text: "early-" } }); send({ type: "response", id: req.id, ok: true, result: { runId: "run-worker-1", agentId: "agent-worker-1" } }); if (mode === "cancel") { @@ -308,8 +309,10 @@ describe("CursorAgentSdkProcessRunner", () => { const receivedDeltas: Array = []; const firstDeltaGate = yield* Deferred.make(); + const startupPhases: Array = []; const run = yield* session.send({ message: "hi", + onStartupPhase: (phase) => Effect.sync(() => startupPhases.push(phase)), onDelta: (update) => Effect.gen(function* () { const text = (update as { readonly text?: string }).text ?? ""; @@ -320,6 +323,7 @@ describe("CursorAgentSdkProcessRunner", () => { }), }); assert.equal(run.runId, "run-worker-1"); + assert.deepEqual(startupPhases, ["plugins"]); yield* Deferred.await(firstDeltaGate); const steerOutcome = yield* run.steer!("change course"); diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts index ed97c62288829..ec40415dd932a 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts @@ -55,6 +55,7 @@ interface ActiveWorkerRun { readonly sessionId: number; readonly queue: Queue.Queue; readonly waitDeferred: Deferred.Deferred; + readonly onStartupPhase: ((phase: string) => Effect.Effect) | undefined; doneEnqueued: boolean; } @@ -104,7 +105,11 @@ interface SpawnedCursorWorker { build: (id: number) => CursorWorkerRequest, method: string, ) => Effect.Effect; - readonly registerRun: (sessionId: number, sendId: number) => Effect.Effect; + readonly registerRun: ( + sessionId: number, + sendId: number, + onStartupPhase: ActiveWorkerRun["onStartupPhase"], + ) => Effect.Effect; readonly unregisterRun: (sendId: number) => Effect.Effect; readonly failSessionRuns: (sessionId: number) => Effect.Effect; readonly setBackgroundShellListener: ( @@ -358,6 +363,8 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc } return Effect.void; } + case "startupPhase": + return activeRuns.get(parsed.sendId)?.onStartupPhase?.(parsed.phase) ?? Effect.void; case "runDone": { const run = activeRuns.get(parsed.sendId); if (run !== undefined && !run.doneEnqueued) { @@ -599,13 +606,23 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc activeCleanups.add(activeCleanup); // Untraced: per-send registration inside CursorAgentSdkSession.send. - const registerRun = Effect.fnUntraced(function* (sessionId: number, sendId: number) { + const registerRun = Effect.fnUntraced(function* ( + sessionId: number, + sendId: number, + onStartupPhase: ActiveWorkerRun["onStartupPhase"], + ) { const queue = yield* Queue.unbounded(); const waitDeferred = yield* Deferred.make< RunResult, CursorAgentSdk.CursorAgentSdkRunnerError >(); - const state: ActiveWorkerRun = { sessionId, queue, waitDeferred, doneEnqueued: false }; + const state: ActiveWorkerRun = { + sessionId, + queue, + waitDeferred, + onStartupPhase, + doneEnqueued: false, + }; activeRuns.set(sendId, state); return state; }); @@ -863,7 +880,11 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc if (sendInput.onBackgroundShell !== undefined) { yield* worker.setBackgroundShellListener(sessionId, sendInput.onBackgroundShell); } - const runState = yield* worker.registerRun(sessionId, sendId); + const runState = yield* worker.registerRun( + sessionId, + sendId, + sendInput.onStartupPhase, + ); let transmitted = false; let acknowledged = false; let rejectedByWorker = false; diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts index 1481795f4ad6a..cdd0fb0136806 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts @@ -225,6 +225,12 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi writeMessage({ type: "delta", sendId: req.id, update }); } }), + onStartupPhase: (phase) => + Effect.sync(() => { + if (startingSendIds.has(req.id)) { + writeMessage({ type: "startupPhase", sendId: req.id, phase }); + } + }), ...(req.listenBackgroundShells === true ? { onBackgroundShell: (event: CursorAgentSdk.CursorBackgroundShellEvent) => diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts index e39323ef67925..7f33fde74d0ee 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts @@ -161,6 +161,11 @@ export type CursorWorkerMessage = readonly sendId: number; readonly update: InteractionUpdate; } + | { + readonly type: "startupPhase"; + readonly sendId: number; + readonly phase: string; + } | { readonly type: "runDone"; readonly sendId: number; diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 85cc2535960b8..4e687ed2b9c9e 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -2581,6 +2581,8 @@ describe("CursorAdapterV2", () => { send: (input) => Effect.gen(function* () { report = input.onBackgroundShell!; + yield* input.onStartupPhase!("plugins"); + yield* input.onStartupPhase!("plugins"); for (const id of ["6", "7", "8"]) { yield* report({ ...shell(id), @@ -2676,6 +2678,15 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); + // The phase the SDK reported while starting is published once and cleared when the run starts. + assert.deepEqual( + events.flatMap((event) => + event.type === "provider_session.updated" + ? [event.providerSession.startupPhase ?? null] + : [], + ), + ["plugins", null], + ); const listed = ( update: ReadonlyArray, ): ReadonlyArray => diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 6b04e17c120a1..426bc8b60a264 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -1153,6 +1153,23 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), }); + let startupPhase: string | undefined; + const emitStartupPhase = Effect.fn("CursorAdapterV2.emitStartupPhase")(function* ( + phase: string | undefined, + ) { + if (phase === startupPhase) return; + startupPhase = phase; + yield* emitProviderEvent({ + type: "provider_session.updated", + driver: CursorAgentSdk.CURSOR_PROVIDER, + providerSession: { + ...session, + ...(phase === undefined ? {} : { startupPhase: phase }), + updatedAt: yield* DateTime.now, + }, + }); + }); + const emitProviderThread = Effect.fn("CursorAdapterV2.emitProviderThread")(function* ( providerThread: OrchestrationV2ProviderThread, sessionScoped = false, @@ -3016,6 +3033,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), ...mcpServers, }; + let starting = true; const sdkRun = yield* agent.session .send({ message, @@ -3041,8 +3059,17 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( return handleInteractionUpdate(context, update); }, onBackgroundShell: (shell) => onBackgroundShell(turnInput, shell), + onStartupPhase: (phase) => (starting ? emitStartupPhase(phase) : Effect.void), }) - .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection))); + .pipe( + Effect.ensuring( + Effect.suspend(() => { + starting = false; + return emitStartupPhase(undefined); + }), + ), + Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection)), + ); // A resume sends no new instructions, and a native one still continues the stopped request. if (resume === undefined) { yield* Ref.set(told, { diff --git a/patches/@cursor__sdk@1.4.2.patch b/patches/@cursor__sdk@1.4.2.patch index 6aadf1b246e56..048f41a7b281d 100644 --- a/patches/@cursor__sdk@1.4.2.patch +++ b/patches/@cursor__sdk@1.4.2.patch @@ -1,5 +1,5 @@ diff --git a/dist/bundled/index.js b/dist/bundled/index.js -index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a9493f0ff 100644 +index 4d813759e7075c0fe8c881d52200d94c657b5988..b9d56b14bac4b3505679a83cfc4cc50cf34318e7 100644 --- a/dist/bundled/index.js +++ b/dist/bundled/index.js @@ -173,7 +173,7 @@ ${X} @@ -25,7 +25,7 @@ index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a ${WP8}`}function zP8($){return $ instanceof Y71}function Q71($){return QP8($)||zP8($)}var T30,Y71,WP8="To view or modify configured hooks, go to Cursor Settings > Hooks.";var bb0=P(()=>{q9();T30=class T30 extends Error{reason;failureType="permission_denied";constructor($){super(`Hook denied: ${$}`);this.name="HookDeniedError",this.reason=$}};Y71=class Y71 extends Error{reason;failureType="error";cause;constructor($,Z){super(`Hook failed (fail-closed): ${$}`);this.name="FailClosedError",this.reason=$,this.cause=Z}}});import{randomUUID as wr6}from"crypto";import{performance as fb0}from"perf_hooks";function HP8($,Z,J,X){try{return rq({hookEventName:J,additionalContext:X})}catch(Y){if(Y instanceof uQ)return P30.warn($,`${J} additional_context exceeded max size; dropping carrier`,{toolName:Z,hookEventName:J,actualLength:Y.actualLength,maxLength:Y.maxLength}),[];throw Y}}function jr6($,Z,J,X){let{toolInput:Y,extraHookFields:Q,hookContextCollector:W}=X,{baseHookRequest:K,toolUseId:H}=X;return{fireFailureAsync:async(V,O,F,N=!1)=>{try{let L=await Yu0($.signal,()=>Z.executeHookForStep(i0.postToolUseFailure,{...K,tool_name:J,tool_input:Y,error_message:O,failure_type:F,duration:V,tool_use_id:H,is_interrupt:N,...Q}));HW(W,HP8($,J,i0.postToolUseFailure,L?.additional_context))}catch(L){P30.warn($,"postToolUseFailure hook error",{toolName:J,error:L instanceof Error?L.message:String(L)})}},fireSuccessAsync:async(V,O)=>{try{let F=await Yu0($.signal,()=>Z.executeHookForStep(i0.postToolUse,{...K,tool_name:J,tool_input:Y,tool_output:O,duration:V,tool_use_id:H,...Q}));HW(W,HP8($,J,i0.postToolUse,F?.additional_context))}catch(F){P30.warn($,"postToolUse hook error",{toolName:J,error:F instanceof Error?F.message:String(F)})}},getToolInput:()=>Y,setToolInput:(V)=>{Y=V},setExtraHookFields:(V)=>{Q=V,X.extraHookFields=V}}}function GP8($,Z,J,X,Y,Q){let W=X($),K=Y.getToolCallId?.(Z)??wr6(),H=Y.getExtraHookFields?.(Z)??{},G={baseHookRequest:W,toolUseId:K,toolInput:Y.createToolInput(Z),extraHookFields:H,hookContextCollector:Q?.hookContextCollector??Y.getHookContextCollector?.(Z)??[]},q=jr6($,J,Y.toolName,G);return{hookContext:G,helpers:q}}async function qP8($,Z,J,X,Y,Q,W,K){let{baseHookRequest:H,toolUseId:G,extraHookFields:q}=X;try{let V=await Yu0($.signal,()=>J.executeHookForStep(i0.preToolUse,{...H,tool_name:Q.toolName,tool_input:Y.getToolInput(),tool_use_id:G,...q}));if(V?.permission==="deny"){let O=V.user_message||`${Q.toolName} blocked by preToolUse hook`,F=Em0(O);try{HW(X.hookContextCollector,rq({hookEventName:i0.preToolUse,additionalContext:V.additional_context}))}catch(N){if(N instanceof uQ)P30.warn($,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:Q.toolName,actualLength:N.actualLength,maxLength:N.maxLength});else throw N}return await Y.fireFailureAsync(0,O,"permission_denied"),{type:"rejected",result:W(Z,F),reason:F}}if(V?.updated_input&&Q.applyUpdatedInput){if(Q.applyUpdatedInput(Z,V.updated_input),Y.setToolInput(Q.createToolInput(Z)),Q.getExtraHookFields)Y.setExtraHookFields(Q.getExtraHookFields(Z))}HW(X.hookContextCollector,rq({hookEventName:i0.preToolUse,additionalContext:V?.additional_context}))}catch(V){let O=J.hasFailClosedHooksForStep?.(i0.preToolUse,Q.toolName)??!1,F=V instanceof uQ,N=F?"preToolUse additional_context exceeded max size":"preToolUse hook failed";if(O){let L=V instanceof Error?V.message:"preToolUse hook error",U=A2(`${N}: ${L}`);return await Y.fireFailureAsync(0,U,"error"),{type:"rejected",result:W(Z,U),reason:U}}P30.warn($,F?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:Q.toolName,error:V instanceof Error?V.message:String(V),...F?{actualLength:V.actualLength,maxLength:V.maxLength}:{}})}if(K)try{let V=await K({ctx:$,args:Z,baseHookRequest:H,hookExecutor:J,toolInput:Y.getToolInput(),toolUseId:G,extraHookFields:X.extraHookFields});if(V!==void 0)return await Y.fireFailureAsync(0,"Pre-execution hook returned rejection","permission_denied"),{type:"rejected",result:V,reason:"Pre-execution hook returned rejection"}}catch(V){if(Q71(V))return await Y.fireFailureAsync(0,V.reason,V.failureType),{type:"rejected",result:W(Z,V.reason),reason:V.reason};throw V}return{type:"continue"}}function T5($){return $.toolCallId}function l6($,Z,J,X){return{async execute(Y,Q,W){let K=W71(Y,Z),{hookContext:H,helpers:G}=GP8(Y,Q,K,J,X,W),q;try{q=await qP8(Y,Q,K,H,G,X,X.createRejectedResult,X.runPreExecutionHooks)}catch(O){throw X.runCleanup?.(H.toolUseId),O}if(q.type==="rejected")return X.runCleanup?.(H.toolUseId),q.result;let V=fb0.now();try{let O=await $.execute(Y,Q,W),F=oU(fb0.now()-V);if(X.runPostExecutionHooks)try{let N=await X.runPostExecutionHooks({ctx:Y,args:Q,result:O,baseHookRequest:H.baseHookRequest,hookExecutor:K,toolInput:G.getToolInput(),toolUseId:H.toolUseId,executionDurationMs:F,extraHookFields:H.extraHookFields});if(N!==void 0)return await G.fireSuccessAsync(F,JSON.stringify(X.createSuccessOutput(Q,N))),X.runCleanup?.(H.toolUseId),N}catch(N){if(Q71(N))return await G.fireFailureAsync(F,N.reason,N.failureType),X.runCleanup?.(H.toolUseId),X.createRejectedResult(Q,N.reason);P30.warn(Y,"postExecutionHooks error",{toolName:X.toolName,error:N instanceof Error?N.message:String(N)})}if(X.isSuccess(O))await G.fireSuccessAsync(F,JSON.stringify(X.createSuccessOutput(Q,O)));else await G.fireFailureAsync(F,X.getErrorMessage(O),X.getFailureType?.(O)??"error",X.isInterrupt?.(O)??!1);return X.runCleanup?.(H.toolUseId),O}catch(O){let F=oU(fb0.now()-V);throw await G.fireFailureAsync(F,O instanceof Error?O.message:String(O),"error"),X.runCleanup?.(H.toolUseId),O}}}}function XI1($,Z,J,X){return{async*execute(Y,Q,W){let K=W71(Y,Z),{hookContext:H,helpers:G}=GP8(Y,Q,K,J,X,W),q=X.runPreExecutionHooks?async(L)=>{await X.runPreExecutionHooks(L);return}:void 0,V=await qP8(Y,Q,K,H,G,X,(L,U)=>X.createRejectedEvent(L,U),q);if(V.type==="rejected"){yield V.result;for(let L of JI1(X,H))yield L;return}let O=fb0.now(),F=X.createResultCollector();try{for await(let L of $.execute(Y,Q,W))F.onEvent(L),yield L}catch(L){let U=oU(fb0.now()-O),D=L instanceof Error?L.message:String(L);await G.fireFailureAsync(U,D,"error");for(let j of JI1(X,H))yield j;throw L}let N=oU(fb0.now()-O);if(X.runPostExecutionHooks)try{await X.runPostExecutionHooks({ctx:Y,args:Q,baseHookRequest:H.baseHookRequest,hookExecutor:K,toolInput:G.getToolInput(),toolUseId:H.toolUseId,extraHookFields:H.extraHookFields,collector:F,executionDurationMs:N})}catch(L){P30.warn(Y,"postExecutionHooks error",{toolName:X.toolName,error:L instanceof Error?L.message:String(L)})}if(F.isAborted())await G.fireFailureAsync(N,"Command was aborted","error",!0);else if(X.isStreamSuccess?.(F)??!0)await G.fireSuccessAsync(N,JSON.stringify(X.createSuccessOutput(Q,F)));else{let L=X.getStreamErrorMessage?.(Q,F)??`Command failed with exit code ${F.getExitCode()}`;await G.fireFailureAsync(N,L,"error")}for(let L of JI1(X,H))yield L}}}function*JI1($,Z){let J=Z.hookContextCollector;if(!$.createHookContextEvent||J===void 0||J.length===0)return;yield $.createHookContextEvent(J)}function W71($,Z){let J=L20($),X=$.get(YW1);if(J&&X===void 0)return Z;let Y=(Q)=>X?.during(Q)??Q;return{executeHookForStep:async(Q,W)=>{if(!J&&m21(Q)){await Y(Z.whenConfigReady());return}return Y(Z.executeHookForStep(Q,W))},hasFailClosedHooksForStep:(Q,W)=>Z.hasFailClosedHooksForStep?.(Q,W)??!1,hasHooksForStep:(Q)=>Z.hasHooksForStep?.(Q)??!0,whenConfigReady:()=>Y(Z.whenConfigReady())}}var P30,oU=($)=>Math.round($*1000)/1000;var OZ=P(()=>{J6();Qu0();F1();q9();$I1();bb0();P30=G1("generic-hooks")});var VP8=()=>{};import{lstat as Mr6}from"fs/promises";import E30 from"path";function Ir6($,Z){let J=E30.resolve($),X=E30.resolve(Z),Y=E30.relative(X,J);if(Y.length===0||Y===".."||Y.startsWith(`..${E30.sep}`)||E30.isAbsolute(Y))return"unsafe";let Q=Y.split(E30.sep).filter((H)=>H.length>0),W=[],K=X;for(let H of Q)K=E30.join(K,H),W.push(K);return W}function Tr6($){if(typeof $!=="object"||$===null||!("code"in $))return!1;let Z=$.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function YI1($,Z){let J=Ir6($,Z);if(J==="unsafe")return!0;for(let X of J)try{if((await Mr6(X)).isSymbolicLink())return!0}catch(Y){if(Tr6(Y))return!0;throw Y}return!1}var QI1=()=>{};import*as K71 from"fs/promises";class z71{async readFile($){try{return await K71.readFile($,"utf-8")}catch(Z){if(Z?.code==="ENOENT")return;throw Z}}async exists($){try{return await K71.access($),!0}catch{return!1}}async pathContainsSymlink($,Z){return YI1($,Z)}}var BP8=P(()=>{QI1()});class H71{innerExecutor;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X){this.innerExecutor=$;this.hooksAdditionalContextPromise=Z;this.teamHooksReadyPromise=J;this.hooksConfigLease=X}async execute($,Z,J){if(this.teamHooksReadyPromise)await this.teamHooksReadyPromise;let X=await this.innerExecutor.execute($,Z,J),Y=await this.hooksAdditionalContextPromise,Q=this.hooksConfigLease?new yB({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if(X.result.case==="success"&&(Y||Q)){let K=X.result.value.requestContext?.clone()??new S5;if(Y)K.hooksAdditionalContext=Y;if(Q)K.hooksConfig=Q;return new b9({result:{case:"success",value:new Y3({requestContext:K,servedFromDiskCache:X.result.value.servedFromDiskCache})}})}return X}}var WI1=P(()=>{c4()});function tU($){if(!$)return!1;return $.type!==GJ.INSECURE_NONE&&$.type!==GJ.UNSPECIFIED}var G71=P(()=>{OV()});async function hb0({hookExecutor:$,baseHookRequest:Z,toolUseId:J,command:X,cwd:Y,sandbox:Q}){let W=await $.executeHookForStep(i0.beforeShellExecution,{...Z,command:X,cwd:Y,sandbox:Q,tool_use_id:J});if(W?.permission==="deny"){let K=sq("Command execution",W.user_message);throw new T30(K)}if(W?.permission==="ask")return JW1(W.user_message);return}var q71=P(()=>{J6();q9();bb0()});class Vl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Pr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}class Bl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Er6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Pr6,Er6;var OP8=P(()=>{J6();q9();MV();q$();OZ();G71();BZ();q71();Pr6={toolName:i8.Shell,getToolCallId:T5,createToolInput:($)=>{let Z=$.workingDirectory||"";return{command:$.command,cwd:Z}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd},createRejectedResult:($,Z)=>new s7({result:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"BackgroundShell error";case"rejected":return $.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${$.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{shell_id:Z.result.value.shellId,pid:Z.result.value.pid};return{success:!0}},getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"",K=tU(J.sandboxPolicy);if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:K}));return}};Er6={toolName:i8.WriteShellStdin,createToolInput:($)=>({shell_id:$.shellId,chars_length:$.chars.length}),createRejectedResult:($,Z)=>new M7({result:{case:"error",value:new DY({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"WriteShellStdin error";return"Unknown error"},createSuccessOutput:($)=>({shell_id:$.shellId,success:!0})}});class Ol0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,kr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var kr6;var FP8=P(()=>{q4();OZ();BZ();kr6={toolName:i8.ComputerUse,getToolCallId:T5,createToolInput:($)=>({actions_count:$.actions.length}),createRejectedResult:($,Z)=>new T7({result:{case:"error",value:new $9({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"ComputerUse error";return"Unknown error"},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{action_count:Z.result.value.actionCount,duration_ms:Z.result.value.durationMs};return{success:!0}}}});class Fl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Rr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Rr6;var NP8=P(()=>{lV();OZ();BZ();Rr6={toolName:i8.Delete,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new C6({result:{case:"rejected",value:new UX({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"fileNotFound":return`File not found: ${$.result.value.path}`;case"notFile":return`Not a file: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;case"fileBusy":return`File busy: ${$.result.value.path}`;case"rejected":return $.result.value.reason||"Delete rejected";case"error":return $.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:($)=>({file_path:$.path,deleted:!0})}});class Nl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Cr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Cr6;var LP8=P(()=>{sV();OZ();BZ();Cr6={toolName:i8.ReadLints,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new S9({result:{case:"rejected",value:new aV({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Diagnostics error";case"rejected":return $.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{file_path:$.path,diagnostics_count:Z.result.value.totalDiagnostics};return{file_path:$.path,success:!0}}}});class Ll0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,_r6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var _r6;var UP8=P(()=>{wf0();OZ();BZ();_r6={toolName:i8.Fetch,getToolCallId:T5,createToolInput:($)=>({url:$.url}),applyUpdatedInput:($,Z)=>{if(typeof Z.url==="string")$.url=Z.url},createRejectedResult:($,Z)=>new wJ({result:{case:"error",value:new sW({url:$.url,error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"Fetch error";return"Unknown error"},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{url:$.url,status_code:Z.result.value.statusCode,content_length:Z.result.value.content.length};return{url:$.url,success:!0}}}});class Ul0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Sr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Sr6;var DP8=P(()=>{iV();OZ();BZ();Sr6={toolName:i8.Grep,getToolCallId:T5,createToolInput:($)=>({pattern:$.pattern,file_path:$.path,glob:$.glob,output_mode:$.outputMode}),applyUpdatedInput:($,Z)=>{if(typeof Z.pattern==="string")$.pattern=Z.pattern;if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new v$({result:{case:"error",value:new P7({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"Grep error";return"Unknown error"},createSuccessOutput:($)=>({pattern:$.pattern,success:!0})}});class Dl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,vr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var vr6;var AP8=P(()=>{H4();OZ();BZ();vr6={toolName:i8.LS,getToolCallId:T5,createToolInput:($)=>({file_path:$.path,ignore:$.ignore}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new s$({result:{case:"rejected",value:new yV({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Ls error";case"rejected":return $.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:($)=>$.result.case==="timeout"?"timeout":"error",createSuccessOutput:($)=>({file_path:$.path,success:!0})}});import{randomUUID as yr6}from"crypto";import{performance as KI1}from"perf_hooks";import{Value as xr6}from"@bufbuild/protobuf";function zI1($){if($===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return!0;if(Array.isArray($))return $.every(zI1);if(typeof $==="object")return Object.values($).every((Z)=>Z!==void 0&&zI1(Z));return!1}function wP8($,Z,J,X){try{return rq({hookEventName:J,additionalContext:X})}catch(Y){if(Y instanceof uQ)return eU.warn($,`${J} additional_context exceeded max size; dropping carrier`,{toolName:Z,hookEventName:J,actualLength:Y.actualLength,maxLength:Y.maxLength}),[];throw Y}}class Al0{innerExecutor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksConfigLease;constructor($,Z,J,X,Y){this.innerExecutor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksConfigLease=Y}async execute($,Z,J){if(Z.smartModeApprovalOnly)return this.innerExecutor.execute($,Z,J);if(Z.symbolicPathArguments.length>0&&(this.hooksConfigLease?.hasHookForStep(i0.preToolUse)===!0||this.hooksConfigLease?.hasHookForStep(i0.beforeMCPExecution)===!0))return new e8({result:{case:"error",value:new k7({error:`"${HQ}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});let X=W71($,this.hookExecutor),Y=this.baseHookRequestExtractor($),Q=yr6(),W=J?.hookContextCollector??[],K=Object.fromEntries(Object.entries(Z.args).map(([D,j])=>[D,j?.toJson()])),H=`MCP:${Z.toolName}`;try{let D=await X.executeHookForStep(i0.preToolUse,{...Y,tool_name:H,tool_input:K,tool_use_id:Q});if(D?.permission==="deny"){let j=D.user_message||"MCP tool blocked by preToolUse hook";try{HW(W,rq({hookEventName:i0.preToolUse,additionalContext:D.additional_context}))}catch(w){if(w instanceof uQ)eU.warn($,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:H,actualLength:w.actualLength,maxLength:w.maxLength});else throw w}return await this.firePostToolUseFailureAsync($,X,Y,H,K,j,"permission_denied",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:sq("MCP tool execution",j),isReadonly:!1})}})}if(D?.updated_input)try{for(let[j,w]of Object.entries(D.updated_input)){if(w===void 0)continue;if(!zI1(w))throw TypeError("updated_input value is not JSON");Z.args[j]=xr6.fromJson(w)}K=Object.fromEntries(Object.entries(Z.args).map(([j,w])=>[j,w?.toJson()]))}catch(j){eU.warn($,"Failed to merge updated_input for MCP",{error:j instanceof Error?j.message:String(j)})}HW(W,rq({hookEventName:i0.preToolUse,additionalContext:D?.additional_context}))}catch(D){let j=X.hasFailClosedHooksForStep?.(i0.preToolUse,H)??!1,w=D instanceof uQ,k=w?"preToolUse additional_context exceeded max size":"preToolUse hook failed";if(j){let T=D instanceof Error?D.message:"preToolUse hook error",I=A2(`${k}: ${T}`);return await this.firePostToolUseFailureAsync($,X,Y,H,K,I,"error",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:sq("MCP tool execution",I),isReadonly:!1})}})}eU.warn($,w?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:H,error:D instanceof Error?D.message:String(D),...w?{actualLength:D.actualLength,maxLength:D.maxLength}:{}})}let q=(await this.mcpLease?.getClient($,Z.providerIdentifier))?.config,V,O=q&&"url"in q&&q.url?q.url:void 0;if(O!==void 0)V={url:O};else if(q&&"command"in q)V={command:[q.command,...q.args??[]].filter(Boolean).join(" ")};else V={command:Z.providerIdentifier};let F={mcp_server_name:Z.providerIdentifier,...O!==void 0?{mcp_server_url:O}:{}},N={...Y,tool_name:Z.toolName,tool_input:JSON.stringify(K),tool_use_id:Q,...F,...V},L=hG($,i0.beforeMCPExecution)?await X.executeHookForStep(i0.beforeMCPExecution,N):void 0;if(L?.permission==="deny"){let D=sq("MCP tool execution",L.user_message);return await this.firePostToolUseFailureAsync($,X,Y,H,K,D,"permission_denied",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:D,isReadonly:!1})}})}let U=KI1.now();try{let D=await this.innerExecutor.execute($,Z,J),j=oU(KI1.now()-U),w="{}";if(D.result.case==="success")try{let I=D.result.value.content.map((M)=>{if(M.content.case==="text")return{type:"text",text:M.content.value.text};else if(M.content.case==="image")return{type:"image",data:Buffer.from(M.content.value.data).toString("base64"),mimeType:M.content.value.mimeType};return{type:"unknown"}});w=JSON.stringify({content:I,isError:D.result.value.isError})}catch(I){eU.warn($,"Failed to serialize MCP result",{error:I instanceof Error?I.message:String(I)}),w=JSON.stringify({error:"Failed to serialize result"})}else if(D.result.case==="error")w=JSON.stringify({error:D.result.value.error});else if(D.result.case==="rejected")w=JSON.stringify({rejected:!0,reason:D.result.value.reason});else if(D.result.case==="permissionDenied")w=JSON.stringify({permissionDenied:!0,error:D.result.value.error});let k={...Y,tool_name:Z.toolName,tool_input:JSON.stringify(K),result_json:w,duration:j,tool_use_id:Q,...F};await X.executeHookForStep(i0.afterMCPExecution,k);let T=await this.firePostToolUse($,X,Y,H,K,w,j,Q,W);if(T?.updated_mcp_tool_output!==void 0)try{let I=T.updated_mcp_tool_output,M=[];if(typeof I==="string")M.push(new H5({content:{case:"text",value:new $7({text:I})}}));else if(typeof I==="object"&&I!==null&&"content"in I&&Array.isArray(I.content)){let v=I.content;for(let R of v)if(typeof R==="object"&&R!==null&&"type"in R&&R.type==="text"&&"text"in R)M.push(new H5({content:{case:"text",value:new $7({text:String(R.text)})}}));else M.push(new H5({content:{case:"text",value:new $7({text:JSON.stringify(R)})}}))}else M.push(new H5({content:{case:"text",value:new $7({text:JSON.stringify(I)})}}));let C=typeof I==="object"&&I!==null&&"isError"in I?Boolean(I.isError):!1;return new e8({result:{case:"success",value:new AJ({content:M,isError:C})}})}catch(I){return eU.warn($,"Failed to process updated_mcp_tool_output",{error:I instanceof Error?I.message:String(I)}),D}return D}catch(D){let j=oU(KI1.now()-U),w=D instanceof Error?D.message:String(D);throw await this.firePostToolUseFailureAsync($,X,Y,H,K,w,"error",j,Q,!1,W),D}}async firePostToolUse($,Z,J,X,Y,Q,W,K,H){try{let G=await Z.executeHookForStep(i0.postToolUse,{...J,tool_name:X,tool_input:Y,tool_output:Q,duration:W,tool_use_id:K});return HW(H,wP8($,X,i0.postToolUse,G?.additional_context)),G}catch(G){eU.warn($,"postToolUse hook error in MCP executor",{error:G instanceof Error?G.message:String(G)});return}}async firePostToolUseFailureAsync($,Z,J,X,Y,Q,W,K,H,G,q){try{let V=await Z.executeHookForStep(i0.postToolUseFailure,{...J,tool_name:X,tool_input:Y,error_message:Q,failure_type:W,duration:K,tool_use_id:H,is_interrupt:G});HW(q,wP8($,X,i0.postToolUseFailure,V?.additional_context))}catch(V){eU.warn($,"postToolUseFailure hook error in MCP executor",{error:V instanceof Error?V.message:String(V)})}}}var eU;var jP8=P(()=>{J6();F1();q9();$I1();bb0();wZ();OZ();eU=G1("hooks-exec:mcp")});class wl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,br6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}class jl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,fr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var br6,fr6;var MP8=P(()=>{wZ();OZ();BZ();br6={toolName:i8.ListMcpResources,createToolInput:($)=>({server:$.server}),applyUpdatedInput:($,Z)=>{if(typeof Z.server==="string")$.server=Z.server},createRejectedResult:($,Z)=>new y9({result:{case:"error",value:new j4({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"ListMcpResources error";case"rejected":return $.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{resources_count:Z.result.value.resources.length};return{success:!0}}};fr6={toolName:i8.FetchMcpResource,createToolInput:($)=>({server:$.server,uri:$.uri,download_path:$.downloadPath}),applyUpdatedInput:($,Z)=>{if(typeof Z.server==="string")$.server=Z.server;if(typeof Z.uri==="string")$.uri=Z.uri;if(typeof Z.download_path==="string")$.downloadPath=Z.download_path},createRejectedResult:($,Z)=>new F$({result:{case:"error",value:new AZ({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"ReadMcpResource error";case"rejected":return $.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success"){let J=Z.result.value;return{uri:$.uri,name:J.name,mime_type:J.mimeType,download_path:J.downloadPath,content_type:J.content.case,content_length:J.content.case==="text"?J.content.value.length:J.content.case==="blob"?J.content.value.length:void 0}}return{uri:$.uri,success:!0}}}});class mb0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=new oS0(l6($,Z,J,hr6))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var hr6;var IP8=P(()=>{J6();q9();jN();OZ();bb0();BZ();hr6={toolName:i8.Read,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new N6({result:{case:"rejected",value:new S3({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Read error";case"rejected":return $.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;case"invalidFile":return`Invalid file: ${$.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success"){let J=Z.result.value.output.case==="content"?Z.result.value.output.value:"";return{file_path:$.path,content_length:J.length}}return{file_path:$.path,success:!0}},runPostExecutionHooks:async($)=>{let{args:Z,result:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$;if(J.result.case!=="success"||Y.hasHooksForStep?.(i0.beforeReadFile)===!1)return;let W=J.result.value.output.case==="content"?J.result.value.output.value:"",K=await ZI1(()=>Y.executeHookForStep(i0.beforeReadFile,{...X,content:W,file_path:Z.path,attachments:[],tool_use_id:Q}),"File read");if(K?.permission==="deny"){let H=sq("File read",K.user_message);throw new T30(H)}return}}});class Ml0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,mr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var mr6;var TP8=P(()=>{kD();OZ();BZ();mr6={toolName:i8.RecordScreen,getToolCallId:T5,createToolInput:($)=>({mode:$.mode,save_as_filename:$.saveAsFilename}),createRejectedResult:($,Z)=>new I7({result:{case:"failure",value:new _W({error:Z,kind:R6.HOOK_REJECTED})}}),isSuccess:($)=>$.result.case!=="failure",getErrorMessage:($)=>{if($.result.case==="failure")return $.result.value.error||"RecordScreen failed";return"Unknown error"},createSuccessOutput:($,Z)=>({result_type:Z.result.case})}});function PP8($){if($.result.case==="success")return $.result.value.stdout+$.result.value.stderr;else if($.result.case==="failure")return $.result.value.stdout+$.result.value.stderr;return""}class Il0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,gr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var gr6;var EP8=P(()=>{J6();q9();q$();OZ();G71();BZ();q71();gr6={toolName:i8.Shell,createToolInput:($)=>{let Z=$.workingDirectory||"",J=$.timeout;return{command:$.command,cwd:Z,...typeof J==="number"&&J>0&&{timeout:J}}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd;if(typeof Z.timeout==="number"&&Z.timeout>=0)$.timeout=Z.timeout},createRejectedResult:($,Z)=>new G6({result:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),isSuccess:($)=>{if($.result.case==="success")return!0;if($.result.case==="failure"&&!$.result.value.aborted)return!0;return!1},getErrorMessage:($)=>{switch($.result.case){case"timeout":return`Command timed out after ${$.result.value.timeoutMs}ms`;case"spawnError":return $.result.value.error||"Failed to spawn command";case"failure":if($.result.value.aborted)return"Command was aborted";return"Command failed";case"rejected":return $.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:($)=>{if($.result.case==="timeout")return"timeout";return"error"},isInterrupt:($)=>{return $.result.case==="failure"&&$.result.value.aborted},createSuccessOutput:($,Z)=>{let J=PP8(Z),X=Z.result.case==="success"?0:1;return{output:J,exitCode:X}},getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"";if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:tU(J.requestedSandboxPolicy)}));return},runPostExecutionHooks:async($)=>{let{args:Z,result:J,baseHookRequest:X,hookExecutor:Y,executionDurationMs:Q,toolUseId:W}=$,K=PP8(J);await Y.executeHookForStep(i0.afterShellExecution,{...X,command:Z.command,output:K,duration:Q,sandbox:tU(Z.requestedSandboxPolicy),tool_use_id:W});return}}});class kP8{output="";exitEvent;onEvent($){if($.event.case==="stdout")this.output+=$.event.value.data;else if($.event.case==="stderr")this.output+=$.event.value.data;else if($.event.case==="exit")this.exitEvent=$.event.value}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}class Tl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=XI1($,Z,J,ur6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var ur6;var RP8=P(()=>{J6();q9();q$();OZ();G71();BZ();q71();ur6={toolName:i8.Shell,createToolInput:($)=>{let Z=$.workingDirectory||"",J=$.timeout;return{command:$.command,cwd:Z,...typeof J==="number"&&J>0&&{timeout:J}}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd;if(typeof Z.timeout==="number"&&Z.timeout>=0)$.timeout=Z.timeout},createRejectedEvent:($,Z)=>new b6({event:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),createHookContextEvent:($)=>new b6({event:{case:"hookContext",value:new RW({hookAdditionalContexts:[...$]})}}),getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},createResultCollector:()=>new kP8,createSuccessOutput:($,Z)=>({output:Z.getOutput(),exitCode:Z.getExitCode()}),isStreamSuccess:($)=>$.getExitCode()===0,getStreamErrorMessage:($,Z)=>{return Z.getOutput().trim()||`Command failed with exit code ${Z.getExitCode()}`},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"",K=tU(J.requestedSandboxPolicy);if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:K}))},runPostExecutionHooks:async($)=>{let{args:Z,baseHookRequest:J,hookExecutor:X,collector:Y,executionDurationMs:Q,toolUseId:W}=$,K=tU(Z.requestedSandboxPolicy);await X.executeHookForStep(i0.afterShellExecution,{...J,command:Z.command,output:Y.getOutput(),duration:Q,sandbox:K,tool_use_id:W})}}});import{stat as cr6}from"fs/promises";function GI1($,Z){let J=sd0("","",$,Z,"","",{context:0,timeout:dr6});if(J===void 0)return[{old_string:"",new_string:Z}];if(J.hunks.length===0)return[];return J.hunks.map((X)=>{let Y=[],Q=[];for(let W of X.lines)if(W.startsWith("-"))Y.push(W.slice(1));else if(W.startsWith("+"))Q.push(W.slice(1));return{old_string:Y.join(` `),new_string:Q.join(` -`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} -+`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,attributionConfigProvider:$.attributionConfigProvider,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({attributionConfigProvider:N7(Q,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} ++`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,attributionConfigProvider:$.attributionConfigProvider,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,($.plugins||$.pluginBootstrap)&&__p("plugins"),X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,$.mcp&&__p("mcp"),X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,$.hooks&&__p("hooks"),X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility&&__p("skills"),$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return __p("connecting"),X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({attributionConfigProvider:N7(Q,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} ${X.finalMessage}`}).join(` @@ -46,12 +46,12 @@ index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a `);await iS8($,J.length>0?`${J} `:"")}function ZP1($){return{...$,createdAt:new Date($.createdAt).getTime()}}Vm0();br0();s71();n$();Zm0();async function L7($,Z){try{return await Z()}catch(J){throw F6(J,{operation:$})}}class K91{constructor(){}static async create($){return L7("Agent.create",async()=>{if($.agentId===void 0&&$.cloud?.envVars!==void 0)return iT1($);let Z=$.agentId??($.cloud?gS0():mS0()),J={...$,agentId:Z};return iT1(J)})}static async resume($,Z){return L7("Agent.resume",()=>FS8($,Z))}static async prompt($,Z){return L7("Agent.prompt",async()=>{let J=await K91.create(Z??{});try{return await(await J.send($)).wait()}finally{await J[Symbol.asyncDispose]()}})}static async list($){return L7("Agent.list",()=>LS8($))}static async listRuns($,Z){return L7("Agent.listRuns",()=>US8($,Z))}static async getRun($,Z){return L7("Agent.getRun",()=>DS8($,Z))}static async cancelRun($,Z){return L7("Agent.cancelRun",()=>AS8($,Z))}static async get($,Z){return L7("Agent.get",()=>IS8($,Z))}static async archive($,Z){return L7("Agent.archive",()=>TS8($,Z))}static async unarchive($,Z){return L7("Agent.unarchive",()=>PS8($,Z))}static async delete($,Z){return L7("Agent.delete",()=>ES8($,Z))}static async getUsage($,Z){return L7("Agent.getUsage",()=>RS8($,Z))}static messages={list($,Z){return L7("Agent.messages.list",()=>wS8($,Z))}}}class XP1{constructor(){}static configure($){Ur0($)}static async me($){return L7("Cursor.me",()=>CS8($))}static models={list($){return L7("Cursor.models.list",()=>_S8($))}};static repositories={list($){return L7("Cursor.repositories.list",()=>SS8($))}};static auth={login($){return L7("Cursor.auth.login",()=>Py1($))},logout($){return L7("Cursor.auth.logout",()=>Ey1($))},status($){return L7("Cursor.auth.status",()=>ky1($))}}}import*as t8 from"zod/v3";RT1();var zv8=t8.object({text:t8.string()}),Hv8=t8.object({text:t8.string(),thinkingDurationMs:t8.number().optional()}),Gv8=t8.object({text:t8.string()}),qv8=t8.object({command:t8.string(),workingDirectory:t8.string().optional()}),Vv8=t8.object({stdout:t8.string(),stderr:t8.string(),exitCode:t8.number()}),Bv8=t8.discriminatedUnion("type",[t8.object({type:t8.literal("assistantMessage"),message:zv8}),t8.object({type:t8.literal("toolCall"),message:Jf0}),t8.object({type:t8.literal("thinkingMessage"),message:Hv8})]),Ov8=t8.object({userMessage:Gv8.optional(),steps:t8.array(Bv8)}),Fv8=t8.object({shellCommand:qv8.optional(),shellOutput:Vv8.optional()}),l5$=t8.discriminatedUnion("type",[t8.object({type:t8.literal("agentConversationTurn"),turn:Ov8}),t8.object({type:t8.literal("shellConversationTurn"),turn:Fv8})]);fT1();function i5$($){return $.type}kT1();export{F6 as wrapSdkError,Qh0 as unionFs,KQ0 as tempFs,Zh0 as strReplaceOnFileSystem,gS8 as startLocalRunEventNotifierServer,DC0 as remapPathError,mJ1 as readOnlyFs,vG as paginateRunDocuments,eN as paginateCheckpointBlobIds,$L as paginateAgentDocuments,en0 as overlayFs,_C0 as localRunStreamEventToSdkMessage,D8$ as isUserMessage,Ah0 as isTerminalLocalRunStreamEvent,w8$ as isMessage,QQ0 as isInvalidGrepPatternError,_3 as isFileNotFoundError,A8$ as isAssistantMessage,i5$ as getTurnType,K20 as getDefaultSdkStateRoot,Qf0 as getDefaultSdkAuthPath,hJ1 as emptyFs,yh1 as decodeSdkMessageRunStreamEvent,Dh0 as decodeLocalRunStreamEvent,Ua0 as createSdkMessageRunStreamEvent,mS8 as createLocalRunEventNotifier,uS8 as createInMemoryRunEventNotifier,XY1 as createFileSystemTools,WY as createAgentPlatform,hv8 as convertError,HV as convertConnectError,Ur0 as configureCursorSdk,m41 as composeLocalAgentStore,dJ1 as childOverlayFs,XQ0 as WriteFailedError,al0 as UserMessageSchema,b_8 as UserMessageAppendedUpdateSchema,W20 as UnsupportedRunOperationError,zJ as UnknownAgentError,c_8 as TurnEndedUpdateSchema,_T1 as ToolCallStartedUpdateSchema,a_8 as ToolCallDeltaUpdateSchema,ST1 as ToolCallCompletedUpdateSchema,f_8 as TokenDeltaUpdateSchema,vT1 as ThinkingDeltaUpdateSchema,yT1 as ThinkingCompletedUpdateSchema,CT1 as TextDeltaUpdateSchema,h_8 as SummaryUpdateSchema,m_8 as SummaryStartedUpdateSchema,g_8 as SummaryCompletedUpdateSchema,Vv8 as ShellOutputSchema,u_8 as ShellOutputDeltaUpdateSchema,Fv8 as ShellConversationTurnSchema,qv8 as ShellCommandSchema,Gv8 as SdkUserMessageSchema,Hv8 as SdkThinkingMessageSchema,zv8 as SdkAssistantMessageSchema,J7 as ReadOnlyMountError,wW as RateLimitError,g9 as PathError,xT1 as PartialToolCallUpdateSchema,JQ0 as NoMountError,A7 as NetworkError,n_8 as NestedTaskUpdateSchema,d_8 as ModelCallCompletedUpdateSchema,__8 as MessageSchema,tl0 as LocalRunEventNotifierServer,Z91 as LocalRunEventNotifier,OQ0 as LOCAL_RUN_STREAM_SCHEMA_VERSION,Na0 as LOCAL_RUN_STREAM_EVENT_TYPE,Q91 as JsonlLocalAgentStore,JP1 as JSONL_LOCAL_AGENT_STORE_FILES,NN as InvalidGrepPatternError,bT1 as InteractionUpdateSchema,Ki0 as IntegrationNotConnectedError,J91 as InMemoryRunEventNotifier,A91 as InMemoryCredentialStore,C_8 as ImageSchema,kJ as FileNotFoundError,Wf0 as FileCredentialStore,zi0 as FeatureUnavailableError,JG as FILE_SYSTEM_SCAN_LIMIT,G2 as EditError,YQ0 as DeleteNotSupportedError,LJ1 as DEFAULT_LOGIN_API_KEY_TTL_MS,BX as CursorSdkError,x30 as CursorAgentPlatform,jW as CursorAgentError,XP1 as Cursor,l5$ as ConversationTurnSchema,Bv8 as ConversationStepSchema,L1 as ConfigurationError,E5 as AuthenticationError,ET1 as AssistantMessageSchema,ND as AgentNotFoundError,Ov8 as AgentConversationTurnSchema,Wi0 as AgentBusyError,K91 as Agent}; diff --git a/dist/cjs/977.js b/dist/cjs/977.js -index 9b48bdf0d6ff3c60e525736752d11daeebb96fef..bbba4a6c1adee197776114ecccc4f7cd6b5b8d5d 100644 +index 9b48bdf0d6ff3c60e525736752d11daeebb96fef..559fc3999ab224e405b959b47548819a2aa634b1 100644 --- a/dist/cjs/977.js +++ b/dist/cjs/977.js @@ -1,4 +1,4 @@ -exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` -+exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({attributionConfigProvider:EB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new c.QFf({action:{case:"resumeAction",value:new c.qKo}}):!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` ++exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,(e.plugins||e.pluginBootstrap)&&__p("plugins"),n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,e.mcp&&__p("mcp"),n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,e.hooks&&__p("hooks"),n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility&&__p("skills"),e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return __p("connecting"),n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({attributionConfigProvider:EB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new c.QFf({action:{case:"resumeAction",value:new c.qKo}}):!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` function global:__cursorUtf8FromLatin1 { param([string]$Text) Set-StrictMode -Off @@ -81,12 +81,12 @@ index ea133a0f358555bcf9393dba47563ffb208f24ad..10bef97ace282f9c83523150bd73e49c +(()=>{"use strict";var t,r,e,n={"./src/agent/analytics-agent-name.ts"(t,r,e){function n(t){if("string"!=typeof t)return;const r=t.trim();return r.length>0?r:void 0}e.d(r,{o:()=>n})},"./src/agent/analytics-prompt-hash.ts"(t,r,e){e.d(r,{E:()=>s});var n=e("node:crypto");function s(t){if("string"==typeof t&&0!==t.length)return(0,n.createHash)("sha256").update(t,"utf8").digest("hex")}},"./src/agent/analytics.ts"(t,r,e){e.d(r,{rd:()=>Q,ou:()=>rt,GY:()=>Y,CI:()=>Z,id:()=>et,G5:()=>X,Zn:()=>V,pL:()=>tt});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ClientOS",[[0,"CLIENT_OS_UNSPECIFIED"],[1,"CLIENT_OS_WINDOWS"],[2,"CLIENT_OS_MACOS"],[3,"CLIENT_OS_LINUX"],[4,"CLIENT_OS_IOS"],[5,"CLIENT_OS_ANDROID"]]),u=(0,s.QT)(n.proto3,i,"ClientLogLevel",[[0,"UNSPECIFIED"],[1,"INFO"],[2,"DEBUG"],[3,"WARN"],[4,"ERROR"]],1),c=(0,s.QT)(n.proto3,i,"StatsigExposureKind",[[0,"UNSPECIFIED"],[1,"FEATURE_GATE"],[2,"EXPERIMENT"],[3,"DYNAMIC_CONFIG"],[4,"LAYER_PARAMETER"]],1);class l extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BootstrapStatsigRequest|1 ignore_dev_status 8?|2 operating_system #0?|3 device_model 9?|4 os_version 9?|5 form_factor 9?|6 stable_id 9?|7 client_channel 9?|8 bundle_id 9?|9 mobile_app_store_country 9?|10 native_build 9?|11 ota_update_id 9?|12 ota_runtime_version 9?|13 ota_embedded_launch 8?|14 previous_response_hash 9?|15 name_filter #1|16 grok_build_version 9?|17 grok_build_channel 9?|18 sign_in_email 9?",a,m]}}class m extends o{constructor(t){super(),this.gates=[],this.configs=[],this.layers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["BootstrapStatsigRequest.NameFilter|1 gates 9*|2 configs 9*|3 layers 9*"]}}class f extends o{constructor(t){super(),this.config="",this.generatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["BootstrapStatsigResponse|1 config 9|2 generated_at_ms 4"]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GetFirstWindowStatsigDecisionRequest|1 operating_system #0?",a]}}class p extends o{constructor(t){super(),this.variant="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GetFirstWindowStatsigDecisionResponse|1 variant 9|2 reason 9"]}}class h extends o{constructor(t){super(),this.name="",this.kind=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["StatsigExposure|1 name 9|2 kind #0|3 parameter 9?",c]}}class g extends o{constructor(t){super(),this.exposures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["LogStatsigExposuresRequest|1 exposures #0*|2 ignore_dev_status 8?|3 operating_system #1?|4 grok_build_version 9?|5 grok_build_channel 9?",h,a]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["LogStatsigExposuresResponse"]}}class J extends o{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["EventData|1 string_value 9 data|2 int_value 3 data|3 bool_value 8 data|4 double_value 1 data"]}}class w extends o{constructor(t){super(),this.eventName="",this.eventData={},this.timestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["AnalyticsEvent|1 event_name 9|2 event_data 9,#0|3 timestamp 3",J]}}class y extends o{constructor(t){super(),this.events=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["TrackEventsRequest|1 events #0*",w]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["TrackEventsResponse"]}}class q extends o{constructor(t){super(),this.event="",this.timestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["BatchEvent|1 event 9|2 properties #0|3 timestamp 3|4 user_id 9?|5 anonymous_id 9?|6 message_id 9?|7 context #1?",n.Struct,B]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["AnalyticsContext|1 client #0?",I]}}class I extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ClientInfo|1 os 9?|2 arch 9?|3 os_version 9?|4 version 9?|5 layout 9?|6 glass_renderer 9?"]}}class P extends o{constructor(t){super(),this.events=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["BatchRequest|1 events #0*",q]}}class b extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["BatchResponse"]}}class R extends o{constructor(t){super(),this.level=u.UNSPECIFIED,this.message="",this.metadata={},this.timestamp=n.protoInt64.zero,this.key="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ClientLogEntry|1 level #0|2 message 9|3 metadata 9,9|4 timestamp 3|5 error_message 9?|6 error_stack 9?|7 key 9",u]}}class v extends o{constructor(t){super(),this.logs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["SubmitLogsRequest|1 logs #0*",R]}}class x extends o{constructor(t){super(),this.success=!1,this.logsProcessed=0,this.logsDropped=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SubmitLogsResponse|1 success 8|2 error_message 9?|3 logs_processed 13|4 logs_dropped 13"]}}class k extends o{constructor(t){super(),this.conversationId="",this.transcript="",this.lastUpdatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["IngestConversationRequest|1 conversation_id 9|2 transcript 9|3 transcript_json 9?|4 mode 9?|5 model 9?|6 last_updated_at 3"]}}class E extends o{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["IngestConversationResponse|1 success 8|2 summary 9?|3 detailed_summary 9?|4 error_message 9?"]}}class C extends o{constructor(t){super(),this.token="",this.payload="",this.payloadHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["UploadIssueTraceRequest|1 token 9|2 payload 9|3 payload_hash 9"]}}class T extends o{constructor(t){super(),this.eventId="",this.size=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["UploadIssueTraceResponse|1 event_id 9|2 size 3"]}}class U extends o{constructor(t){super(),this.token="",this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["DownloadIssueTracesRequest|1 token 9|2 limit 5"]}}class A extends o{constructor(t){super(),this.data=new Uint8Array(0),this.totalTraces=0,this.totalBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["DownloadIssueTracesResponse|1 data 12|2 total_traces 5|3 total_bytes 3"]}}var $=e("@connectrpc/connect");function M(t){const r={};if(!t)return r;for(const[e,n]of Object.entries(t))"string"==typeof n?r[e]=new J({data:{case:"stringValue",value:n}}):"number"==typeof n?r[e]=new J({data:{case:"doubleValue",value:n}}):"boolean"==typeof n?r[e]=new J({data:{case:"boolValue",value:n}}):"bigint"==typeof n&&(r[e]=new J({data:{case:"intValue",value:n}}));return r}const O=Symbol("token_check_timeout"),D={[$.Code.Canceled]:"cancelled",[$.Code.Unknown]:"unknown",[$.Code.InvalidArgument]:"invalid_argument",[$.Code.DeadlineExceeded]:"deadline_exceeded",[$.Code.NotFound]:"not_found",[$.Code.AlreadyExists]:"already_exists",[$.Code.PermissionDenied]:"permission_denied",[$.Code.ResourceExhausted]:"resource_exhausted",[$.Code.FailedPrecondition]:"failed_precondition",[$.Code.Unimplemented]:"unimplemented",[$.Code.Internal]:"internal",[$.Code.Unavailable]:"unavailable",[$.Code.DataLoss]:"data_loss",[$.Code.Unauthenticated]:"unauthenticated"};class N{constructor(t){this.buffer=[],this.flushTimer=null,this.activeFlush=null,this.droppedOldestSinceLastOutcome=0,this.client=t.client,this.tokenProvider=t.tokenProvider,this.bufferLimit=t.bufferLimit??200,this.flushIntervalMs=t.flushIntervalMs??3e3,this.normalFlushTimeoutMs=t.normalFlushTimeoutMs??2500,this.onDebug=t.onDebug??(()=>{}),this.onDeliveryOutcome=t.onDeliveryOutcome??(()=>{})}track(t,r,e){const n="number"==typeof e?BigInt(e):BigInt(Date.now()),s=new w({eventName:t,eventData:M(r),timestamp:n});this.buffer.push(s),this.trimRetainedEvents(),this.buffer.length>=this.bufferLimit?this.flushInBackground():this.scheduleFlush()}async flush(t){for(;;){if(this.activeFlush){if(await this.activeFlush,0===this.buffer.length)return;continue}if(0===this.buffer.length)return;const r=this.flushOnce(t);this.activeFlush=r;let e=0;try{e=await r}finally{this.activeFlush===r&&(this.activeFlush=null)}if(0===this.buffer.length||0===e)return}}async flushOnce(t){if(0===this.buffer.length)return 0;const r=this.buffer.slice(),e=new Set(r);this.inFlightEvents=e;const n=new AbortController,s=setTimeout((()=>n.abort()),t);s.unref?.();try{try{const t=await Promise.race([this.tokenProvider.getAccessToken(),new Promise((t=>{n.signal.addEventListener("abort",(()=>t(O)),{once:!0})}))]);if(t===O)return this.onDebug("analytics.flush.deferred",{reason:"token_check_timed_out",count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("token_check_timed_out"),0;if(!t)return this.onDebug("analytics.flush.deferred",{reason:"no_token",count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("no_token"),0}catch(t){return this.onDebug("analytics.flush.deferred",{reason:"token_check_failed",error:t,count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("token_check_failed"),0}try{return await this.client.trackEvents(new y({events:r}),{signal:n.signal}),this.inFlightEvents=void 0,this.buffer=this.buffer.filter((t=>!e.has(t))),this.reportOutcome({outcome:"sent",sentCount:r.length,retainedCount:this.buffer.length,droppedOldestCount:this.takeDroppedOldestCount(),oldestRowAgeMs:this.oldestRowAgeMs()}),r.length}catch(t){return this.releaseInFlightEvents(),this.onDebug("analytics.flush.error",{error:t}),this.reportRetained("rpc_failed",(i=t,n.signal.aborted?"aborted":i instanceof $.ConnectError?D[i.code]??"other":"other")),0}}finally{clearTimeout(s)}var i}releaseInFlightEvents(){this.inFlightEvents=void 0,this.trimRetainedEvents()}flushInBackground(){this.flush(this.normalFlushTimeoutMs)}reportRetained(t,r){this.reportOutcome({outcome:"retained",reason:t,retainedCount:this.buffer.length,droppedOldestCount:this.takeDroppedOldestCount(),oldestRowAgeMs:this.oldestRowAgeMs(),...void 0===r?{}:{rpcFailureClass:r}})}reportOutcome(t){try{this.onDeliveryOutcome(t)}catch{}}takeDroppedOldestCount(){const t=this.droppedOldestSinceLastOutcome;return this.droppedOldestSinceLastOutcome=0,t}trimRetainedEvents(){let t=(void 0===this.inFlightEvents?this.buffer.length:this.buffer.reduce(((t,r)=>t+(!0===this.inFlightEvents?.has(r)?0:1)),0))-this.bufferLimit;if(t<=0)return;const r=t;this.buffer=this.buffer.filter((r=>t<=0||!0===this.inFlightEvents?.has(r)||(t-=1,!1))),this.droppedOldestSinceLastOutcome+=r}oldestRowAgeMs(){const t=this.buffer[0]?.timestamp;return void 0===t?0:Math.max(0,Date.now()-Number(t))}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout((()=>{this.flushTimer=null,this.flushInBackground()}),this.flushIntervalMs),this.flushTimer.unref?.())}}class G{constructor(t,r,e){this.apiKey=t,this.baseUrl=r,this.exchange=e,this.cached=null,this.inflight=null}async getAccessToken(){if(this.cached)return this.cached;if(this.inflight)return this.inflight;const t=this.exchange(this.apiKey,this.baseUrl).then((r=>(this.inflight===t&&(this.cached=r??null),r??null))).catch((()=>null)).finally((()=>{this.inflight===t&&(this.inflight=null)}));return this.inflight=t,this.inflight}invalidate(){this.cached=null,this.inflight=null}}const L={typeName:"aiserver.v1.AnalyticsService",methods:{trackEvents:{name:"TrackEvents",I:y,O:S,kind:n.MethodKind.Unary},batch:{name:"Batch",I:P,O:b,kind:n.MethodKind.Unary},bootstrapStatsig:{name:"BootstrapStatsig",I:l,O:f,kind:n.MethodKind.Unary},getFirstWindowStatsigDecision:{name:"GetFirstWindowStatsigDecision",I:d,O:p,kind:n.MethodKind.Unary},logStatsigExposures:{name:"LogStatsigExposures",I:g,O:_,kind:n.MethodKind.Unary},submitLogs:{name:"SubmitLogs",I:v,O:x,kind:n.MethodKind.Unary},ingestConversation:{name:"IngestConversation",I:k,O:E,kind:n.MethodKind.Unary},uploadIssueTrace:{name:"UploadIssueTrace",I:C,O:T,kind:n.MethodKind.Unary},downloadIssueTraces:{name:"DownloadIssueTraces",I:U,O:A,kind:n.MethodKind.Unary}}};var F=e("./package.json"),K=e("./src/agent/auth/stored-credentials.ts"),z=e("./src/agent/errors.ts"),j=e("./src/agent/executor-common.ts");const H=new Map;function W(t,r,e){const n=(0,K.Lc)(t);if(n)try{(function(t){const r=H.get(t);if(r)return r;const e=(0,j.KU)(t),n=(0,$.createClient)(L,e),s=new G(t,process.env.CURSOR_BACKEND_URL??"https://api2.cursor.sh",j.dC),i=new N({client:n,tokenProvider:s});return H.set(t,i),i})(n).track(r,function(t){const r={surface:"sdk",sdk_version:F.rE,os_platform:process.platform,os_arch:process.arch};for(const[e,n]of Object.entries(t))void 0!==n&&("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n&&"bigint"!=typeof n||(r[e]=n));return r}(e))}catch{}}async function Q(t=2e3){const r=Array.from(H.values());await Promise.allSettled(r.map((r=>r.flush(t))))}function V(t,r){W(t,"sdk.run.created",{...r})}function X(t,r){W(t,"sdk.run.completed",{...r})}function Y(t,r){W(t,"sdk.mcp.admin_tool_limit",{...r})}function Z({apiKey:t,operation:r,runtime:e,error:n}){n instanceof z.v3||401===n.status||W(t,"sdk.operation.failed",{operation:r,runtime:e,error_type:n.name,error_code:n.code,error_status:n.status,error_is_retryable:n.isRetryable,request_id:n.requestId})}function tt(t,r){W(t,"sdk.run.send_latency",{...r})}function rt(t,r){W(t,"sdk.executor.startup",{...r})}function et(t,r){W(t,"sdk.request.pr_opened",{...r})}},"./src/agent/auth/credential-store.ts"(t,r,e){e.d(r,{Nw:()=>u,Tg:()=>c,fZ:()=>l,rJ:()=>a});var n=e("node:fs/promises"),s=e("node:os"),i=e("node:path"),o=e("../utils/dist/private-file.js");function a(){return(0,i.join)((0,s.homedir)(),".cursor","sdk","auth.json")}function u(t){return function(t){return"object"==typeof t&&null!==t&&("version"in t&&1===t.version&&"backendUrl"in t&&"string"==typeof t.backendUrl&&"apiKey"in t&&"string"==typeof t.apiKey&&"createdAtMs"in t&&"number"==typeof t.createdAtMs&&(!("apiKeyExpiresAtMs"in t)||void 0===t.apiKeyExpiresAtMs||"number"==typeof t.apiKeyExpiresAtMs)&&(!("email"in t)||void 0===t.email||"string"==typeof t.email))}(t)?t:void 0}class c{constructor(t){this.filePath=t??a()}get path(){return this.filePath}async load(){let t;try{await(0,o.rV)(this.filePath),t=await(0,n.readFile)(this.filePath,"utf8")}catch{return}try{return u(JSON.parse(t))}catch{return}}async save(t){await(0,o.Pl)(this.filePath,`${JSON.stringify(t,null,2)}\n`)}async clear(){await(0,n.rm)(this.filePath,{force:!0})}}class l{async load(){return this.credentials}async save(t){this.credentials=t}async clear(){this.credentials=void 0}}},"./src/agent/auth/login-flow.ts"(t,r,e){e.d(r,{Fw:()=>o,bi:()=>u,er:()=>f,pi:()=>a});var n=e("node:crypto");function s(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function i(t){return t.replace(/\/+$/,"")}function o(t){return i(t??process.env.CURSOR_WEBSITE_URL??"https://cursor.com")}function a(t){return i(t??process.env.CURSOR_BACKEND_URL??"https://api2.cursor.sh")}function u(t){const r=s((0,n.randomBytes)(32)),e=s((0,n.createHash)("sha256").update(r).digest()),i=(0,n.randomUUID)();return{uuid:i,verifier:r,loginUrl:`${t}/loginDeepControl?challenge=${e}&uuid=${i}&mode=login&redirectTarget=sdk`}}function c(t){if(!t.startsWith("{"))return!1;try{const r=JSON.parse(t);if("object"!=typeof r||null===r||!("message"in r))return!1;const e=r.message;return"string"==typeof e&&/^Route \w+:/.test(e)&&e.includes("not found")}catch{return!1}}function l(t){return!0===t?.aborted}function m(t,r){return new Promise((e=>{if(!0===r?.aborted)return void e();const n=()=>{clearTimeout(s),e()},s=setTimeout((()=>{r?.removeEventListener("abort",n),e()}),t);r?.addEventListener("abort",n,{once:!0})}))}async function f(t){const{apiUrl:r,uuid:e,verifier:n,signal:s,onWarning:i,maxAttempts:o=150,baseDelayMs:a=1e3,maxDelayMs:u=1e4}=t;let f=0,d=!1,p=!1;for(let t=0;t=3)return null;await m(o,s);continue}f=0;const a=await t.json();return"object"==typeof(h=a)&&null!==h&&"accessToken"in h&&"string"==typeof h.accessToken&&"refreshToken"in h&&"string"==typeof h.refreshToken?a:null}catch{if(l(s))return null;if(f++,f>=3)return null;await m(o,s)}}var h;return null}},"./src/agent/auth/stored-credentials.ts"(t,r,e){e.d(r,{Lc:()=>u,s1:()=>a});var n=e("node:fs"),s=e("./src/agent/auth/credential-store.ts"),i=e("./src/agent/auth/login-flow.ts");let o;function a(){o=void 0}function u(t){return void 0!==t?t:process.env.CURSOR_API_KEY??function(){const t=function(){const t=Date.now();if(void 0!==o&&t-o.readAtMs<5e3)return o.value;let r;try{const t=(0,n.readFileSync)((0,s.rJ)(),"utf8");r=(0,s.Nw)(JSON.parse(t))}catch{r=void 0}return o={value:r,readAtMs:t},r}();if(void 0!==t&&!(void 0!==t.apiKeyExpiresAtMs&&t.apiKeyExpiresAtMs<=Date.now())&&t.backendUrl===(0,i.pi)())return t.apiKey}()}},"./src/agent/cloud-api-client.ts"(t,r,e){e.d(r,{N_:()=>l,O0:()=>c,nu:()=>u});var n=e("./src/agent/errors.ts"),s=e("./src/agent/executor-common.ts"),i=e("./src/agent/team-id.ts"),o=e("./src/agent/tool-call-utils.ts"),a=e("./src/agent/utils/logger.ts");function u(t){return{usage:t.totalUsage,...void 0!==t.cost?{cost:t.cost}:{},runs:t.runs.map((t=>({runId:t.id,usage:t.usage,...void 0!==t.cost?{cost:t.cost}:{}})))}}function c(t){const r=(0,o.u)(t)?t:{},e="string"==typeof r.result?r.result:void 0,n="string"==typeof r.text?r.text:void 0,s="number"==typeof r.durationMs?r.durationMs:void 0,i=function(t){if((0,o.u)(t)&&"string"==typeof t.message)return{message:t.message,..."string"==typeof t.code?{code:t.code}:{}}}(r.error),a=function(t){if(!(0,o.u)(t)||!Array.isArray(t.branches))return;const r=[];for(const e of t.branches){if(!(0,o.u)(e)||"string"!=typeof e.repoUrl)return;r.push({repoUrl:e.repoUrl,..."string"==typeof e.branch?{branch:e.branch}:{},..."string"==typeof e.prUrl?{prUrl:e.prUrl}:{}})}return{branches:r}}(r.git);return{status:"string"==typeof r.status?r.status:"FINISHED",...void 0!==e?{result:e}:void 0!==n?{result:n}:{},...void 0!==i?{error:i}:{},...void 0!==s?{durationMs:s}:{},...void 0!==a?{git:a}:{}}}class l{constructor(t,r,e){this.baseUrl=r??process.env.CURSOR_BACKEND_URL??"https://api.cursor.com",this.apiKey=t,this.teamId=(0,i.E)(e),this.isLocalhost=/:\/\/(localhost|127\.0\.0\.1)/.test(this.baseUrl),this.useLocalNonVm="true"===process.env.CURSOR_CLOUD_AGENT_USE_LOCAL_NON_VM}async headers(t){await(0,s.ly)(this.apiKey);const r={Authorization:`Bearer ${this.apiKey}`,"x-ghost-mode":(0,s.U)(this.apiKey),"x-cursor-client-version":(0,s.tF)(),"x-cursor-client-type":"sdk"};return void 0!==this.teamId&&(r[i.P]=String(this.teamId)),t?.hasBody&&(r["Content-Type"]="application/json"),this.isLocalhost&&this.useLocalNonVm&&(r["x-background-composer-local-use-non-vm"]="true"),t?.streaming&&(r["x-cursor-streaming"]="true"),t?.idempotencyKey&&(r["Idempotency-Key"]=t.idempotencyKey),r}async request({method:t,path:r,body:e,query:s,idempotencyKey:i,retryable:o=!0}){const u=s?Object.entries(s).filter((([,t])=>void 0!==t)).map((([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`)).join("&"):"",c=`${this.baseUrl}${r}${u?`?${u}`:""}`,l=`${t} ${r}`,m=void 0!==e,d=await this.headers({hasBody:m,idempotencyKey:i});let p;a.v.log(`[cloud-api] ${t} ${c}`);try{p=await fetch(c,{method:t,headers:d,...m?{body:JSON.stringify(e)}:{}})}catch(t){throw new n.Dr("Network request failed",{endpoint:l,isRetryable:o,cause:t})}if(!p.ok){const e=await p.text().catch((()=>""));a.v.log(`[cloud-api] ${t} ${r} status=${p.status} ${e}`),this.throwApiError(p.status,e,{endpoint:l,requestId:f(p),retryable:o})}const h=await p.text();if(!h)return{};try{return JSON.parse(h)}catch(t){throw new n.c$("Failed to parse Cursor API response",{endpoint:l,isRetryable:!1,cause:t})}}throwApiError(t,r,e){const s=e.retryable??!0;let i,a,u="unknown",c=r||`Request failed with status ${t}`;try{const t=function(t){const r=(0,o.u)(t)?t:{},e=(0,o.u)(r.error)?r.error:r;return{code:"string"==typeof e.code?e.code:void 0,message:"string"==typeof e.message?e.message:void 0,helpUrl:"string"==typeof e.helpUrl?e.helpUrl:void 0,provider:"string"==typeof e.provider?e.provider:void 0}}(JSON.parse(r));u=t.code??u,c=t.message??c,i=t.helpUrl,a=t.provider}catch{}const l={status:t,code:u,endpoint:e.endpoint,requestId:e.requestId},m=`[${u}] ${c}`;if("integration_not_connected"===u){if(void 0!==i&&void 0!==a)throw new n.VW(m,{...l,helpUrl:i,provider:a,isRetryable:!1});throw new n.j1(m,{...l,isRetryable:!1})}if("feature_unavailable"===u)throw new n.zz(m,{...l,isRetryable:!1});if("agent_busy"===u)throw new n.J1(m,{...l,isRetryable:!1});switch(t){case 401:throw new n.v3(c,{...l,isRetryable:!1});case 429:throw new n.OE(c,{...l,isRetryable:!0});case 400:case 404:case 409:throw new n.j1(m,{...l,isRetryable:!1});default:if(t>=500)throw new n.Dr(m,{...l,isRetryable:s});throw new n.c$(m,{...l,isRetryable:!1})}}async createAgent(t,r){return this.request({method:"POST",path:"/v1/agents",body:t,idempotencyKey:r?.idempotencyKey})}async recoverCreatedAgent(t,r){try{const e=await this.getAgent(t),n=e.latestRunId?.trim();if(e.id!==t||void 0===n||""===n)throw r;const s=await this.getRun({agentId:t,runId:n});if(s.id!==n||s.agentId!==t)throw r;return{agent:{...e,latestRunId:n},run:s}}catch{throw r}}async getAgent(t){return this.request({method:"GET",path:`/v1/agents/${m(t)}`})}async listAgents(t){return this.request({method:"GET",path:"/v1/agents",query:t})}async archiveAgent(t){return this.request({method:"POST",path:`/v1/agents/${m(t)}/archive`})}async unarchiveAgent(t){return this.request({method:"POST",path:`/v1/agents/${m(t)}/unarchive`})}async deleteAgent(t){return this.request({method:"DELETE",path:`/v1/agents/${m(t)}`})}async createRun(t,r,e){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs`,body:r,idempotencyKey:e?.idempotencyKey})}async steerRun(t,r){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs`,body:r,retryable:!1})}async listRuns(t,r){return this.request({method:"GET",path:`/v1/agents/${m(t)}/runs`,query:r})}async getRun({agentId:t,runId:r}){return this.request({method:"GET",path:`/v1/agents/${m(t)}/runs/${m(r)}`})}async cancelRun({agentId:t,runId:r}){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs/${m(r)}/cancel`})}async streamRun({agentId:t,runId:r,lastEventId:e,signal:s}){const i=`/v1/agents/${m(t)}/runs/${m(r)}/stream`,o=`${this.baseUrl}${i}`,u=`GET ${i}`,c=await this.headers({streaming:!0});let l;c.Accept="text/event-stream",e&&(c["Last-Event-ID"]=e),a.v.log(`[cloud-api] GET ${o}`);try{l=await fetch(o,{method:"GET",headers:c,signal:s})}catch(t){throw new n.Dr("Network request failed",{endpoint:u,isRetryable:!0,cause:t})}if(!l.ok||!l.body){const t=await l.text().catch((()=>""));a.v.log(`[cloud-api] stream status=${l.status} ${t}`),this.throwApiError(l.status,t,{endpoint:u,requestId:f(l)})}return l}async listArtifacts(t){return this.request({method:"GET",path:`/v1/agents/${m(t)}/artifacts`})}async getArtifactDownloadUrl({agentId:t,path:r}){return this.request({method:"GET",path:`/v1/agents/${m(t)}/artifacts/download`,query:{path:r}})}async getAgentUsage(t,r){return this.request({method:"GET",path:`/v1/agents/${m(t)}/usage`,query:{runId:r?.runId}})}async getMe(){return this.request({method:"GET",path:"/v1/me"})}async listModels(){return this.request({method:"GET",path:"/v1/models"})}async listRepositories(){return this.request({method:"GET",path:"/v1/repositories"})}}function m(t){return encodeURIComponent(t)}function f(t){return t.headers.get("x-request-id")??void 0}},"./src/agent/errors.ts"(t,r,e){e.d(r,{D7:()=>S,Dr:()=>f,J1:()=>l,LF:()=>i,Nt:()=>y,OE:()=>u,VW:()=>m,W_:()=>I,XB:()=>h,c$:()=>d,e_:()=>R,j1:()=>c,q3:()=>b,ud:()=>o,v3:()=>a,vg:()=>P,zz:()=>p});var n=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),s=e("@connectrpc/connect");class i extends Error{constructor(t,r={}){super(t),this.name=r.errorName??"CursorSdkError",this.isRetryable=r.isRetryable??!1,g(this,"code",r.code),g(this,"status",r.status),g(this,"cause",r.cause),g(this,"endpoint",r.endpoint),g(this,"requestId",r.requestId),g(this,"operation",r.operation),Error.captureStackTrace?.(this,this.constructor)}toJSON(){return t={name:this.name,message:this.message,code:this.code,status:this.status,isRetryable:this.isRetryable,endpoint:this.endpoint,requestId:this.requestId,operation:this.operation},Object.fromEntries(Object.entries(t).filter((([,t])=>void 0!==t)));var t}}class o extends i{constructor(t,r={}){super(t,{...r,errorName:r.errorName??"CursorAgentError"})}}class a extends o{constructor(t,r={}){super(t,{...r,errorName:"AuthenticationError"})}}class u extends o{constructor(t,r={}){super(t,{...r,errorName:"RateLimitError"})}}class c extends o{constructor(t,r={}){super(t,{...r,errorName:"ConfigurationError"})}}class l extends o{constructor(t,r={}){super(t,{...r,errorName:"AgentBusyError"})}}class m extends c{constructor(t,r){super(t,r),this.name="IntegrationNotConnectedError",this.helpUrl=r.helpUrl,this.provider=r.provider}toJSON(){return{...super.toJSON(),helpUrl:this.helpUrl,provider:this.provider}}}class f extends o{constructor(t,r={}){super(t,{...r,errorName:"NetworkError"})}}class d extends o{constructor(t,r={}){super(t,{...r,errorName:"UnknownAgentError"})}}class p extends d{constructor(t,r={}){super(t,r),this.name="FeatureUnavailableError"}}class h extends o{constructor(t,r={}){super(t,{code:"agent_not_found",...r,errorName:"AgentNotFoundError"})}}function g(t,r,e){void 0!==e&&Object.defineProperty(t,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}function _(t,r){if(void 0===r)return t;for(const[e,n]of Object.entries(r))w(e)&&void 0!==n&&void 0===t[e]&&g(t,e,n);return t}const J=["operation","endpoint","status","code","requestId","isRetryable"];function w(t){return J.some((r=>r===t))}function y(t,r={}){if(t instanceof i)return _(t,r);if(t instanceof s.ConnectError)return _(R(t),r);if(function(t){return t instanceof Error&&"AbortError"===t.name}(t))return _(new f(t.message,{code:"ABORT_ERR",isRetryable:!0,cause:t}),r);const e=t instanceof Error?t.message:String(t);return"connection_stalled"===function(t){if("object"!=typeof t||null===t||!("code"in t))return;const r=t.code;return"string"==typeof r&&r.length>0&&r.length<=64?r:void 0}(t)&&t instanceof Error?_(new f(e,{code:"connection_stalled",isRetryable:!0,cause:t}),r):new d(e,{...r,cause:t,isRetryable:r.isRetryable??!1})}function S(t){const r=y(t),e=void 0!==r.code?`[${r.code}] `:void 0;return{message:void 0!==e&&r.message.startsWith(e)?r.message.slice(e.length):r.message,...void 0!==r.code?{code:r.code}:{}}}const q=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,B=/^\[([A-Za-z][A-Za-z0-9_]{0,63})\] ([\s\S]*)$/;function I(t){const r=t.code;if(void 0===r||!q.test(r))return t.message;const e=`[${r}] `;return t.message.startsWith(e)?t.message:`${e}${t.message}`}function P(t){const r=B.exec(t);if(null===r)return{message:t};const e=r[1],n=r[2]??"";return void 0===e?{message:t}:{message:n,code:e}}function b(t){return t instanceof s.ConnectError?R(t):t instanceof Error?t:new Error(String(t))}function R(t){const r=t.cause??void 0;if(r instanceof o)return r;const e=function(t){const r=t.findDetails(n.vj).at(0);if(void 0!==r)return r;const e=t.cause;return e instanceof s.ConnectError?e.findDetails(n.vj).at(0)??null:null}(t);let i,l,m=!1;if(e?.details){const{title:r,detail:n}=e.details;i=r&&n?`${r} ${n}`:r||n||t.message,m=e.details.isRetryable??!1,l=e.error}else i=t.message;if(void 0!==l){const r=function(t){return n.yM[t]??String(t)}(l);switch(l){case n.yM.NOT_LOGGED_IN:case n.yM.INVALID_AUTH_ID:case n.yM.NOT_HIGH_ENOUGH_PERMISSIONS:case n.yM.AGENT_REQUIRES_LOGIN:case n.yM.AUTH_TOKEN_NOT_FOUND:case n.yM.AUTH_TOKEN_EXPIRED:case n.yM.UNAUTHORIZED:return new a(i,{code:r,isRetryable:m,cause:t});case n.yM.FREE_USER_RATE_LIMIT_EXCEEDED:case n.yM.PRO_USER_RATE_LIMIT_EXCEEDED:case n.yM.FREE_USER_USAGE_LIMIT:case n.yM.PRO_USER_USAGE_LIMIT:case n.yM.RESOURCE_EXHAUSTED:case n.yM.OPENAI_RATE_LIMIT_EXCEEDED:case n.yM.GENERIC_RATE_LIMIT_EXCEEDED:case n.yM.GPT_4_VISION_PREVIEW_RATE_LIMIT:case n.yM.API_KEY_RATE_LIMIT:case n.yM.RATE_LIMITED:case n.yM.RATE_LIMITED_CHANGEABLE:return new u(i,{code:r,isRetryable:m,cause:t});case n.yM.BAD_API_KEY:case n.yM.BAD_USER_API_KEY:case n.yM.BAD_MODEL_NAME:case n.yM.MODEL_BLOCKED:case n.yM.NOT_FOUND:case n.yM.DEPRECATED:case n.yM.USER_NOT_FOUND:case n.yM.BAD_REQUEST:case n.yM.FILE_NOT_FOUND:return new c(i,{code:r,isRetryable:m,cause:t});case n.yM.TIMEOUT:return new f(i,{code:r,isRetryable:m,cause:t});default:return new d(i,{code:r,isRetryable:m,cause:t})}}const p=function(t){switch(t){case s.Code.Canceled:return"canceled";case s.Code.Unknown:return"unknown";case s.Code.InvalidArgument:return"invalid_argument";case s.Code.DeadlineExceeded:return"deadline_exceeded";case s.Code.NotFound:return"not_found";case s.Code.AlreadyExists:return"already_exists";case s.Code.PermissionDenied:return"permission_denied";case s.Code.ResourceExhausted:return"resource_exhausted";case s.Code.FailedPrecondition:return"failed_precondition";case s.Code.Aborted:return"aborted";case s.Code.OutOfRange:return"out_of_range";case s.Code.Unimplemented:return"unimplemented";case s.Code.Internal:return"internal";case s.Code.Unavailable:return"unavailable";case s.Code.DataLoss:return"data_loss";case s.Code.Unauthenticated:return"unauthenticated";default:return String(t)}}(t.code);switch(t.code){case s.Code.Unauthenticated:return new a(i,{code:p,isRetryable:m,cause:t});case s.Code.ResourceExhausted:return new u(i,{code:p,isRetryable:m,cause:t});case s.Code.InvalidArgument:case s.Code.NotFound:return new c(i,{code:p,isRetryable:m,cause:t});case s.Code.Unavailable:case s.Code.DeadlineExceeded:case s.Code.Internal:return new f(i,{code:p,isRetryable:m,cause:t});default:return new d(i,{code:p,isRetryable:m,cause:t})}}},"./src/agent/executor-common.ts"(t,r,e){e.d(r,{EV:()=>ar,qN:()=>Tr,KU:()=>Ur,Vh:()=>$r,v8:()=>Or,ly:()=>Ir,mU:()=>_r,dC:()=>wr,U:()=>Sr,tF:()=>Br,qd:()=>qr});var n=e("node:buffer"),s=e("node:crypto"),i=e("node:fs");let o,a=!1;var u=e("../proto/dist/generated/aiserver/v1/bidi_pb.js"),c=e("@bufbuild/protobuf"),l=e("@connectrpc/connect"),m=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js");function f(t){return t instanceof Error?t:new Error(String(t))}class d extends Error{constructor(){super("Append failed"),this.name="AppendFailedError"}}class p{constructor(t,r,e,n,s={}){this.mapper=t,this.bidiClient=r,this.innerTransport=e,this.onError=n,this.binaryEncoding=!0===s.binaryEncoding,this.appendTimeoutMs=s.appendTimeoutMs??6e4}unary(t,r,e,n,s,i,o){return this.innerTransport.unary(t,r,e,n,s,i,o)}async stream(t,r,e,n,l,f,d){if(r.kind!==c.MethodKind.BiDiStreaming)return this.innerTransport.stream(t,r,e,n,l,f,d);const p=this.mapper.map(r),{requestId:h,header:g}=function(t){const r=t instanceof Headers?t.get("x-request-id"):Array.isArray(t)?t.find((([t])=>"x-request-id"===t))?.[1]:t?.["x-request-id"];if("string"==typeof r&&void 0!==t)return{requestId:r,header:t};const e=function(){const t=function(){if(!a)try{void 0===o&&(o=(0,i.openSync)("/dev/urandom","r"));const t=Buffer.alloc(16);let r=0;for(;r<16;){const e=(0,i.readSync)(o,t,r,16-r,null);if(e<=0)return;r+=e}return t}catch{if(a=!0,void 0!==o){try{(0,i.closeSync)(o)}catch{}o=void 0}return}}();return void 0===t?(0,s.randomUUID)({disableEntropyCache:!0}):function(t){const r=t[6]??0,e=t[8]??0;t[6]=15&r|64,t[8]=63&e|128;const n=t.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(t)}();if(void 0===t){const t=new Headers;return t.set("x-request-id",e),{requestId:e,header:t}}return t instanceof Headers?t.set("x-request-id",e):Array.isArray(t)?t.push(["x-request-id",e]):"object"==typeof t&&null!==t&&(t["x-request-id"]=e),{requestId:e,header:t}}(l),_=new u.$r({requestId:h}),J=(0,m.T$)([_]);let w;const y=new Promise(((t,r)=>{w=r}));y.catch((()=>{}));const S=this.innerTransport.stream(t,p,e,n,g,J,d);this.startAppendingInputs(h,f,e,n,g,w);const q=await S,B=q.message,I={[Symbol.asyncIterator](){const t=B[Symbol.asyncIterator]();return{next:()=>Promise.race([t.next(),y]),return:r=>t.return?.(r)??Promise.resolve({done:!0,value:void 0}),throw:r=>t.throw?.(r)??Promise.resolve({done:!0,value:void 0})}}};return{...q,method:r,message:I}}startAppendingInputs(t,r,e,n,s,i){Promise.resolve().then((async()=>{let o=0;const a=[],m=r[Symbol.asyncIterator](),p=new AbortController,h=p.signal;let g,_;const J=new Promise(((t,r)=>{_=()=>r(new d)}));let w;if(J.catch((()=>{})),e?.aborted)p.abort(e.reason);else if(void 0!==e){const t=()=>{p.abort(e.reason),_()};e.addEventListener("abort",t,{once:!0}),g=()=>{e.removeEventListener("abort",t)}}try{for(;!h.aborted&&void 0===w;){const r=await Promise.race([m.next(),J]);if(r.done)break;const e=r.value;if(!(0,c.isMessage)(e))throw new Error("bidi append input is not a protobuf message");const d=o++,g=new u.$r({requestId:t}),y=e.toBinary(),S=y.buffer instanceof ArrayBuffer?y:new Uint8Array(y),q=this.binaryEncoding?S.length:2*S.length,B=this.appendTimeoutMs+Math.ceil(q/131072*1e3),I=void 0!==n?Math.min(n,B):B,P=this.bidiClient.bidiAppend(this.binaryEncoding?{requestId:g,appendSeqno:BigInt(d),dataBinary:S}:{requestId:g,appendSeqno:BigInt(d),data:Buffer.from(S.buffer,S.byteOffset,S.byteLength).toString("hex")},{signal:h,timeoutMs:I,headers:s}).then((()=>{})).catch((t=>{var r;if(r=h,!0!==r?.aborted&&void 0===w){const r=t instanceof l.ConnectError&&t.code===l.Code.DeadlineExceeded?new l.ConnectError(`bidi_append_deadline_exceeded: append seqno=${d} (${S.length} bytes) exceeded ${I}ms deadline`,l.Code.DeadlineExceeded,void 0,void 0,t):f(t);w=r,p.abort(r),this.onError(r),i(r),_()}})).finally((()=>{const t=a.indexOf(P);t>-1&&a.splice(t,1)}));if(a.push(P),await Promise.resolve(),h.aborted||void 0!==w)break;a.length>=16&&await Promise.race(a)}await Promise.allSettled(a)}catch(t){if(await Promise.allSettled(a),t instanceof d)return;const r=f(t);p.abort(r),this.onError(r),i(r)}finally{g?.(),await(m.return?.())}}))}}var h=e("../proto/dist/generated/agent/v1/agent_service_connect.js");const g={typeName:"aiserver.v1.BidiService",methods:{bidiAppend:{name:"BidiAppend",I:u.Qd,O:u.yq,kind:c.MethodKind.Unary}}};var _=e("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"),J=e("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),w=e("../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"),y=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),S=e("../proto/dist/runtime/compact.js");S.HL,c.proto3,c.proto3,c.proto3,e("../proto/dist/generated/aiserver/v1/chat_pb.js"),e("../proto/dist/generated/aiserver/v1/tools_pb.js"),e("../proto/dist/generated/agent/v1/exec_pb.js"),S.HL;S.HL,c.proto3,c.proto3,e("../proto/dist/generated/aiserver/v1/repository_pb.js");S.HL,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,e("../proto/dist/generated/agent/v1/requested_model_pb.js");S.HL,c.proto3,c.proto3,c.proto3,S.HL,e("../proto/dist/generated/aiserver/v1/docs_pb.js"),e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),S.HL,e("../proto/dist/generated/agent/v1/agent_pb.js");S.HL,c.proto3,c.proto3;S.HL,c.proto3,c.proto3,S.HL,e("../proto/dist/generated/aiserver/v1/usage_pb.js");S.HL,c.proto3;S.HL,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,S.HL;class q extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}c.proto3;class B extends q{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(B,t,r)}static $(){return["BugConfigResponse|1 linter_strategy_v1 #0|2 bug_bot_v1 #1|3 linter_strategy_v2 #2",I,b,P]}}class I extends q{constructor(t){super(),this.enabled=!1,this.tryTriggerOnSave=!1,this.waitBetweenTriggersMs=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(I,t,r)}static $(){return["BugConfigResponse.LinterStrategyV1|1 enabled 8|2 try_trigger_on_save 8|3 wait_between_triggers_ms 1"]}}class P extends q{constructor(t){super(),this.enabled=!1,this.waitBetweenTriggersMs=0,this.debounceTriggersMs=0,this.keepLinesAroundChunk=0,this.preventTriggeringForFilesWithThisManyLines=0,this.preventTriggeringWhenLints=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(P,t,r)}static $(){return["BugConfigResponse.LinterStrategyV2|1 enabled 8|2 wait_between_triggers_ms 1|3 debounce_triggers_ms 1|4 keep_lines_around_chunk 5|5 prevent_triggering_for_files_with_this_many_lines 5|6 prevent_triggering_when_lints 8"]}}class b extends q{constructor(t){super(),this.enabled=!1,this.isSubsidized=!1,this.backgroundCallFrequencyMs=0,this.killSwitch=!1,this.showIntrusiveNotificationOnlyIfLastTimeWasMoreThanMsAgo=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(b,t,r)}static $(){return["BugConfigResponse.BugBotV1|1 enabled 8|2 is_subsidized 8|3 background_call_frequency_ms 5|4 kill_switch 8|5 show_intrusive_notification_only_if_last_time_was_more_than_ms_ago 1|6 background_diff_absolute_max_tokens 5?|7 background_diff_min_min_token_threshold 5?|8 background_diff_min_max_token_threshold 5?|9 background_diff_last_commit_less_than_this_many_ms_ago 1?|15 background_unified_context_lines 5?|16 background_diff_include_uncommitted 8?|10 default_diff_context_lines 5?|11 diff_absolute_max_tokens 5?|12 custom_instructions_max_char_length 5?|13 default_fallback_iterations 5?|14 threshold_for_expensive_run_modal_cents 5?|17 cheap_model_name 9?|18 cheap_absolute_max_tokens 5?|19 expensive_absolute_max_tokens 5?"]}}c.proto3,c.proto3;class R extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}class v extends R{constructor(t){super(),this.samplingInterval=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(v,t,r)}static $(){return["HeapProfileConfig|1 sampling_interval 5|2 include_objects_collected_by_major_gc 8?|3 include_objects_collected_by_minor_gc 8?"]}}class x extends R{constructor(t){super(),this.interval=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(x,t,r)}static $(){return["CpuProfileConfig|1 interval 5"]}}class k extends R{constructor(t){super(),this.id="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(k,t,r)}static $(){return["ProfileConfig|1 id 9|2 heap #0?|3 cpu #1?",v,x]}}class E extends R{constructor(t){super(),this.id="",this.process="",this.configId="",this.activityTimeout=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(E,t,r)}static $(){return["ProfileScheduleConfig|1 id 9|2 process 9|3 config_id 9|4 schedule #0|5 activity_timeout 5",C]}}class C extends R{constructor(t){super(),this.interval=0,this.duration=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(C,t,r)}static $(){return["ProfileScheduleConfig.ScheduleConfig|1 interval 5|2 duration 5"]}}class T extends R{constructor(t){super(),this.enabled=!1,this.configs=[],this.schedules=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(T,t,r)}static $(){return["ProfilingConfig|1 enabled 8|2 configs #0*|3 schedules #1*",k,E]}}class U extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}c.proto3;class A extends U{constructor(t){super(),this.enabled=!1,this.maxRequestsTracked=0,this.maxRequestsTrackedMb=0,this.maxRequestRetentionSeconds=0,this.sendOriginalFileContentsForInitialSnapshot=!1,this.sendFullAddedLinesInDiffChanges=!1,this.numCommitsTracked=0,this.timeIntervalsTrackedMinutes=[],this.tooBigFileSizeBytes=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(A,t,r)}static $(){return["OnlineMetricsConfig|1 enabled 8|2 max_requests_tracked 5|3 max_requests_tracked_mb 5|4 max_request_retention_seconds 1|5 send_original_file_contents_for_initial_snapshot 8|6 send_full_added_lines_in_diff_changes 8|7 num_commits_tracked 5|8 time_intervals_tracked_minutes 5*|9 too_big_file_size_bytes 5"]}}const $="aiserver.v1.";class M extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return $}}var O=(0,S.QT)(c.proto3,$,"ButtonType",[[0,"UNSPECIFIED"],[1,"LEADING"],[2,"PRIMARY"],[3,"SECONDARY"]],1),D=(0,S.QT)(c.proto3,$,"DisplayMode",[[0,"UNSPECIFIED"],[1,"TOAST"],[2,"MODAL"]],1),N=(0,S.QT)(c.proto3,$,"ClientUpdateLevel",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"RECOMMENDED"],[3,"REQUIRED"]],1),G=(0,S.QT)(c.proto3,$,"RemoteConnectionType",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"WSL"],[3,"SSH"],[4,"DEVCONTAINER"],[5,"DEVCONTAINER_SSH"],[6,"DEVCONTAINER_WSL"]],1),L=(0,S.QT)(c.proto3,$,"ClientSurface",[[0,"UNSPECIFIED"],[1,"EDITOR"],[2,"GLASS"]],1),F=(0,S.QT)(c.proto3,$,"InAppAdTrigger",[[0,"UNSPECIFIED"],[1,"MOUNT"],[2,"FIND_ISSUES"],[3,"GIT_PUSH"],[4,"COMMIT"],[5,"IOS_DOWNLOAD_MENU"]],1),K=(0,S.QT)(c.proto3,$,"ScmConnectAdProvider",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GITLAB"]],1),z=(0,S.QT)(c.proto3,$,"ScmConnectAdConnectionState",[[0,"UNSPECIFIED"],[1,"UNKNOWN"],[2,"NOT_CONNECTED"],[3,"HAS_ACCESS"]],1),j=(0,S.QT)(c.proto3,$,"Http2Config",[[0,"UNSPECIFIED"],[1,"FORCE_ALL_DISABLED"],[2,"FORCE_ALL_ENABLED"],[3,"FORCE_BIDI_DISABLED"],[4,"FORCE_BIDI_ENABLED"]],1),H=(0,S.QT)(c.proto3,$,"RetrievalKeepAliveConfig",[[0,"UNSPECIFIED"],[1,"FORCE_DISABLED"],[2,"FORCE_ENABLED"]],1),W=(0,S.QT)(c.proto3,$,"BugbotPlanType",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1),Q=(0,S.QT)(c.proto3,$,"NewRepoFlowProbeInterpreter",[[0,"UNSPECIFIED"],[1,"VERCEL_PROJECT_LINK_MATCH"],[2,"JSON_PATH_EQUALS"],[3,"BOOLEAN_FIELD"]],1),V=(0,S.QT)(c.proto3,$,"NewRepoFlowFact",[[0,"UNSPECIFIED"],[1,"STARTED_AS_NEW_PROJECT"],[2,"REPO_IS_STANDARD_ORIGIN"],[3,"IS_SUBAGENT_CONVERSATION"],[4,"PLUGIN_INSTALLED"],[5,"PROBE_RESULT"],[6,"STEP_LATCHED"],[7,"SERVER_FACT"],[8,"PROBE_LINKED_WITH_LATCH_FALLBACK"],[9,"MCP_NEEDS_AUTH"]],1),X=(0,S.QT)(c.proto3,$,"NewRepoFlowStepPresentation",[[0,"UNSPECIFIED"],[1,"PILL"],[2,"PLUGIN_NUDGE"],[3,"BLOCKING_TRAY"]],1),Y=(0,S.QT)(c.proto3,$,"NewRepoFlowPluginAuthTarget",[[0,"UNSPECIFIED"],[1,"CLOUD"],[2,"LOCAL"]],1),Z=(0,S.QT)(c.proto3,$,"InferenceProviderWarningTrigger",[[0,"UNSPECIFIED"],[1,"ON_SELECT"],[2,"ON_ERROR"]],1);class tt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(tt,t,r)}static $(){return["ModalDisplayConfig|1 background_gradient 9?|2 description 9?|3 background_gradient_light 9?|4 background_gradient_dark 9?"]}}class rt extends M{constructor(t){super(),this.id="",this.buttons=[],this.displayMode=D.UNSPECIFIED,this.targetSurfaces=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(rt,t,r)}static $(){return["InAppAd|1 id 9|2 header #0|3 content #1|4 buttons #2*|5 force_dark_close_button 8?|6 display_mode #3|7 analytics_variant 9?|8 modal_display_config #4?|9 target_surfaces #5*|10 ignore_seen 8?",et,nt,it,D,tt,L]}}class et extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(et,t,r)}static $(){return["AdHeader|1 banner_url 9?|2 banner_url_light 9?|3 banner_url_dark 9?"]}}class nt extends M{constructor(t){super(),this.title="",this.sections=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(nt,t,r)}static $(){return["AdContent|1 tag 9?|2 title 9|3 sections #0*|4 center_title 8?",st]}}class st extends M{constructor(t){super(),this.iconSvg="",this.title="",this.description="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(st,t,r)}static $(){return["AdSection|1 icon_svg 9|2 title 9|3 description 9|4 is_beta 8?"]}}class it extends M{constructor(t){super(),this.text="",this.buttonType=O.UNSPECIFIED,this.action={case:void 0},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(it,t,r)}static $(){return["AdButton|1 text 9|2 button_type #0|3 external_url 9 action|4 command_id 9 action|5 client_action #1 action",O,y.O2]}}class ot extends M{constructor(t){super(),this.updateLevel=N.UNSPECIFIED,this.currentClientVersion="",this.minSupportedClientVersion="",this.minAllowedClientVersion="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ot,t,r)}static $(){return["ClientVersionStatus|1 update_level #0|2 current_client_version 9|3 min_supported_client_version 9|4 min_allowed_client_version 9|5 message 9?",N]}}class at extends M{constructor(t){super(),this.maxConcurrentUploads=0,this.absoluteMaxNumberFiles=0,this.maxFileRetries=0,this.syncConcurrency=0,this.autoIndexingMaxNumFiles=0,this.indexingPeriodSeconds=0,this.repo42AuthToken="",this.copyStatusCheckPeriodSeconds=0,this.copyTimeoutSeconds=0,this.maxBatchBytes=0,this.maxBatchNumRequests=0,this.maxSyncMerkleBatchSize=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(at,t,r)}static $(){return["IndexingConfig|1 max_concurrent_uploads 5|2 absolute_max_number_files 5|3 max_file_retries 5|4 sync_concurrency 5|5 auto_indexing_max_num_files 5|6 indexing_period_seconds 5|7 repo42_auth_token 9|8 incremental 8?|9 default_user_path_encryption_key 9?|10 default_team_path_encryption_key 9?|11 multi_root_indexing_enabled 8?|12 copy_status_check_period_seconds 1|13 copy_timeout_seconds 5|14 max_batch_bytes 5|15 max_batch_num_requests 5|16 max_sync_merkle_batch_size 5"]}}class ut extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ut,t,r)}static $(){return["GitIndexingConfig|1 enabled 8?|2 max_pr_count 5?|3 max_pr_size 5?|4 pr_embedding_context 5?|5 js_concurrency 5?|6 js_chunk_size 5?|7 cpu_concurrency 5?|8 indexing_period_seconds 5?|9 max_attempts_per_pr 5?|10 allow_index_copy_from_server 8?"]}}class ct extends M{constructor(t){super(),this.globalSampleRate=0,this.tracesSampleRate=0,this.loggerSampleRate=0,this.minidumpSampleRate=0,this.errorRateLimit=0,this.performanceUnitRateLimit=0,this.profilesSampleRate=0,this.jsonStringifySampleRate=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ct,t,r)}static $(){return["ClientTracingConfig|1 global_sample_rate 1|2 traces_sample_rate 1|3 logger_sample_rate 1|4 minidump_sample_rate 1|5 error_rate_limit 1|6 performance_unit_rate_limit 1|7 profiles_sample_rate 1|8 json_stringify_sample_rate 1"]}}class lt extends M{constructor(t){super(),this.disableUnification=!1,this.fullContextTokenLimit=0,this.disableYoloMode=!1,this.maxRuleLength=0,this.maxMcpTools=0,this.warnMcpTools=0,this.summarizationMessage="",this.numFilesForMemoryGeneration=0,this.memoryDefaultEnabled=!1,this.numSummarizationsBeforeWarningShown=0,this.cursorRulesReadFileFixEnabled=!1,this.dontSendCtrlCBeforeCommand=!1,this.clientStatsigPollIntervalMs=0,this.disableStatsig=!1,this.listDirV2PredefinedIgnoreGlobs=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(lt,t,r)}static $(){return["ChatConfig|1 disable_unification 8|2 full_context_token_limit 5|3 disable_yolo_mode 8|4 max_rule_length 5|5 max_mcp_tools 5|6 warn_mcp_tools 5|7 summarization_message 9|8 num_files_for_memory_generation 5|9 memory_default_enabled 8|10 num_summarizations_before_warning_shown 5|11 cursor_rules_read_file_fix_enabled 8|12 dont_send_ctrl_c_before_command 8|13 client_statsig_poll_interval_ms 5|14 disable_statsig 8|15 list_dir_v2_predefined_ignore_globs 9*"]}}class mt extends M{constructor(t){super(),this.connectionType=G.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(mt,t,r)}static $(){return["RemoteAuthority|1 connection_type #0",G]}}class ft extends M{constructor(t){super(),this.provider=K.UNSPECIFIED,this.remoteUrl="",this.connectionState=z.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ft,t,r)}static $(){return["ScmConnectAdContext|1 provider #0|2 remote_url 9|3 connection_state #1",K,z]}}class dt extends M{constructor(t){super(),this.hasAlternativeCli=!1,this.hasCursorAgentCli=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(dt,t,r)}static $(){return["DevEnvironment|1 has_alternative_cli 8|2 has_cursor_agent_cli 8"]}}class pt extends M{constructor(t){super(),this.telemEnabled=!1,this.bugBotDismissedNotificationLast10TimesUnixMs=[],this.bugBotViewedNotificationLast10TimesUnixMs=[],this.inAppAdTrigger=F.UNSPECIFIED,this.clientSurface=L.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(pt,t,r)}static $(){return["GetServerConfigRequest|1 telem_enabled 8|2 bug_bot_dismissed_notification_last_10_times_unix_ms 1*|3 bug_bot_viewed_notification_last_10_times_unix_ms 1*|4 os_stats #0|5 os_properties #1|6 remote_authority #2|7 in_app_ad_trigger #3|8 dev_environment #4|9 client_surface #5|10 scm_connect_ad_context #6",y.e$,y.Se,mt,F,dt,L,ft]}}class ht extends M{constructor(t){super(),this.enabledInPrivacyMode=!1,this.enabledInNonPrivacyMode=!1,this.excludedAgentHostModuleTagKeys=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ht,t,r)}static $(){return["MetricsConfig|2 enabled_in_privacy_mode 8|3 enabled_in_non_privacy_mode 8|4 excluded_agent_host_module_tag_keys 9*"]}}class gt extends M{constructor(t){super(),this.enableBackgroundAgent=!1,this.showBackgroundAgentInBetaSettings=!1,this.showBackgroundAgentHistoryAction=!1,this.useModalExperience=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(gt,t,r)}static $(){return["BackgroundComposerConfig|1 enable_background_agent 8|2 show_background_agent_in_beta_settings 8|3 window_in_window_preload_count 5?|4 window_in_window_ping_interval_ms 1?|5 show_background_agent_disclaimer 8?|6 show_background_agent_slack_ad 8?|7 show_background_agent_history_action 8|8 max_window_in_windows 5?|9 use_modal_experience 8|10 max_multi_repo_environment_repos 5?|11 allow_mixed_host_environment_repos 8?"]}}class _t extends M{constructor(t){super(),this.enabled=!1,this.enabledFallback=!1,this.enabledGitGraph=!1,this.enabledSemSearch=!1,this.enabledV2=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(_t,t,r)}static $(){return["AutoContextConfig|1 enabled 8|2 enabled_fallback 8|3 enabled_git_graph 8|4 enabled_sem_search 8|5 enabled_v2 8"]}}class Jt extends M{constructor(t){super(),this.enabled=!1,this.showStatusEntry=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Jt,t,r)}static $(){return["MemoryMonitorConfig|1 enabled 8|2 show_status_entry 8|3 base_threshold_mb 5?|4 critical_offset_mb 5?|5 process_memory_interval_sec 5?"]}}class wt extends M{constructor(t){super(),this.releaseTrack="",this.mode=yt.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(wt,t,r)}static $(){return["UpdateConfig|1 release_track 9|2 mode #0|3 applied_at 5?",yt]}}var yt=(0,S.QT)(c.proto3,$,"UpdateConfig.UpdateMode",[[0,"UNSPECIFIED"],[1,"ONE_TIME"]],1);class St extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(St,t,r)}static $(){return["PerformanceEventsConfig|1 enabled 8|2 buffer_size 5?|3 flush_interval_ms 5?"]}}class qt extends M{constructor(t){super(),this.profilingEnabled=!1,this.metricsEnabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(qt,t,r)}static $(){return["InteractionConfig|1 profiling_enabled 8|2 metrics_enabled 8|3 profiling_interval_sec 5?|4 metrics_interval_sec 5?|5 profiling_max_buffer_size 5?|6 profiling_interaction_duration_threshold_ms 5?|7 profiling_sample_interval_ms 5?|8 metrics_min_interactions_for_loaf 5?|9 metrics_min_foreground_time_ms 5?|10 metrics_combined_inp_drop_highest_count 5?|11 metrics_click_inp_drop_highest_count 5?|12 metrics_keypress_inp_drop_highest_count 5?|13 metrics_startup_threshold_sec 5?|14 analytics_summary_every_n_windows 5?|15 ext_host_lag_summary_interval_sec 5?"]}}class Bt extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Bt,t,r)}static $(){return["AgentTelemetryConfig|1 enabled 8"]}}class It extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(It,t,r)}static $(){return["TraceConfig|1 enabled 8|2 buffer_size 5?|3 flush_interval_ms 5?|4 sample_rate 1?|5 internal_sample_rate 1?|6 internal_ext_host_sample_rate 1?"]}}class Pt extends M{constructor(t){super(),this.id="",this.modelSetting="",this.targetModel="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Pt,t,r)}static $(){return["ModelMigration|1 id 9|2 model_setting 9|3 target_model 9|4 previous_model 9?|5 migrate_mode_models 8?|6 remove_previous_model 8?|7 max_mode 8?|8 migrate_old_composers_and_current_composer 8?"]}}class bt extends M{constructor(t){super(),this.maxTotalBytes=0,this.maxNumFiles=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(bt,t,r)}static $(){return["FolderSizeLimit|1 max_total_bytes 5|2 max_num_files 5"]}}class Rt extends M{constructor(t){super(),this.compositeShellCommands=[],this.safeShellCommands=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Rt,t,r)}static $(){return["RunTerminalServerConfig|1 composite_shell_commands 9*|2 safe_shell_commands 9*"]}}class vt extends M{constructor(t){super(),this.allowedActionIds=[],this.deniedActionIds=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(vt,t,r)}static $(){return["AgentLayoutPolicy|1 allowed_action_ids 9*|2 denied_action_ids 9*"]}}class xt extends M{constructor(t){super(),this.message="",this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(xt,t,r)}static $(){return["TerminalTipConfig|1 message 9|2 enabled 8"]}}class kt extends M{constructor(t){super(),this.marketplacePluginNames=[],this.agenticOnboardingEnabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(kt,t,r)}static $(){return["OnboardingConfig|1 marketplace_plugin_names 9*|2 agentic_onboarding_enabled 8"]}}class Et extends M{constructor(t){super(),this.bugbotPlanEnabled=!1,this.bugbotPlanType=W.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Et,t,r)}static $(){return["BugbotConfig|1 bugbot_plan_enabled 8|2 bugbot_plan_type #0",W]}}class Ct extends M{constructor(t){super(),this.enabled=!1,this.resetToken="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ct,t,r)}static $(){return["CodebaseTelemetryConfig|1 enabled 8|2 reset_token 9"]}}class Tt extends M{constructor(t){super(),this.id="",this.mcpServerNameMatch="",this.toolName="",this.argsJson="",this.interpreter=Q.UNSPECIFIED,this.interpreterParam="",this.interpreterExpectedValue="",this.backendMethod="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Tt,t,r)}static $(){return["NewRepoFlowProbe|1 id 9|2 mcp_server_name_match 9|3 tool_name 9|4 args_json 9|5 interpreter #0|6 interpreter_param 9|7 interpreter_expected_value 9|8 backend_method 9",Q]}}class Ut extends M{constructor(t){super(),this.method="",this.repoName="",this.repoUrl="",this.previousRepoName="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ut,t,r)}static $(){return["ResolveNewRepoFlowBackendProbeRequest|1 method 9|2 repo_name 9|3 repo_url 9|4 previous_repo_name 9"]}}class At extends M{constructor(t){super(),this.payloadText="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(At,t,r)}static $(){return["ResolveNewRepoFlowBackendProbeResponse|1 payload_text 9"]}}class $t extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals($t,t,r)}static $(){return["GetNewRepoFlowConfigRequest"]}}class Mt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Mt,t,r)}static $(){return["GetNewRepoFlowConfigResponse|1 config #0",zt]}}class Ot extends M{constructor(t){super(),this.fact=V.UNSPECIFIED,this.param="",this.expectedValue="",this.negate=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ot,t,r)}static $(){return["NewRepoFlowCondition|1 fact #0|2 param 9|3 expected_value 9|4 negate 8",V]}}class Dt extends M{constructor(t){super(),this.pluginName="",this.authTarget=Y.UNSPECIFIED,this.redirectMetadata={},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Dt,t,r)}static $(){return["NewRepoFlowInstallPluginAction|1 plugin_name 9|2 auth_target #0|3 redirect_metadata 9,9",Y]}}class Nt extends M{constructor(t){super(),this.slashCommand="",this.promptBody="",this.compactTitle="",this.latchKey="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Nt,t,r)}static $(){return["NewRepoFlowSubmitFollowupAction|1 slash_command 9|2 prompt_body 9|3 compact_title 9|4 latch_key 9"]}}class Gt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Gt,t,r)}static $(){return["NewRepoFlowDismissAction"]}}class Lt extends M{constructor(t){super(),this.serverNameMatch="",this.postAuthReturnPathTemplate="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Lt,t,r)}static $(){return["NewRepoFlowMcpAuthenticateAction|1 server_name_match 9|2 post_auth_return_path_template 9"]}}class Ft extends M{constructor(t){super(),this.label="",this.buttonType=O.UNSPECIFIED,this.action={case:void 0},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ft,t,r)}static $(){return["NewRepoFlowStepButton|1 label 9|2 button_type #0|3 external_url 9 action|4 install_plugin #1 action|5 submit_followup #2 action|6 client_action #3 action|7 dismiss #4 action|8 mcp_authenticate #5 action",O,Dt,Nt,y.O2,Gt,Lt]}}class Kt extends M{constructor(t){super(),this.id="",this.presentation=X.UNSPECIFIED,this.title="",this.bodyMarkdown="",this.pillLabel="",this.buttons=[],this.visibleWhen=[],this.dismissible=!1,this.brandPluginName="",this.disabledWhen=[],this.disabledReason="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Kt,t,r)}static $(){return["NewRepoFlowStep|1 id 9|2 presentation #0|3 title 9|4 body_markdown 9|5 pill_label 9|6 buttons #1*|7 visible_when #2*|8 dismissible 8|9 brand_plugin_name 9|10 disabled_when #2*|11 disabled_reason 9",X,Ft,Ot]}}class zt extends M{constructor(t){super(),this.configVersion="",this.probes=[],this.steps=[],this.serverFacts={},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(zt,t,r)}static $(){return["NewRepoFlowConfig|1 config_version 9|2 probes #0*|3 steps #1*|4 server_facts 9,9",Tt,Kt]}}class jt extends M{constructor(t){super(),this.isDevDoNotUseForSecretThingsBecauseCanBeSpoofedByUsers=!1,this.configVersion="",this.http2Config=j.UNSPECIFIED,this.modelMigrations=[],this.useNlbForNal=!1,this.inferenceProviderWarnings=[],this.retrievalKeepAliveConfig=H.UNSPECIFIED,this.voiceInputUnavailable=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(jt,t,r)}static $(){return["GetServerConfigResponse|1 bug_config_response #0|2 is_dev_do_not_use_for_secret_things_because_can_be_spoofed_by_users 8|3 indexing_config #1|4 client_tracing_config #2|5 chat_config #3|6 config_version 9|7 http2_config #4|8 profiling_config #5|9 metrics_config #6|10 background_composer_config #7|11 auto_context_config #8|12 model_migrations #9*|13 memory_monitor_config #10|14 folder_size_limit #11|20 online_metrics_config #12|15 git_indexing_config #13|16 performance_events_config #14|17 current_in_app_ad #15?|18 trace_config #16|19 run_terminal_server_config #17?|21 interaction_config #18|22 agent_telemetry_config #19|23 client_version_status #20?|24 update_config #21?|25 agent_layout_policy #22?|26 use_nlb_for_nal 8|27 agent_url_config #23|28 cli_sandbox_default_enabled 8?|30 terminal_tip_config #24?|31 model_picker_nudge 9?|32 inference_provider_warnings #25*|33 onboarding_config #26?|34 bugbot_config #27?|35 codebase_telemetry_config #28?|36 retrieval_keep_alive_config #29|37 google_workspace_mcp_oauth_client #30?|38 new_repo_flow_config #31?|39 voice_input_unavailable 8|40 extension_gallery_service_url 9?",B,at,ct,lt,j,T,ht,gt,_t,Pt,Jt,bt,A,ut,St,rt,It,Rt,qt,Bt,ot,wt,vt,Qt,xt,Wt,kt,Et,Ct,H,Ht,zt]}}class Ht extends M{constructor(t){super(),this.clientId="",this.clientSecret="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ht,t,r)}static $(){return["GoogleWorkspaceMcpOAuthClient|1 client_id 9|2 client_secret 9"]}}class Wt extends M{constructor(t){super(),this.message="",this.affectedModels=[],this.trigger=Z.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Wt,t,r)}static $(){return["InferenceProviderWarning|1 message 9|2 affected_models 9*|3 fallback_model 9?|4 trigger #0",Z]}}class Qt extends M{constructor(t){super(),this.agentUrl="",this.agentnUrl="",this.localLoopInferenceUrl="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Qt,t,r)}static $(){return["AgentUrlConfig|1 agent_url 9|2 agentn_url 9|3 local_loop_inference_url 9"]}}const Vt={typeName:"aiserver.v1.ServerConfigService",methods:{getServerConfig:{name:"GetServerConfig",I:pt,O:jt,kind:c.MethodKind.Unary},resolveNewRepoFlowBackendProbe:{name:"ResolveNewRepoFlowBackendProbe",I:Ut,O:At,kind:c.MethodKind.Unary},getNewRepoFlowConfig:{name:"GetNewRepoFlowConfig",I:$t,O:Mt,kind:c.MethodKind.Unary}}};var Xt=e("../utils/dist/promise-extras.js"),Yt=e("../utils/dist/fresh-uuid.js"),Zt=e("./package.json"),tr=e("./src/agent/auth/stored-credentials.ts"),rr=e("./src/agent/errors.ts"),er=e("./src/agent/sdk-config.ts"),nr=e("./src/agent/team-id.ts"),sr=e("./src/agent/tool-call-utils.ts"),ir=e("./src/agent/transport.ts"),or=e("./src/agent/utils/logger.ts");const ar=process.env.CURSOR_BACKEND_URL||"https://api2.cursor.sh";let ur="true";const cr=new Map,lr=new Map,mr=new Map,fr=new Map,dr=new Map,pr=new Map,hr=t=>{try{return"http:"===new URL(t).protocol}catch{return t.startsWith("http://")}},gr=()=>{const t=Object.getOwnPropertyDescriptor(globalThis,"Bun");return void 0!==t&&(void 0!==t.get||void 0!==t.value)};async function _r(t){if(!t||dr.has(t))return;const r=pr.get(t);if(r)return void await r;const e=(async()=>{const r=await async function(t){try{const r=await wr(t,ar);if(!r)return;const e=t=>async e=>(e.header.set("authorization",`Bearer ${r}`),t(e)),n=(0,ir.cf)({baseUrl:ar,httpVersion:"1.1",interceptors:[e]}),s=(0,l.createClient)(Vt,n);return(await s.getServerConfig(new pt)).http2Config}catch(t){return void or.v.log(`Failed to fetch server HTTP/2 config: ${t instanceof Error?t.message:String(t)}`)}}(t);void 0!==r&&dr.set(t,r)})().finally((()=>{pr.delete(t)}));pr.set(t,e),await e}class Jr{map(t){if(t.name===h.N.methods.run.name)return{name:"RunSSE",I:u.$r,O:t.O,kind:c.MethodKind.ServerStreaming};throw new Error(`Unknown method: ${t.name}`)}}async function wr(t,r,e){const n=r.endsWith("/")?r.slice(0,-1):r;try{const r=await fetch(`${n}/auth/exchange_user_api_key`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:"{}",signal:e});if(!r.ok){const t=await r.text().catch((()=>"")),e=function(t){try{const r=JSON.parse(t);if(!(0,sr.u)(r))return;const e=(0,sr.u)(r.error)?r.error:r;return"string"==typeof e.message?e.message:void 0}catch{return}}(t);throw 401===r.status?new rr.v3(e??"Invalid API key. Please check your Cursor API key and try again.",{code:"unauthenticated",isRetryable:!1}):404===r.status?new rr.j1("API key exchange endpoint not found. Please verify your backend URL.",{code:"not_found",isRetryable:!1}):429===r.status?new rr.OE(e??"Rate limited during API key exchange.",{code:"resource_exhausted",isRetryable:!0}):r.status>=500?new rr.Dr(`Server error during API key exchange: ${t||r.statusText}`,{code:"internal",isRetryable:!0}):new rr.c$(`API key exchange failed with status ${r.status}: ${t||r.statusText}`,{code:"unknown",isRetryable:!1})}const s=await r.json();if("string"==typeof s.accessToken&&s.accessToken.length>0)return s.accessToken;throw new rr.j1("API key exchange succeeded but returned no access token. Please check your API key and try again.",{code:"internal",isRetryable:!1})}catch(t){if(t instanceof rr.LF)throw t;throw new rr.Dr(`Failed to connect to API key exchange endpoint: ${t instanceof Error?t.message:"Unknown error"}`,{code:"unavailable",isRetryable:!0})}}async function yr(t,r){try{const n=await wr(t,ar,r);if(!n)return;const s=t=>async r=>(r.header.set("authorization",`Bearer ${n}`),t(r)),i=(0,ir.cf)({baseUrl:ar,httpVersion:(e=ar,hr(e)||((0,er.it)()??gr())?"1.1":"2"),interceptors:[s]}),o=(0,l.createClient)(_.I,i);return(await o.getUserPrivacyMode(new J.KoG({inferredPrivacyMode:w.Y.NO_STORAGE}),{signal:r})).privacyMode}catch(t){return void or.v.log(`Failed to fetch user privacy mode: ${t instanceof Error?t.message:String(t)}`)}var e}const Sr=t=>t&&cr.has(t)?cr.get(t):ur;async function qr(t){const r=(0,tr.Lc)(t);if(!r)return!1;const e=await async function(t){const r=lr.get(t);if(r&&Date.now()-r.fetchedAt<=6e4)return r.privacyMode;const e=mr.get(t);if(e)return e;const n=(async()=>{const r=new AbortController,e=setTimeout((()=>r.abort()),3e3);e.unref?.();try{const e=await yr(t,r.signal);return lr.set(t,{privacyMode:e,fetchedAt:Date.now()}),e}finally{clearTimeout(e)}})().finally((()=>{mr.delete(t)}));return mr.set(t,n),n}(r);return e===w.Y.NO_TRAINING||e===w.Y.USAGE_DATA_TRAINING_ALLOWED||e===w.Y.USAGE_CODEBASE_TRAINING_ALLOWED}function Br(){const t=process.env.AGENT_CLI_STATIC_VERSION;if("string"==typeof t&&""!==t.trim())return`cli-${t.trim()}`;const r=process.env.CURSOR_AGENTKIT_VERSION;if("string"==typeof r&&""!==r.trim())return`agentkit-${r.trim()}`;const e=Zt.rE,n=process.env.CURSOR_SDK_PYTHON_VERSION;if("python"===process.env.CURSOR_SDK_CLIENT_LANGUAGE){const t="string"==typeof n&&""!==n.trim()?n.trim():"string"==typeof e&&""!==e.trim()?e.trim():void 0;return void 0!==t?`sdk-python-${t}`:"sdk-python-unknown"}return"string"==typeof e&&""!==e.trim()?`sdk-${e}`:"sdk-unknown"}async function Ir(t){if(!t)return;if(cr.has(t))return void(ur=cr.get(t));const r=fr.get(t);if(r)return await r,void(ur=cr.get(t)??ur);const e=(async()=>{const r=await yr(t);lr.set(t,{privacyMode:r,fetchedAt:Date.now()});const e=(t=>t===w.Y.USAGE_DATA_TRAINING_ALLOWED||t===w.Y.USAGE_CODEBASE_TRAINING_ALLOWED?"false":"true")(r);ur=e,cr.set(t,e)})().finally((()=>{fr.delete(t)}));fr.set(t,e),await e}const Pr=18e5;function br(t){return t instanceof l.ConnectError&&t.code===l.Code.Unauthenticated}function Rr(t){return t instanceof rr.LF&&t.isRetryable}async function*vr(t,r){try{yield*t}catch(t){throw br(t)&&r(),t}}const xr=new Set(["asr-runner","asr-at-rest","vuln-hunter"]);function kr(t){let r,e,s;return{getBearer:async()=>{if(void 0!==s)throw s;const i=r;if(void 0!==i&&Date.now(){const e=await wr(t,ar);if(!e)throw new rr.j1("API key exchange succeeded but returned no access token. Please check your API key and try again.",{code:"internal",isRetryable:!1});const s=Date.now(),i=function(t,r){try{const e=t.split(".")[1];if(void 0===e)return r+Pr;const s=JSON.parse(n.Buffer.from(e,"base64url").toString("utf8"));if(!(0,sr.u)(s)||"number"!=typeof s.exp)return r+Pr;const i=1e3*s.exp;return Number.isFinite(i)&&i>0?i:r+Pr}catch{return r+Pr}}(e,s),o={value:e,expiresAtMs:i,refreshAtMs:Math.max(i-3e5,s+(i-s)/2)};return r=o,o})().catch((t=>{const r=t instanceof Error?t:new Error(String(t));throw r instanceof rr.LF&&!r.isRetryable&&(s=r),r})).finally((()=>{e=void 0})));try{return await e}catch(t){if(void 0!==i&&r===i&&Date.now(){r===t&&(r=void 0)}}}const Er=[500,1500];function Cr({getBearer:t}){return async()=>{for(let r=0;;r++)try{return(await t()).value}catch(t){const e=Er[r];if(Rr(t)&&void 0!==e){await(0,Xt.cb)(e);continue}return void or.v.log(`Failed to get an access token for the API key: ${t instanceof Error?t.message:String(t)}`)}}}function Tr(t,r){const e=kr(t);return{transport:Ar(e,t,r),getAccessToken:Cr(e)}}function Ur(t,r){return Ar(kr(t),t,r)}function Ar({getBearer:t,invalidateBearer:r},e,n){const s=(0,nr.E)(n),i=n=>async i=>{i.header.set("x-cursor-client-version",Br()),i.header.set("x-cursor-client-type","sdk"),function(t){const r=process.env.CURSOR_HOST_APP_NAME?.trim();void 0!==r&&xr.has(r)&&t.set("x-cursor-host-app-name",r)}(i.header);const o=cr.get(e)??ur;i.header.set("x-ghost-mode",o),void 0===s||i.header.get(nr.P)||i.header.set(nr.P,String(s)),i.header.get("x-request-id")||i.header.set("x-request-id",(0,Yt.C)());const a=async t=>{i.header.set("authorization",`Bearer ${t.value}`);const e=await n(i);return e.stream?{...e,message:vr(e.message,(()=>{r(t)}))}:e};let u=await t();try{return await a(u)}catch(e){if(br(e)){if(r(u),i.stream)throw or.v.log("Auth rejected, invalidating cached token"),e;or.v.log("Auth expired, re-authenticating"),u=await t()}else{if(i.stream||!function(t,r){return t instanceof l.ConnectError&&t.code===l.Code.Unavailable&&!t.metadata.has("retry-after")&&r.service.typeName!==g.typeName&&t.findDetails(y.vj).some((t=>!0===t.details?.isRetryable))}(e,i))throw e;if(or.v.log("Request unavailable, retrying once"),await(0,Xt.st)(1e3*Math.random(),i.signal),i.signal.aborted)throw e}try{return await a(u)}catch(t){throw br(t)&&r(u),t}}},o=((t,r)=>{const e=(0,er.it)(),n=hr(t)||(e??gr());switch(void 0!==r?dr.get(r):void 0){case j.FORCE_ALL_DISABLED:case j.FORCE_BIDI_DISABLED:return!0;case j.FORCE_ALL_ENABLED:case j.FORCE_BIDI_ENABLED:return!1;case j.UNSPECIFIED:default:return n}})(ar,e),a=(0,ir.cf)({baseUrl:ar,httpVersion:o?"1.1":"2",interceptors:o?[t=>async r=>(r.header.set("x-cursor-streaming","true"),t(r)),i]:[i]});if(!o)return a;const u=(0,l.createClient)(g,a);return new p(new Jr,u,a,(t=>{or.v.log(`Bidi SSE transport error: ${t instanceof Error?t.message:String(t)}`)}))}function $r(t,r){let e=t;return{async run(...t){try{await e.run(...t)}catch(n){if(!(n instanceof l.ConnectError&&n.code===l.Code.Unauthenticated)){if(n instanceof l.ConnectError)throw(0,rr.e_)(n);throw n}e=r();try{await e.run(...t)}catch(t){if(t instanceof l.ConnectError)throw(0,rr.e_)(t);throw t}}}}}const Mr=new Map([[[255,216,255],"image/jpeg"],[[137,80,78,71],"image/png"]]);function Or(t){for(const[r,e]of Mr)if(t.length>=r.length&&r.every(((r,e)=>t[e]===r)))return e}},"./src/agent/filesystem/compose.ts"(t,r,e){e.d(r,{Mb:()=>J,VL:()=>g,w1:()=>S});var n=e("./src/agent/filesystem/errors.ts"),s=e("./src/agent/filesystem/merge.ts"),i=e("./src/agent/filesystem/trees.ts"),o=e("./src/agent/filesystem/walk.ts");function a(t,r){let e;for(const n of r)(0,o.hJ)({path:t,prefix:n.prefix})&&(void 0===e||n.prefix.length>e.prefix.length)&&(e=n);return e}function u(t,r){return r.filter((r=>r.prefix!==t&&(0,o.hJ)({path:r.prefix,prefix:t})))}function c(t){return"/"===t?0:t.split("/").length-1}function l(t,r){return"/"===r?t:t===r?"/":t.startsWith(`${r}/`)?t.slice(r.length):t}function m(t,r){return"/"===r?t:"/"===t||""===t?r:t.startsWith("/")?`${r}${t}`:`${r}/${t}`}async function*f(t,r){try{for await(const e of t)yield{...e,path:m(e.path,r)}}catch(t){throw(0,n.Zu)(t,r)}}async function*d(t,{owner:r,mounts:e}){const n=e.filter((t=>t.prefix.length>r.prefix.length));for await(const r of t)n.some((t=>r.path!==t.prefix&&(0,o.hJ)({path:r.path,prefix:t.prefix})))||(yield r)}async function*p(t,r){const e={maxDepth:1,excludes:r?.excludes};for await(const n of f(t.fs.list(void 0,e),t.prefix))if(!(0,o.a)(n.path,r?.excludes))return void(yield n)}function h(t,r){return{excludes:t?.excludes,maxDepth:r}}function g(t){const r=Object.entries(t).map((([t,r])=>({prefix:(0,o.eI)(t),fs:r})));r.sort(((t,r)=>r.prefix.length-t.prefix.length));const e=(t,e)=>d(f(e,t.prefix),{owner:t,mounts:r}),i=async(t,e)=>{const s=a(t,r);if(void 0===s)throw new n.VV(t);try{return await e(s.fs,l(t,s.prefix))}catch(t){throw(0,n.Zu)(t,s.prefix)}};return{async*list(t,n){const s=(0,o.c9)(t),i=async function*(t,r){for await(const e of t)(0,o.a)(e.path,r)||(yield e)}((0,o.mU)(((t,n)=>{const s=(0,o.eV)(n);void 0===s&&(n?.excludes?.length??0)>0&&(n={...n,limit:void 0});const i=[];for(const o of u(t,r)){if(void 0===s){i.push(e(o,o.fs.list(void 0,n)));continue}const r=s-(c(o.prefix)-c(t));i.push(r<1?p(o,n):e(o,o.fs.list(void 0,h(n,r))))}const m=a(t,r);if(void 0!==m){const r=l(t,m.prefix),o=void 0===s?n:h(n,s);i.push(e(m,m.fs.list("/"===r?void 0:r,o)))}return i})(s,n),{unique:!0}),n?.excludes),m=(0,o.eV)(n);void 0!==m?yield*(0,o.SC)(i,{scope:s,maxDepth:m,limit:n?.limit}):yield*(0,o.I6)(i,n?.limit)},async stat(t){const e=(0,o.eI)(t);if("/"===e)return{kind:"directory"};if(r.some((t=>t.prefix===e)))return{kind:"directory"};const n=a(e,r),s=void 0===n?{kind:"missing"}:await n.fs.stat(l(e,n.prefix));return"missing"===s.kind&&u(e,r).length>0?{kind:"directory"}:s},read:async t=>i((0,o.eI)(t),((t,r)=>t.read(r))),write:async(t,r)=>i((0,o.eI)(t),((t,e)=>t.write(e,r))),delete:async t=>i((0,o.eI)(t),((t,r)=>t.delete(r))),async*grep(t){yield*(0,o.I6)(async function*(){const n=void 0===t.path||""===t.path?"/":(0,o.eI)(t.path);if("/"===n)return void(yield*(0,s.C)(r.map((r=>e(r,r.fs.grep({...t,path:void 0})))),{compare:o.h}));const i=a(n,r);if(void 0===i)return;const u=l(n,i.prefix);yield*e(i,i.fs.grep({...t,path:"/"===u?void 0:u}))}(),t.maxResults)},async*glob(t,n,s){yield*(0,o.I6)(async function*(){const i=void 0===n||""===n?"/":(0,o.eI)(n);if("/"===i)return void(yield*(0,o.mU)(r.map((r=>e(r,r.fs.glob(t,void 0,s)))),{unique:!0}));const c=u(i,r).map((e=>d(async function*(t,r,e){for await(const n of f(t.fs.list(void 0),t.prefix))(0,o.ZC)({filePath:n.path,dir:r,globPattern:e})&&(yield n)}(e,i,t),{owner:e,mounts:r}))),m=a(i,r);if(void 0!==m){const r=l(i,m.prefix);c.push(e(m,m.fs.glob(t,"/"===r?void 0:r,s)))}yield*(0,o.mU)(c,{unique:!0})}(),s?.limit)}}}async function _(t){const r=[];try{for await(const e of t.list())r.push(e.path)}catch{}return r}function J(t){if(0===t.length)throw new Error("overlayFs needs at least one layer.");const r=async r=>{const e=[];let n,s=!1;for(const i of t){const t=[];try{for await(const e of r(i))t.push(e)}catch(t){n??=t;continue}s=!0,e.push(t)}if(!s&&void 0!==n)throw n;return e};return{async*list(t,e){const n=(0,o.eV)(e),s=void 0===n?e:h(e,n),i=await r((r=>r.list(t,s))),a=(0,o.mU)(i,{unique:!0});void 0!==n?yield*(0,o.SC)(a,{scope:(0,o.c9)(t),maxDepth:n,limit:e?.limit}):yield*(0,o.I6)(a,e?.limit)},async stat(r){let e,n=!1;for(const s of t)try{const t=await s.stat(r);if("missing"!==t.kind)return t;n=!0}catch(t){e??=t}if(!n&&void 0!==e)throw e;return{kind:"missing"}},async*glob(t,e,n){const s=await r((r=>r.glob(t,e,n)));yield*(0,o.I6)((0,o.mU)(s,{unique:!0}),n?.limit)},async read(r){let e;for(const s of t)try{return await s.read(r)}catch(t){if((0,n.Wp)(t))continue;e??=t}if(void 0!==e)throw e;throw new n.kG(r)},async*grep(r){const{maxResults:e,...i}=r,a=await(async(r,e)=>{const n=[],s=new Set;let i,o=!1;for(const a of t){const t=[];try{for await(const e of r(a))s.has(e.path)||t.push(e);o=!0}catch(t){if(!0===e?.(t))throw t;i??=t;continue}n.push(t);for(const t of await _(a))s.add(t)}if(!o&&void 0!==i)throw i;return n})((t=>t.grep(i)),(t=>(0,n.q_)(t)));yield*(0,o.I6)((0,s.C)(a,{compare:o.h}),e)},async write(t){throw new n.QK(t)},async delete(t){throw new n.QK(t)}}}function w(t,r){const e=t=>!r.has((0,o.eI)(t));async function*s(t){for await(const r of t)e(r.path)&&(yield r)}return{async*list(e,n){const i=(0,o.eV)(n);if(0===r.size)return void(yield*t.list(e,n));if(void 0===i){const r={...n,limit:void 0};return void(yield*(0,o.I6)(s(t.list(e,r)),n?.limit))}const a=s(t.list(e,{excludes:n?.excludes}));yield*(0,o.SC)(a,{scope:(0,o.c9)(e),maxDepth:i,limit:n?.limit})},async stat(n){const s=(0,o.eI)(n);if(r.has(s))return{kind:"missing"};const i=await t.stat(n);if("directory"!==i.kind||"/"===s)return i;if(![...r].some((t=>(0,o.hJ)({path:t,prefix:s}))))return i;let a=!1;for await(const r of t.list(s)){if(e(r.path))return i;a=!0}return a?{kind:"missing"}:i},async*glob(e,n,i){if(0===r.size)return void(yield*t.glob(e,n,i));const a={...i,limit:void 0};yield*(0,o.I6)(s(t.glob(e,n,a)),i?.limit)},async read(e){const s=(0,o.eI)(e);if(r.has(s))throw new n.kG(s);return t.read(e)},async*grep(r){for await(const n of t.grep(r))e(n.path)&&(yield n)},async write(t){throw new n.QK((0,o.eI)(t))},async delete(t){throw new n.QK((0,o.eI)(t))}}}async function y(t,r){if("missing"===(await t.stat(r)).kind)try{await t.read(r)}catch(t){if((0,n.Wp)(t))return;throw t}}function S(t){const r=(0,i.Om)(),e=new Set,s=J([r,w(t,e)]);return{list:(t,r)=>s.list(t,r),stat:t=>s.stat(t),glob:(t,r,e)=>s.glob(t,r,e),read:t=>s.read(t),grep:t=>s.grep(t),async write(i,a){const u=(0,o.eI)(i);if(await y(t,u),"directory"===(await s.stat(u)).kind)throw new n.JA(u,`path is a directory: ${u}`);e.delete(u),await r.write(u,a)},async delete(i){const a=(0,o.eI)(i);if(await y(t,a),"file"!==(await s.stat(a)).kind)throw new n.kG(a);e.add(a);try{await r.delete(a)}catch(t){if(!(0,n.Wp)(t))throw t}}}}},"./src/agent/filesystem/errors.ts"(t,r,e){e.d(r,{ER:()=>a,F:()=>d,JA:()=>m,QK:()=>c,VV:()=>l,Wp:()=>h,Zu:()=>J,kG:()=>u,kp:()=>p,q_:()=>g,x$:()=>f});var n=e("node:path"),s=e.n(n);function i(t){const r=t.replace(/\\/g,"/");if(""===r)return"/";const e=r.startsWith("/")?r:`/${r}`,n=s().posix.normalize(e);return n.length>1&&n.endsWith("/")?n.slice(0,-1):"."===n||""===n?"/":n}const o=/^(not found|read-only mount|write failed|edit failed|no mount for path|delete is not supported): \/$/;class a extends Error{constructor(t,r){super(r),this.name=Object.hasOwn(new.target,"errorName")?new.target.errorName:new.target.name,this.path=i(t)}withPath(t){const r=i(t);return r===this.path?this:this.recreate(r,(e=this.message,(n=this.path)===(s=r)?e:"/"===n?o.test(e)?e.replace(/\/$/,s):e:e.includes(n)?e.split(n).join(s):e));var e,n,s}recreate(t,r){return new a(t,r)}}a.errorName="PathError";class u extends a{constructor(t,r){super(t,r??`not found: ${i(t)}`)}recreate(t,r){return new u(t,r)}}u.errorName="FileNotFoundError";class c extends a{constructor(t,r){super(t,r??`read-only mount: ${i(t)}`)}recreate(t,r){return new c(t,r)}}c.errorName="ReadOnlyMountError";class l extends a{constructor(t,r){super(t,r??`no mount for path: ${i(t)}`)}recreate(t,r){return new l(t,r)}}l.errorName="NoMountError";class m extends a{constructor(t,r){super(t,r??`write failed: ${i(t)}`)}recreate(t,r){return new m(t,r)}}m.errorName="WriteFailedError";class f extends a{constructor(t,r){super(t,r??`delete is not supported: ${i(t)}`)}recreate(t,r){return new f(t,r)}}f.errorName="DeleteNotSupportedError";class d extends a{recreate(t,r){return new d(t,r)}}d.errorName="EditError";class p extends a{constructor(t,r="/",e){super(r,e??`invalid grep pattern: ${t}`),this.pattern=t}recreate(t,r){return new p(this.pattern,t,r)}}function h(t){return t instanceof u||t instanceof Error&&t.message.startsWith("not found:")}function g(t){return t instanceof p||t instanceof Error&&t.message.startsWith("invalid grep pattern:")}p.errorName="InvalidGrepPatternError";const _=["not found: ","read-only mount: ","write failed: ","edit failed: ","no mount for path: ","delete is not supported: "];function J(t,r){return t instanceof a?t.withPath(w(t.path,r)):t instanceof Error?function(t,r){for(const e of _){if(!t.message.startsWith(e))continue;const n=`${e}${w(t.message.slice(e.length),r)}`;if(n===t.message)return t;const s=new Error(n);return s.name=t.name,s}return t}(t,r):new a(r,String(t))}function w(t,r){const e=i(r),n=i(t);return"/"===e?n:"/"===n?e:`${e}${n}`}},"./src/agent/filesystem/executors.ts"(t,r,e){e.d(r,{c9:()=>q,mv:()=>y});var n=e("node:buffer"),s=e("node:path"),i=e("../proto/dist/generated/agent/v1/delete_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/grep_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),u=e("../proto/dist/generated/agent/v1/read_exec_pb.js"),c=e("../proto/dist/generated/agent/v1/write_exec_pb.js"),l=e("./src/agent/filesystem/errors.ts"),m=e("./src/agent/filesystem/walk.ts");function f(t){const r=(0,m.c9)(t.dir),e=d(r),n=new Map([[r,e]]),s={charactersUsed:r.length,budgetExceeded:!1};for(const e of t.entries)if("directory"!==e.kind)p({filePath:e.path,rootPath:r,nodes:n,state:s});else{const t=g({dirPath:e.path,rootPath:r,nodes:n,state:s});void 0!==t&&(t.childrenWereProcessed=!1)}return t.truncated&&(e.childrenWereProcessed=!1),e}function d(t){return new a.vq({absPath:t,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{},numFiles:0})}function p(t){const{filePath:r,rootPath:e,nodes:n,state:i}=t,o=J(r),u=g({dirPath:o,rootPath:e,nodes:n,state:i});if(void 0===u)return;const c=s.posix.basename(r);if(!i.budgetExceeded&&i.charactersUsed+c.length<=2500)return u.childrenFiles.push(new a.ur({name:c})),void(i.charactersUsed+=c.length);if(!i.budgetExceeded){i.budgetExceeded=!0;for(const t of h({dirPath:o,rootPath:e,nodes:n}))t.childrenWereProcessed=!1}const l=s.posix.extname(r);for(const t of h({dirPath:o,rootPath:e,nodes:n}))t.fullSubtreeExtensionCounts[l]=(t.fullSubtreeExtensionCounts[l]??0)+1,t.numFiles+=1}function*h(t){let r=t.dirPath;for(;_({path:r,rootPath:t.rootPath});){const e=t.nodes.get(r);void 0!==e&&(yield e);const n=J(r);if(n===r)return;r=n}}function g(t){const{dirPath:r,rootPath:e,nodes:n,state:s}=t,i=n.get(r);if(void 0!==i)return i;if(!_({path:r,rootPath:e}))return;const o=g({dirPath:J(r),rootPath:e,nodes:n,state:s});if(void 0===o)return;const a=d(r);return a.childrenWereProcessed=!s.budgetExceeded,n.set(r,a),o.childrenDirs.push(a),a}function _(t){return"/"===t.rootPath||t.path===t.rootPath||t.path.startsWith(`${t.rootPath}/`)}function J(t){const r=s.posix.dirname(t);return"."===r||r===t?"/":r}var w=e("./src/agent/filesystem/types.ts");function y(t){const r=(t.path??"").replace(/\\/g,"/");if(""===r)return t.workspace;const e=r.startsWith("/")||/^[A-Za-z]:(?:\/|$)/.test(r);return(0,m.eI)(e?r:s.posix.join(t.workspace,r))}function S(t){return(0,m.eI)(t?.workspace??"/")}function q(t,r){return{read:B(t,r),write:R(t,r),grep:U(t,r),ls:E(t,r),delete:x(t,r)}}function B(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path});let i;try{if("directory"===(await t.stat(s)).kind)return P({case:"invalidFile",value:new u.cW({path:s,reason:"Path is a directory, not a file"})});i=await t.read(s)}catch(t){return function(t){const r=N(t.error,t.path);return(0,l.Wp)(t.error)?P({case:"fileNotFound",value:new u.Ko({path:r})}):t.error instanceof l.QK?P({case:"permissionDenied",value:new u.lW({path:r})}):P({case:"error",value:new u.F_({path:r,error:G(t.error,"read failed")})})}({path:s,error:t})}if(i instanceof Uint8Array){if(void 0!==function(t){const{bytes:r}=t;if(b(r,[255,216,255]))return"image/jpeg";if(b(r,[137,80,78,71]))return"image/png";if(b(r,[71,73,70]))return"image/gif";if(b(r,[82,73,70,70])&&r.length>=12&&"WEBP"===String.fromCharCode(r[8]??0,r[9]??0,r[10]??0,r[11]??0))return"image/webp";const e=t.path.toLowerCase();return e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".png")?"image/png":e.endsWith(".gif")?"image/gif":e.endsWith(".webp")?"image/webp":void 0}({bytes:i,path:s})||function(t,r){return b(t,[37,80,68,70])||r.toLowerCase().endsWith(".pdf")}(i,s))return P({case:"success",value:new u.mE({path:s,output:{case:"data",value:i},totalLines:0,fileSize:BigInt(i.byteLength),truncated:!1,rangeApplied:!1})});const t=function(t){let r;try{r=new TextDecoder(t.encodingHint??"utf-8",{fatal:!0})}catch{r=new TextDecoder("utf-8",{fatal:!0})}try{const e=r.decode(t.bytes);return e.includes("\0")?void 0:e}catch{return}}({bytes:i,encodingHint:e.encodingHint});return void 0===t?P({case:"invalidFile",value:new u.cW({path:s,reason:"File content is binary data, not text"})}):I({path:s,text:t,fileSize:i.byteLength,args:e})}return I({path:s,text:i,fileSize:n.Buffer.byteLength(i,"utf8"),args:e})}({fs:t,workspace:e},s)}}function I(t){const{text:r}=t,e=r.split("\n"),n=e.length,s=""===r?void 0:function(t){if(void 0===t.offset&&void 0===t.limit||0===t.totalLines)return;const r=t.offset??1,e=t.limit??(r<0?Math.abs(r):t.totalLines),n=r<0?Math.max(0,t.totalLines+r):Math.max(0,r-1);return n>=t.totalLines?void 0:{start:n,end:Math.min(t.totalLines,n+e)}}({totalLines:n,offset:t.args.offset,limit:t.args.limit});return P({case:"success",value:new u.mE({path:t.path,output:{case:"content",value:void 0===s?r:e.slice(s.start,s.end).join("\n")},totalLines:n,fileSize:BigInt(t.fileSize),truncated:!1,rangeApplied:void 0!==s})})}function P(t){return new u.sV({result:t})}function b(t,r){return t.length>=r.length&&r.every(((r,e)=>t[e]===r))}function R(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path}),i=e.fileBytes.length>0?e.fileBytes:e.fileText;try{if("directory"===(await t.stat(s)).kind)return v({case:"error",value:new c.QM({path:s,error:`EISDIR: illegal operation on a directory, open '${s}'`})});await t.write(s,i)}catch(t){return function(t){const r=N(t.error,t.path);return t.error instanceof l.QK?v({case:"permissionDenied",value:new c.U7({path:r,directory:"",operation:"create_file",error:t.error.message,isReadonly:!0})}):v({case:"error",value:new c.QM({path:r,error:G(t.error,"write failed")})})}({path:s,error:t})}let o;if(e.returnFileContentAfterWrite)try{const r=await t.read(s);o="string"==typeof r?r:void 0}catch{o=void 0}const a="string"==typeof i?i:void 0;return v({case:"success",value:new c.j6({path:s,linesCreated:void 0===a||""===a?0:a.split("\n").length,fileSize:"string"==typeof i?n.Buffer.byteLength(i):i.byteLength,fileContentAfterWrite:o})})}({fs:t,workspace:e},s)}}function v(t){return new c.v3({result:t})}function x(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path});let o,a;try{const r=await t.stat(s);if("missing"===r.kind)return k({case:"fileNotFound",value:new i.n0({path:s})});if("directory"===r.kind)return k({case:"notFile",value:new i.LX({path:s,actualType:"directory"})});const e=await t.read(s);a="string"==typeof e?n.Buffer.byteLength(e):e.byteLength,o="string"==typeof e?e:"",await t.delete(s)}catch(t){return function(t){const r=N(t.error,t.path);return(0,l.Wp)(t.error)?k({case:"fileNotFound",value:new i.n0({path:r})}):t.error instanceof l.QK?k({case:"permissionDenied",value:new i.QG({path:r,clientVisibleError:t.error.message,isReadonly:!0})}):t.error instanceof l.x$?k({case:"rejected",value:new i.iq({path:r,reason:t.error.message})}):k({case:"error",value:new i.GU({path:r,error:G(t.error,"delete failed")})})}({path:s,error:t})}return k({case:"success",value:new i.fl({path:s,deletedFile:s,fileSize:BigInt(a),prevContent:o})})}({fs:t,workspace:e},s)}}function k(t){return new i.Pi({result:t})}function E(t,r){const e=S(r);return{execute:(r,n)=>async function({fs:t,workspace:r},e){const n=y({workspace:r,path:e.path}),s=e.ignore.length>0?e.ignore:void 0,i=[];try{for await(const r of t.list(n,{excludes:s,limit:w.H+1,maxDepth:3})){const t=(0,m.eI)(r.path);(0,m.a)(t,s)||i.push({...r,path:t})}if(0===i.length){const r=(await t.stat(n)).kind;if("missing"===r)return C({path:n,error:`Path does not exist: ${n}`});if("file"===r)return C({path:n,error:`Path is not a directory: ${n}`})}}catch(t){return C({path:n,error:G(t,"list failed")})}const o=(0,m.e4)({entries:i,scope:n,maxDepth:3}),u=i.length>w.H||o.length>w.H;return new a.fv({result:{case:"success",value:new a.PC({directoryTreeRoot:f({dir:n,entries:o.slice(0,w.H),truncated:u})})}})}({fs:t,workspace:e},n)}}function C(t){return new a.fv({result:{case:"error",value:new a.uj({path:t.path,error:t.error})}})}const T={c:"*.{c,h}",cpp:"*.{cc,cpp,cxx,hh,hpp,hxx,h}",css:"*.{css,scss,sass,less}",go:"*.go",html:"*.{htm,html}",java:"*.java",js:"*.{js,jsx,mjs,cjs}",json:"*.json",kotlin:"*.{kt,kts}",md:"*.{md,markdown,mdx}",markdown:"*.{md,markdown,mdx}",py:"*.{py,pyi}",python:"*.{py,pyi}",rb:"*.rb",ruby:"*.rb",rust:"*.rs",sh:"*.{sh,bash,zsh}",sql:"*.sql",swift:"*.swift",toml:"*.toml",ts:"*.{ts,tsx,mts,cts}",typescript:"*.{ts,tsx,mts,cts}",yaml:"*.{yaml,yml}"};function U(t,r){const e=S(r);return{execute:(r,n)=>async function({fs:t,workspace:r},e){const n="files"===(i=e.outputMode)||"files_with_matches"===i?"files_with_matches":"count"===i?"count":"content",s=y({workspace:r,path:e.path});var i;try{if(!0===e.multiline)return M("multiline grep is not supported on this filesystem");const i=function(t){const r=""===t.glob?void 0:t.glob;if(void 0===t.type||""===t.type)return r;const e=T[t.type.toLowerCase()];if(void 0===e)throw new Error(`unsupported grep type: ${t.type}. Use glob instead.`);if(void 0!==r)throw new Error("grep type and glob cannot be combined on this filesystem. Use glob only.");return e}({glob:e.glob,type:e.type});if("missing"===(await t.stat(s)).kind)return M(`Path does not exist: ${s}`);const a={headLimit:D(e.headLimit),offset:D(e.offset)??0},u=""===e.pattern&&"files_with_matches"===n?await async function(t){const r=w.H,e=[];for await(const n of t.fs.glob(t.glob??"**",t.path,{limit:r+1}))"directory"!==n.kind&&e.push((0,m.eI)(n.path));const n=e.length>r,s=e.slice(0,r),i=void 0===t.page.headLimit?void 0:t.page.offset+t.page.headLimit,a=s.slice(t.page.offset,i);return new o.vD({result:{case:"files",value:new o.T7({files:a,totalFiles:s.length,clientTruncated:n||a.length0?t.page.offset:void 0})}})}({fs:t,path:s,glob:i,page:a}):await async function(t){const{matches:r,truncated:e}=await async function(t){const{headLimit:r,offset:e}=t.page,n="content"===t.outputMode,s=n&&void 0!==r?e+r+1:void 0,i=[],o=new Set,a=new Set;let u=0,c=0;for await(const l of t.fs.grep({...t.query,maxResults:s}))if(n){if(u=r)return{matches:i,truncated:!0};i.push(l),c++}else if(!o.has(l.path)){if(!a.has(l.path)){if(u=r)return{matches:i,truncated:!0};a.add(l.path),c++}i.push(l)}return{matches:i,truncated:!1}}(t),n={clientTruncated:e,ripgrepTruncated:e,headLimitApplied:t.page.headLimit,offsetApplied:t.page.offset>0?t.page.offset:void 0};if("files_with_matches"===t.outputMode){const t=[...new Set(r.map((t=>t.path)))];return new o.vD({result:{case:"files",value:new o.T7({files:t,totalFiles:t.length,...n})}})}if("count"===t.outputMode){const t=new Map;for(const e of r)t.set(e.path,(t.get(e.path)??0)+1);const e=[...t].map((([t,r])=>new o.sS({file:t,count:r})));return new o.vD({result:{case:"count",value:new o.xA({counts:e,totalFiles:e.length,totalMatches:r.length,...n})}})}const s=await async function(t){const{before:r,after:e}=t.context,n=new Map,s=new Map;for(const i of t.matches){let a=n.get(i.path);void 0===a&&(a=new Map,n.set(i.path,a));let u=s.get(i.path);void 0===u&&(r>0||e>0)&&(u=await $(t.fs,i.path),s.set(i.path,u));const c=i.lineNumber-1;if(void 0!==u)for(let t=Math.max(0,c-r);tnew o.uI({file:t,matches:[...r.entries()].sort(((t,r)=>t[0]-r[0])).map((t=>t[1]))})))}({fs:t.fs,matches:r,context:t.context});return new o.vD({result:{case:"content",value:new o.Zp({matches:s,totalLines:s.reduce(((t,r)=>t+r.matches.length),0),totalMatchedLines:r.length,...n})}})}({fs:t,query:{pattern:e.pattern,path:s,glob:i,caseInsensitive:!0===e.caseInsensitive},outputMode:n,page:a,context:"content"===n?{before:O({specific:e.contextBefore,both:e.context}),after:O({specific:e.contextAfter,both:e.context})}:{before:0,after:0}});return new o.Ud({result:{case:"success",value:new o._0({pattern:e.pattern,path:s,outputMode:n,workspaceResults:{[r]:u}})}})}catch(t){return M((0,l.q_)(t)?G(t,`invalid grep pattern: ${e.pattern}`):G(t,"grep failed"))}}({fs:t,workspace:e},n)}}function A(t){t.rows.has(t.lineNumber)||t.rows.set(t.lineNumber,new o.dx({lineNumber:t.lineNumber,content:t.content,contentTruncated:!1,isContextLine:!0}))}async function $(t,r){try{return(0,m.Zy)(await t.read(r)).split("\n")}catch{return[]}}function M(t){return new o.Ud({result:{case:"error",value:new o.ts({error:t})}})}function O(t){return D(t.specific??t.both)??0}function D(t){if(void 0!==t&&Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function N(t,r){return t instanceof Error&&"path"in t&&"string"==typeof t.path?t.path:r}function G(t,r){return t instanceof Error&&""!==t.message?t.message:r}},"./src/agent/filesystem/local-fs.ts"(t,r,e){e.d(r,{I2:()=>a,VP:()=>o,rK:()=>i,xh:()=>u});var n=e("node:path"),s=e("./src/agent/errors.ts");const i="localFileSystem";function o(...t){if(t.some((t=>void 0!==t?.fs)))throw new s.j1("local.fs is only supported for local SDK agents. Omit cloud options, or omit local.fs.",{isRetryable:!1})}function a(t){if(void 0===t.fs)return;const r=[void 0!==t.subagentInherit?"local.subagentInherit":void 0,void 0!==t.resourceProviderOptions?"local.resourceProviderOptions":void 0].filter((t=>void 0!==t));if(r.length>0)throw new s.j1(`local.fs cannot be combined with ${r.join(", ")}: local.fs sets the session's executors and its Task children. Remove ${r.join(", ")}.`,{isRetryable:!1});void 0!==t.reportedWorkspacePath&&u(t.reportedWorkspacePath)}function u(t){const r=r=>{throw new s.j1(`local.reportedWorkspacePath ${JSON.stringify(t)} is not a workspace inside local.fs: ${r}.`,{isRetryable:!1})};t.startsWith("/")&&!t.includes("\\")||r('it must be an absolute posix path such as "/repo"');const e=n.posix.normalize(t),i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e;return("/tmp"===i||i.startsWith("/tmp/"))&&r("/tmp is the SDK's scratch space and is empty at the start of every run"),i}},"./src/agent/filesystem/merge.ts"(t,r,e){async function*n(t,r){const{compare:e,unique:n=!1}=r,a=new o(((t,r)=>{const n=e(t.value,r.value);return 0!==n?n:t.source-r.source})),u=t.map(((t,r)=>({iterator:Symbol.asyncIterator in t?t[Symbol.asyncIterator]():async function*(){yield*t}(),sourceIndex:r})));for(await Promise.all(u.map((async({iterator:t,sourceIndex:r})=>{const e=await t.next();e.done||a.push({value:e.value,iterator:t,source:r})})));a.size>0;){const t=a.pop();if(void 0===t)return;yield t.value,n?await i(a,t,e):await s(a,t)}}async function s(t,r){const e=await r.iterator.next();e.done||t.push({value:e.value,iterator:r.iterator,source:r.source})}async function i(t,r,e){for(await s(t,r);t.size>0;){const n=t.peek();if(void 0===n||0!==e(n.value,r.value))return;const i=t.pop();if(void 0===i)return;await s(t,i)}}e.d(r,{C:()=>n});class o{constructor(t){this.compare=t,this.items=[]}get size(){return this.items.length}peek(){return this.items[0]}push(t){this.items.push(t),this.bubbleUp(this.items.length-1)}pop(){const t=this.items[0];if(void 0===t)return;const r=this.items.pop();return void 0===r||0===this.items.length||(this.items[0]=r,this.bubbleDown(0)),t}bubbleUp(t){let r=t;for(;r>0;){const t=Math.floor((r-1)/2),e=this.items[t],n=this.items[r];if(void 0===e||void 0===n||this.compare(n,e)>=0)return;this.items[t]=n,this.items[r]=e,r=t}}bubbleDown(t){let r=t;for(;;){const t=2*r+1,e=t+1;let n=r;const s=this.items[n],i=this.items[t];void 0!==i&&void 0!==s&&this.compare(i,s)<0&&(n=t);const o=this.items[n],a=this.items[e];if(void 0!==a&&void 0!==o&&this.compare(a,o)<0&&(n=e),n===r)return;const u=this.items[r],c=this.items[n];if(void 0===u||void 0===c)return;this.items[r]=c,this.items[n]=u,r=n}}}},"./src/agent/filesystem/trees.ts"(t,r,e){e.d(r,{Om:()=>l,f1:()=>c,i$:()=>f,iK:()=>m});var n=e("./src/agent/filesystem/errors.ts"),s=e("./src/agent/filesystem/walk.ts");async function*i(){}function o(t){return void 0===t||""===t?"/":(0,s.eI)(t)}function a(t){return"string"==typeof t?t:new Uint8Array(t)}const u=new TextEncoder;function c(){return{list:()=>i(),glob:()=>i(),async*grep(t){const r=o(t.path);(0,s.kN)({pattern:t.pattern,caseInsensitive:t.caseInsensitive,path:r}),yield*i()},stat:async t=>(0,s.dN)([],t),async read(t){throw new n.kG((0,s.eI)(t))},async write(t){throw new n.QK((0,s.eI)(t))},async delete(t){throw new n.QK((0,s.eI)(t))}}}function l(t={}){const r=new Map,e=new Map,i=(t,n)=>{const i=(0,s.eI)(t);r.set(i,a(n)),e.set(i,function(t){return"string"==typeof t?u.encode(t).byteLength:t.byteLength}(n))};for(const[r,e]of Object.entries(t))i(r,e);const c=()=>[...e.entries()].map((([t,r])=>({path:t,size:r})));return{list:(t,r)=>(0,s.qq)(c(),t,r),stat:async t=>(0,s.dN)(r.keys(),t),async read(t){const e=(0,s.eI)(t),i=r.get(e);if(void 0===i)throw new n.kG(e);return a(i)},async*grep(t){yield*(0,s.I6)(async function*(){const e=o(t.path),n=(0,s.kN)({pattern:t.pattern,caseInsensitive:t.caseInsensitive,path:e}),i=r.get(e);if("/"!==e&&void 0!==i){if(void 0!==t.glob&&!(0,s.ZC)({filePath:e,dir:e,globPattern:t.glob,matchBasename:!0}))return;if((0,s.a)(e,t.excludes))return;return void(yield*(0,s.sn)({path:e,content:(0,s.Zy)(i),regex:n}))}const a=(0,s.qq)(c(),"/"===e?void 0:e,void 0===t.excludes?void 0:{excludes:t.excludes});for await(const i of a){if(void 0!==t.glob&&!(0,s.ZC)({filePath:i.path,dir:e,globPattern:t.glob,matchBasename:!0}))continue;const o=r.get(i.path);void 0!==o&&(yield*(0,s.sn)({path:i.path,content:(0,s.Zy)(o),regex:n}))}}(),t.maxResults)},async*glob(t,r,e){const n=void 0===r||""===r?"/":(0,s.eI)(r);yield*(0,s.lN)((0,s.qq)(c(),"/"===n?void 0:n),{pattern:t,dir:n,limit:e?.limit})},async write(t,r){i(t,r)},async delete(t){const i=(0,s.eI)(t);if(!r.has(i))throw new n.kG(i);r.delete(i),e.delete(i)}}}function m(t){return{list:(r,e)=>t.list(r,e),stat:r=>t.stat(r),glob:(r,e,n)=>t.glob(r,e,n),read:r=>t.read(r),grep:r=>t.grep(r),async write(t){throw new n.QK((0,s.eI)(t))},async delete(t){throw new n.QK((0,s.eI)(t))}}}async function f(t,r){const e=await t.read(r.path);if("string"!=typeof e)throw new n.F(r.path,`${r.path} is not text`);if(""===r.oldText)throw new n.F(r.path,"oldText is empty");if(r.oldText===r.newText)throw new n.F(r.path,"oldText and newText are exactly the same");const s=function(t){let r=0,e=0;for(;e<=t.haystack.length-t.needle.length;){const n=t.haystack.indexOf(t.needle,e);if(-1===n)break;r++,e=n+t.needle.length}return r}({haystack:e,needle:r.oldText});if(0===s)throw new n.F(r.path,"The string to replace was not found in the file");const i=!0===r.replaceAll;if(s>1&&!i)throw new n.F(r.path,"The string to replace was found multiple times in the file. Use replace_all to replace all occurrences, or include more context to only edit one occurrence.");return await t.write(r.path,function(t){if(t.replaceAll)return t.existing.split(t.oldText).join(t.newText);const r=t.existing.indexOf(t.oldText);return-1===r?t.existing:t.existing.slice(0,r)+t.newText+t.existing.slice(r+t.oldText.length)}({existing:e,oldText:r.oldText,newText:r.newText,replaceAll:i})),{occurrencesModified:s}}},"./src/agent/filesystem/types.ts"(t,r,e){e.d(r,{H:()=>n});const n=1e3},"./src/agent/filesystem/walk.ts"(t,r,e){e.d(r,{SC:()=>ht,e4:()=>pt,h:()=>qt,kN:()=>Bt,Zy:()=>bt,lN:()=>St,sn:()=>It,a:()=>ct,I6:()=>yt,qq:()=>_t,eV:()=>ft,mU:()=>wt,eI:()=>st,c9:()=>ot,hJ:()=>it,ZC:()=>ut,dN:()=>Jt});var n=e("node:path"),s=e.n(n),i=e("../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js");const o=t=>{if("string"!=typeof t)throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},a={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},u=t=>t.replace(/[[\]\\-]/g,"\\$&"),c=t=>t.join(""),l=(t,r)=>{const e=r;if("["!==t.charAt(e))throw new Error("not in a brace expression");const n=[],s=[];let i=e+1,o=!1,l=!1,m=!1,f=!1,d=e,p="";t:for(;ip?n.push(u(p)+"-"+u(r)):r===p&&n.push(u(r)),p="",i++):t.startsWith("-]",i+1)?(n.push(u(r+"-")),i+=2):t.startsWith("-",i+1)?(p=r,i+=2):(n.push(u(r)),i++)}else m=!0,i++}else f=!0,i++}if(de?r?t.replace(/\[([^/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):r?t.replace(/\[([^/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var f;const d=new Set(["!","?","+","*","@"]),p=t=>d.has(t),h=t=>p(t.type),g=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),_=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),J=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),w=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),y="(?!\\.)",S=new Set(["[","."]),q=new Set(["..","."]),B=new Set("().*{}+?[]^$\\!"),I="[^/]",P=I+"*?",b=I+"+?";let R=0;class v{type;#t;#r;#e=!1;#n=[];#s;#i;#o;#a=!1;#u;#c;#l=!1;id=++R;get depth(){return(this.#s?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#t.id,parent:this.#s?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(t,r,e={}){this.type=t,t&&(this.#r=!0),this.#s=r,this.#t=this.#s?this.#s.#t:this,this.#u=this.#t===this?e:this.#t.#u,this.#o=this.#t===this?[]:this.#t.#o,"!"!==t||this.#t.#a||this.#o.push(this),this.#i=this.#s?this.#s.#n.length:0}get hasMagic(){if(void 0!==this.#r)return this.#r;for(const t of this.#n)if("string"!=typeof t&&(t.type||t.hasMagic))return this.#r=!0;return this.#r}toString(){return void 0!==this.#c?this.#c:this.type?this.#c=this.type+"("+this.#n.map((t=>String(t))).join("|")+")":this.#c=this.#n.map((t=>String(t))).join("")}#m(){if(this!==this.#t)throw new Error("should only call on root");if(this.#a)return this;let t;for(this.toString(),this.#a=!0;t=this.#o.pop();){if("!"!==t.type)continue;let r=t,e=r.#s;for(;e;){for(let n=r.#i+1;!e.type&&n"string"==typeof t?t:t.toJSON())):[this.type,...this.#n.map((t=>t.toJSON()))];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#a&&"!"===this.#s?.type)&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#s?.isStart())return!1;if(0===this.#i)return!0;const t=this.#s;for(let r=0;r"string"!=typeof t)),n=this.#n.map((r=>{const[n,s,i,o]="string"==typeof r?f.#q(r,this.#r,e):r.toRegExpSource(t);return this.#r=this.#r||i,this.#e=this.#e||o,n})).join("");let s="";if(this.isStart()&&"string"==typeof this.#n[0]&&(1!==this.#n.length||!q.has(this.#n[0]))){const e=S,i=r&&e.has(n.charAt(0))||n.startsWith("\\.")&&e.has(n.charAt(2))||n.startsWith("\\.\\.")&&e.has(n.charAt(4)),o=!r&&!t&&e.has(n.charAt(0));s=i?"(?!(?:^|/)\\.\\.?(?:$|/))":o?y:""}let i="";return this.isEnd()&&this.#t.#a&&"!"===this.#s?.type&&(i="(?:$|\\/)"),[s+n+i,m(n),this.#r=!!this.#r,this.#e]}const e="*"===this.type||"+"===this.type,n="!"===this.type?"(?:(?!(?:":"(?:";let s=this.#B(r);if(this.isStart()&&this.isEnd()&&!s&&"!"!==this.type){const t=this.toString(),r=this;return r.#n=[t],r.type=null,r.#r=void 0,[t,m(this.toString()),!1,!1]}let i=!e||t||r?"":this.#B(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let o="";return o="!"===this.type&&this.#l?(this.isStart()&&!r?y:"")+b:n+s+("!"===this.type?"))"+(!this.isStart()||r||t?"":y)+P+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&i?")":"*"===this.type&&i?")?":`)${this.type}`),[o,m(s),this.#r=!!this.#r,this.#e]}#S(){if(h(this)){let t=0,r=!1;do{r=!0;for(let t=0;t{if("string"==typeof r)throw new Error("string type in extglob ast??");const[e,n,s,i]=r.toRegExpSource(t);return this.#e=this.#e||i,e})).filter((t=>!(this.isStart()&&this.isEnd()&&!t))).join("|")}static#q(t,r,e=!1){let n=!1,s="",i=!1,o=!1;for(let a=0;a(o(r),!(!e.nocomment&&"#"===r.charAt(0))&&new rt(r,e).match(t)),k=/^\*+([^+@!?*[(]*)$/,E=t=>r=>!r.startsWith(".")&&r.endsWith(t),C=t=>r=>r.endsWith(t),T=t=>(t=t.toLowerCase(),r=>!r.startsWith(".")&&r.toLowerCase().endsWith(t)),U=t=>(t=t.toLowerCase(),r=>r.toLowerCase().endsWith(t)),A=/^\*+\.\*+$/,$=t=>!t.startsWith(".")&&t.includes("."),M=t=>"."!==t&&".."!==t&&t.includes("."),O=/^\.\*+$/,D=t=>"."!==t&&".."!==t&&t.startsWith("."),N=/^\*+$/,G=t=>0!==t.length&&!t.startsWith("."),L=t=>0!==t.length&&"."!==t&&".."!==t,F=/^\?+([^+@!?*[(]*)?$/,K=([t,r=""])=>{const e=W([t]);return r?(r=r.toLowerCase(),t=>e(t)&&t.toLowerCase().endsWith(r)):e},z=([t,r=""])=>{const e=Q([t]);return r?(r=r.toLowerCase(),t=>e(t)&&t.toLowerCase().endsWith(r)):e},j=([t,r=""])=>{const e=Q([t]);return r?t=>e(t)&&t.endsWith(r):e},H=([t,r=""])=>{const e=W([t]);return r?t=>e(t)&&t.endsWith(r):e},W=([t])=>{const r=t.length;return t=>t.length===r&&!t.startsWith(".")},Q=([t])=>{const r=t.length;return t=>t.length===r&&"."!==t&&".."!==t},V="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";x.sep="win32"===V?"\\":"/";const X=Symbol("globstar **");x.GLOBSTAR=X,x.filter=(t,r={})=>e=>x(e,t,r);const Y=(t,r={})=>Object.assign({},t,r);x.defaults=t=>{if(!t||"object"!=typeof t||!Object.keys(t).length)return x;const r=x;return Object.assign(((e,n,s={})=>r(e,n,Y(t,s))),{Minimatch:class extends r.Minimatch{constructor(r,e={}){super(r,Y(t,e))}static defaults(e){return r.defaults(Y(t,e)).Minimatch}},AST:class extends r.AST{constructor(r,e,n={}){super(r,e,Y(t,n))}static fromGlob(e,n={}){return r.AST.fromGlob(e,Y(t,n))}},unescape:(e,n={})=>r.unescape(e,Y(t,n)),escape:(e,n={})=>r.escape(e,Y(t,n)),filter:(e,n={})=>r.filter(e,Y(t,n)),defaults:e=>r.defaults(Y(t,e)),makeRe:(e,n={})=>r.makeRe(e,Y(t,n)),braceExpand:(e,n={})=>r.braceExpand(e,Y(t,n)),match:(e,n,s={})=>r.match(e,n,Y(t,s)),sep:r.sep,GLOBSTAR:X})};const Z=(t,r={})=>(o(t),r.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:(0,i.fT)(t,{max:r.braceExpandMax}));x.braceExpand=Z,x.makeRe=(t,r={})=>new rt(t,r).makeRe(),x.match=(t,r,e={})=>{const n=new rt(r,e);return t=t.filter((t=>n.match(t))),n.options.nonull&&!t.length&&t.push(r),t};const tt=/[?*]|[+@!]\(.*?\)|\[|\]/;class rt{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){o(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||V,this.isWindows="win32"===this.platform,this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||!1===r.allowWindowsEscape,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=void 0!==r.windowsNoMagicRoot?r.windowsNoMagicRoot:!(!this.isWindows||!this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const t of this.set)for(const r of t)if("string"!=typeof r)return!0;return!1}debug(...t){}make(){const t=this.pattern,r=this.options;if(!r.nocomment&&"#"===t.charAt(0))return void(this.comment=!0);if(!t)return void(this.empty=!0);this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...t)=>console.error(...t)),this.debug(this.pattern,this.globSet);const e=this.globSet.map((t=>this.slashSplit(t)));this.globParts=this.preprocess(e),this.debug(this.pattern,this.globParts);let n=this.globParts.map(((t,r,e)=>{if(this.isWindows&&this.windowsNoMagicRoot){const r=!(""!==t[0]||""!==t[1]||"?"!==t[2]&&tt.test(t[2])||tt.test(t[3])),e=/^[a-z]:/i.test(t[0]);if(r)return[...t.slice(0,4),...t.slice(4).map((t=>this.parse(t)))];if(e)return[t[0],...t.slice(1).map((t=>this.parse(t)))]}return t.map((t=>this.parse(t)))}));if(this.debug(this.pattern,n),this.set=n.filter((t=>-1===t.indexOf(!1))),this.isWindows)for(let t=0;t=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):t=r>=1?this.levelOneOptimize(t):this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map((t=>{let r=-1;for(;-1!==(r=t.indexOf("**",r+1));){let e=r;for(;"**"===t[e+1];)e++;e!==r&&t.splice(r,e-r)}return t}))}levelOneOptimize(t){return t.map((t=>0===(t=t.reduce(((t,r)=>{const e=t[t.length-1];return"**"===r&&"**"===e?t:".."===r&&e&&".."!==e&&"."!==e&&"**"!==e?(t.pop(),t):(t.push(r),t)}),[])).length?[""]:t))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let e=1;en&&e.splice(n+1,s-n);let i=e[n+1];const o=e[n+2],a=e[n+3];if(".."!==i)continue;if(!o||"."===o||".."===o||!a||"."===a||".."===a)continue;r=!0,e.splice(n,1);const u=e.slice(0);u[n]="**",t.push(u),n--}if(!this.preserveMultipleSlashes){for(let t=1;tt.length))}partsMatch(t,r,e=!1){let n=0,s=0,i=[],o="";for(;n=2&&(t=this.levelTwoFileOptimize(t)),r.includes(X)?this.#I(t,r,e,n,s):this.#P(t,r,e,n,s)}#I(t,r,e,n,s){const i=r.indexOf(X,s),o=r.lastIndexOf(X),[a,u,c]=e?[r.slice(s,i),r.slice(i+1),[]]:[r.slice(s,i),r.slice(i+1,o),r.slice(o+1)];if(a.length){const r=t.slice(n,n+a.length);if(!this.#P(r,a,e,0,0))return!1;n+=a.length,s+=a.length}let l=0;if(c.length){if(c.length+n>t.length)return!1;let r=t.length-c.length;if(this.#P(t,c,e,r,0))l=c.length;else{if(""!==t[t.length-1]||n+c.length===t.length)return!1;if(r--,!this.#P(t,c,e,r,0))return!1;l=c.length+1}}if(!u.length){let r=!!l;for(let e=n;e{const r=t.map((t=>{if(t instanceof RegExp)for(const r of t.flags.split(""))n.add(r);return"string"==typeof t?t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):t===X?X:t._src}));r.forEach(((t,n)=>{const s=r[n+1],i=r[n-1];t===X&&i!==X&&(void 0===i?void 0!==s&&s!==X?r[n+1]="(?:\\/|"+e+"\\/)?"+s:r[n]=e:void 0===s?r[n-1]=i+"(?:\\/|\\/"+e+")?":s!==X&&(r[n-1]=i+"(?:\\/|\\/"+e+"\\/)"+s,r[n+1]=X))}));const s=r.filter((t=>t!==X));if(this.partial&&s.length>=1){const t=[];for(let r=1;r<=s.length;r++)t.push(s.slice(0,r).join("/"));return"(?:"+t.join("|")+")"}return s.join("/")})).join("|");const[i,o]=t.length>1?["(?:",")"]:["",""];s="^"+i+s+o+"$",this.partial&&(s="^(?:\\/|"+i+s.slice(1,-1)+o+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...n].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return""===t;if("/"===t&&r)return!0;const e=this.options;this.isWindows&&(t=t.split("\\").join("/"));const n=this.slashSplit(t);this.debug(this.pattern,"split",n);const s=this.set;this.debug(this.pattern,"set",s);let i=n[n.length-1];if(!i)for(let t=n.length-2;!i&&t>=0;t--)i=n[t];for(const t of s){let s=n;if(e.matchBase&&1===t.length&&(s=[i]),this.matchOne(s,t,r))return!!e.flipNegate||!this.negate}return!e.flipNegate&&this.negate}static defaults(t){return x.defaults(t).Minimatch}}x.AST=v,x.Minimatch=rt,x.escape=(t,{windowsPathsNoEscape:r=!1,magicalBraces:e=!1}={})=>e?r?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):r?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),x.unescape=m;var et=e("./src/agent/filesystem/errors.ts"),nt=e("./src/agent/filesystem/merge.ts");function st(t){const r=t.replace(/\\/g,"/");if(""===r)return"/";const e=r.startsWith("/")?r:`/${r}`,n=s().posix.normalize(e);return n.length>1&&n.endsWith("/")?n.slice(0,-1):"."===n||""===n?"/":n}function it(t){const r=st(t.path),e=st(t.prefix);return"/"===e||r===e||r.startsWith(`${e}/`)}function ot(t){return void 0===t||""===t||"/"===t?"/":st(t)}function at(t,r){return x(t,r,{dot:!0,nocase:!1})}function ut(t){const r=t.filePath.replace(/\\/g,"/"),e=t.dir.replace(/\\/g,"/");let n;if(n="/"===e?r.replace(/^\//,""):r.startsWith(`${e}/`)?r.slice(e.length+1):r.replace(/^\//,""),at(n,t.globPattern)||at(r.replace(/^\//,""),t.globPattern))return!0;if(!0===t.matchBasename&&!t.globPattern.includes("/")){const r=n.lastIndexOf("/");return at(-1===r?n:n.slice(r+1),t.globPattern)}return!1}function ct(t,r){return void 0!==r&&0!==r.length&&r.some((r=>function(t,r){const e=r.startsWith("**/")?r:"**/"+r,n=t.replace(/^\//,"");for(const r of[n,t])if(x(r,e,{dot:!0})||x(r,`${e}/**`,{dot:!0}))return!0;return!1}(t,r)))}function lt(t,r){return t.path.localeCompare(r.path)}function mt(t){if(void 0!==t&&Number.isFinite(t))return Math.max(0,Math.floor(t))}function ft(t){return mt(t?.maxDepth)}function dt(t,r,e){const n=function(t,r){return"/"===t?r.replace(/^\//,"").split("/"):r.startsWith(`${t}/`)?r.slice(t.length+1).split("/"):void 0}(r,t.path);return void 0===n||n.length<=e?t:{path:`${"/"===r?"":r}/${n.slice(0,e).join("/")}`,kind:"directory"}}function pt(t){if(t.maxDepth<1)return[];const r=new Map;for(const e of t.entries){const n=dt(e,t.scope,t.maxDepth);r.has(n.path)||r.set(n.path,n)}return[...r.values()].sort(lt)}async function*ht(t,r){const e=[];for await(const r of t)e.push(r);yield*gt(pt({entries:e,scope:r.scope,maxDepth:r.maxDepth}),r.limit)}function gt(t,r){const e=mt(r);return void 0===e?[...t]:t.slice(0,e)}async function*_t(t,r,e){const n=ot(r),s="/"===n?"/":`${n}/`,i=[];for(const r of t){const t=st(r.path);("/"===n||t!==n&&t.startsWith(s))&&(ct(t,e?.excludes)||i.push(void 0===r.size?{path:t}:{path:t,size:r.size}))}const o=ft(e),a=void 0===o?i.sort(lt):pt({entries:i,scope:n,maxDepth:o});yield*gt(a,e?.limit)}function Jt(t,r){const e=ot(r);if("/"===e)return{kind:"directory"};const n=`${e}/`;for(const r of t){const t=st(r);if(t===e)return{kind:"file"};if(t.startsWith(n))return{kind:"directory"}}return{kind:"missing"}}async function*wt(t,r){yield*(0,nt.C)(t,{compare:lt,unique:!0===r?.unique})}async function*yt(t,r){const e=mt(r);if(0===e)return;let n=0;for await(const r of t)if(yield r,n++,void 0!==e&&n>=e)return}async function*St(t,r){yield*yt(async function*(){for await(const e of t)ut({filePath:e.path,dir:r.dir,globPattern:r.pattern})&&(yield e)}(),r.limit)}function qt(t,r){return t.pathr.path?1:t.lineNumber-r.lineNumber}function Bt(t){try{return new RegExp(t.pattern,!0===t.caseInsensitive?"i":void 0)}catch{throw new et.kp(t.pattern,t.path)}}function*It(t){for(const[r,e]of t.content.split("\n").entries())t.regex.test(e)&&(yield{path:t.path,lineNumber:r+1,line:e})}const Pt=new TextDecoder;function bt(t){return"string"==typeof t?t:Pt.decode(t)}},"./src/agent/messages.ts"(t,r,e){e.d(r,{J5:()=>p,LN:()=>c,MV:()=>i,Nk:()=>u,bM:()=>d,cD:()=>a,do:()=>o,xc:()=>f});var n=e("./src/agent/errors.ts"),s=e("./src/agent/usage-types.ts");const i=1,o="run_stream_event";function a(t,r,e){return"summary-started"===t.type?{type:"summary",agent_id:r,run_id:e,status:"running"}:{type:"summary",agent_id:r,run_id:e,status:!0===t.failed?"error":"completed",...!0===t.fallback?{fallback:!0}:{}}}function u(t){return{schemaVersion:i,type:"sdk_message",agentId:t.agent_id,runId:t.run_id,message:t}}function c(t){if(!function(t){return"object"==typeof t&&null!==t&&"schemaVersion"in t&&"type"in t}(t))throw new n.j1("Invalid local run stream event payload",{isRetryable:!1});if(t.schemaVersion!==i)throw new n.j1(`Unsupported local run stream event schema version ${l(t.schemaVersion)}`,{isRetryable:!1});if("sdk_message"!==t.type&&"result"!==t.type&&"done"!==t.type)throw new n.j1(`Unsupported local run stream event type ${l(t.type)}`,{isRetryable:!1});const r="string"==typeof t.agentId?t.agentId:void 0,e="string"==typeof t.runId?t.runId:void 0;if(void 0===r||void 0===e)throw new n.j1("Invalid local run stream event payload",{isRetryable:!1});if("sdk_message"===t.type&&function(t){return"object"==typeof t&&null!==t&&"type"in t&&"agent_id"in t&&"run_id"in t}(t.message))return{schemaVersion:i,type:"sdk_message",agentId:r,runId:e,message:m(t.message)};if("result"===t.type&&("finished"===(s=t.status)||"error"===s||"cancelled"===s)){const n="string"==typeof t.errorCode?t.errorCode:void 0;return{schemaVersion:i,type:"result",agentId:r,runId:e,status:t.status,...void 0!==n?{errorCode:n}:{}}}var s;if("done"===t.type)return{schemaVersion:i,type:"done",agentId:r,runId:e};throw new n.j1(`Unsupported local run stream event type ${l(t.type)}`,{isRetryable:!1})}function l(t){return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?String(t):"unknown"}function m(t){if("usage"!==t.type)return t;const r=(0,s.g8)(t.usage);return r?{...t,usage:r}:t}function f(t){return"sdk_message"===t.type?t.message:void 0}function d(t){const r=c(t),e=f(r);if(!e)throw new n.j1(`Local run stream event ${r.type} is not an SDK message`,{isRetryable:!1});return e}function p(t){return"done"===t.type||"result"===t.type||"status"===(r=t.message).type&&("FINISHED"===r.status||"ERROR"===r.status||"CANCELLED"===r.status||"EXPIRED"===r.status);var r}},"./src/agent/native/vendored-tree-sitter.ts"(t,r,e){e.r(r),e.d(r,{configureVendoredTreeSitterWorkspaceDir:()=>a,createUnavailableParserClass:()=>c,loadVendoredTreeSitterModule:()=>u});var n=e("node:fs"),s=e("node:path"),i=e("./src/agent/platform-package-locator.ts");const o=new Set;function a(t){o.add((0,s.resolve)(t))}function u(t){const r=function(){const t=process.env.CURSOR_TREE_SITTER_VENDOR_DIR;return t&&(0,s.isAbsolute)(t)?t:(0,i.nk)({relativePath:"vendor",excludedWorkspaceDirs:o.size>0?[...o]:[process.cwd()],accept:t=>(0,n.existsSync)((0,s.join)(t,"tree-sitter","index.js"))})}();return void 0===r?{available:!1,reason:`the @cursor/sdk-${process.platform}-${process.arch} optional dependency (which vendors the tree-sitter natives) is not installed; shell command analysis is disabled`}:{available:!0,module:t.nativeRequire((0,s.join)(r,t.packageName,"index.js"))}}function c(t){return class{constructor(){const r=new Error(t);throw Object.assign(r,{code:"CURSOR_TREE_SITTER_STUBBED"})}}}},"./src/agent/platform-package-locator.ts"(t,r,e){e.d(r,{hQ:()=>c,nk:()=>u});var n=e("node:fs"),s=e("node:path");function i(t){try{const r=(0,n.statSync)(t);return r.isFile()&&("win32"===process.platform||!!(73&r.mode))}catch{return!1}}function o(t){let r=(0,s.resolve)(t);const e=(0,s.parse)(r).root;for(;;){if((0,n.existsSync)((0,s.join)(r,".git")))return r;if(r===e)return;r=(0,s.dirname)(r)}}const a="string"==typeof __filename?(0,s.dirname)(__filename):void 0;function u(t){const{relativePath:r,accept:e}=t,n=`${process.platform}-${process.arch}`,i=[`@cursor/sdk-${n}`,`@cursor/february-${n}`],u=[];for(const r of t.excludedWorkspaceDirs){u.push((0,s.resolve)(r));const t=o(r);void 0!==t&&u.push(t)}const c=[];process.argv[1]&&c.push({startDir:(0,s.dirname)((0,s.resolve)(process.argv[1])),excludeWorkspaceHelpers:!1});const l=t.sdkModuleDir??a;void 0!==l&&c.push({startDir:(0,s.resolve)(l),excludeWorkspaceHelpers:!1}),c.push({startDir:(0,s.dirname)((0,s.resolve)(process.execPath)),excludeWorkspaceHelpers:!0});const m=t=>u.some((r=>function(t){const r=(0,s.relative)((0,s.resolve)(t.directory),(0,s.resolve)(t.candidatePath));return""===r||!r.startsWith("..")&&!(0,s.isAbsolute)(r)}({candidatePath:t,directory:r})));for(const{startDir:t,excludeWorkspaceHelpers:n}of c){let o=t;const a=(0,s.parse)(o).root;for(;o!==a;){for(const t of i){const i=(0,s.join)(o,"node_modules",t,r);if(e(i)&&(!n||!m(i)))return i}o=(0,s.dirname)(o)}}}function c(t){return u({relativePath:(0,s.join)("bin",t.binaryName),excludedWorkspaceDirs:[t.excludedWorkspaceDir],accept:i})}},"./src/agent/run-interaction-accumulator.ts"(t,r,e){e.d(r,{KG:()=>i,e4:()=>s});var n=e("./src/agent/usage-types.ts");class s{constructor(t={}){this.options=t,this.turns=[],this.currentTurn=null,this.lastFiredStepIndex=-1,this.openTurnModelCalls=[]}conversation(){return[...this.turns]}usage(){return(0,n.wV)([this.endedTurnsUsage,...this.openTurnModelCalls])}finalAssistantText(){for(let t=this.turns.length-1;t>=0;t--){const r=this.turns[t];if("agentConversationTurn"!==r?.type)continue;const e=r.turn.steps;for(let t=e.length-1;t>=0;t--){const r=e[t];if("assistantMessage"===r?.type)return r.message.text}}}async apply(t){this.recordUsage(t),this.didPreviousStepComplete(t.type)&&await this.flushPendingStep();const{didStepComplete:r}=this.mergeIntoConversation(t);r&&await this.flushPendingStep(),function(t){return"summary"===t.type||"summary-started"===t.type||"summary-completed"===t.type}(t)||await(this.options.onDelta?.({update:t}))}recordUsage(t){switch(t.type){case"model-call-completed":this.openTurnModelCalls.push(t.usage);break;case"turn-ended":this.endedTurnsUsage=(0,n.wV)([this.endedTurnsUsage,t.usage??(0,n.wV)(this.openTurnModelCalls)]),this.openTurnModelCalls=[]}}async flushPendingStep(){const t=this.currentTurn;if(!t)return;const r=t.steps.length-1;if(r>this.lastFiredStepIndex&&r>=0){const e=t.steps[r];await(this.options.onStep?.({step:e})),this.lastFiredStepIndex=r}}ensureCurrentTurn(){if(this.currentTurn)return this.currentTurn;const t={steps:[]};return this.turns.push({type:"agentConversationTurn",turn:t}),this.currentTurn=t,t}mergeIntoConversation(t){switch(t.type){case"user-message-appended":this.onUserMessage(t),this.lastFiredStepIndex=-1;break;case"text-delta":this.onTextDelta(t);break;case"thinking-delta":this.onThinkingDelta(t);break;case"thinking-completed":return this.onThinkingCompleted(t),{didStepComplete:!0};case"tool-call-completed":return this.onTool(t),{didStepComplete:!0}}return{didStepComplete:!1}}onUserMessage(t){const r={userMessage:{text:t.userMessage.text},steps:[]};this.turns.push({type:"agentConversationTurn",turn:r}),this.currentTurn=r}onTextDelta(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];if("assistantMessage"!==e?.type)r.steps.push({type:"assistantMessage",message:{text:t.text}});else{const n=e.message,s={...n,text:`${n.text}${t.text}`};r.steps[r.steps.length-1]={type:"assistantMessage",message:s}}}onThinkingDelta(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];if("thinkingMessage"!==e?.type)r.steps.push({type:"thinkingMessage",message:{text:t.text}});else{const n=e.message,s={...n,text:`${n.text}${t.text}`};r.steps[r.steps.length-1]={type:"thinkingMessage",message:s}}}onThinkingCompleted(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];"thinkingMessage"===e?.type&&(r.steps[r.steps.length-1]={type:"thinkingMessage",message:{...e.message,thinkingDurationMs:t.thinkingDurationMs}})}onTool(t){this.ensureCurrentTurn().steps.push({type:"toolCall",message:t.toolCall})}didPreviousStepComplete(t){const r=this.currentTurn;if(!r||0===r.steps.length)return!1;const e=r.steps[r.steps.length-1].type;return"token-delta"!==t&&"summary"!==t&&"summary-started"!==t&&"summary-completed"!==t&&("assistantMessage"===e&&"text-delta"!==t||"thinkingMessage"===e&&"thinking-delta"!==t&&"thinking-completed"!==t)}}async function i(t){const r=new s;for await(const e of t){const t=o(e);t&&await r.apply(t)}return await r.flushPendingStep(),r.conversation()}function o(t){switch(t.type){case"user":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t.agent_id,text:t.message.content.map((t=>t.text)).join("")}};case"assistant":{const r=t.message.content.filter((t=>"text"===t.type)).map((t=>t.text)).join("");return r?{type:"text-delta",text:r}:void 0}case"thinking":return void 0!==t.thinking_duration_ms&&""===t.text?{type:"thinking-completed",thinkingDurationMs:t.thinking_duration_ms}:{type:"thinking-delta",text:t.text};case"tool_call":if("running"===t.status)return;return{type:"tool-call-completed",callId:t.call_id,modelCallId:t.call_id,toolCall:a(t)};default:return}}function a(t){return{type:t.name,..."args"in t?{args:t.args}:{},...void 0!==t.result?{result:t.result}:{},...void 0!==t.truncated?{truncated:t.truncated}:{}}}},"./src/agent/sdk-config.ts"(t,r,e){e.d(r,{Mu:()=>c,it:()=>u,xP:()=>a});var n=e("./src/agent/errors.ts"),s=e("./src/agent/store/sdk-local-defaults.ts");let i,o;function a(t){if(void 0!==t.local&&"store"in t.local&&(0,s.Dt)(t.local.store??void 0),void 0!==t.local&&"useHttp1ForAgent"in t.local&&(i=t.local.useHttp1ForAgent??void 0),void 0!==t.local&&"workspaceScanCacheTtlMs"in t.local){const r=t.local.workspaceScanCacheTtlMs??void 0;if(void 0!==r&&(!Number.isFinite(r)||r<=0))throw new n.j1(`local.workspaceScanCacheTtlMs must be a positive number of milliseconds, got ${r}`,{isRetryable:!1});o=r}}function u(){return i}function c(){return o}},"./src/agent/store/local-agent-record-conversion.ts"(t,r,e){function n(t){return{agentId:t.agentId,cwd:t.workspaceRef,status:c(t.status),activeRunId:t.activeRunId??null,latestCheckpoint:t.latestCheckpointRef?a(t.latestCheckpointRef):null,name:t.name??null,createdAt:t.createdAt.getTime(),updatedAt:t.updatedAt.getTime(),sdkMetadata:t.metadata}}function s(t){const r=t.finishedAt?.getTime()??t.cancelledAt?.getTime()??t.expiredAt?.getTime()??null;return{runId:t.runId,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:m(t.status),model:t.model??null,result:t.result??null,error:t.errorCode??null,usageRef:t.usageRef??null,usage:t.usage??null,createdAt:t.createdAt.getTime(),updatedAt:t.updatedAt.getTime(),startedAt:t.startedAt?.getTime()??null,endedAt:r,startCheckpointRef:t.startCheckpointRef?a(t.startCheckpointRef):null,latestCheckpointRef:t.latestCheckpointRef?a(t.latestCheckpointRef):null}}function i(t){return{agentId:t.agentId,workspaceRef:t.cwd,status:l(t.status),activeRunId:t.activeRunId??null,latestCheckpointRef:t.latestCheckpoint?u(t.latestCheckpoint):null,name:t.name??null,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),metadata:t.sdkMetadata??{}}}function o(t){const r=function(t){switch(t){case"queued":return"QUEUED";case"running":return"RUNNING";case"finished":return"FINISHED";case"error":return"ERROR";case"cancelled":return"CANCELLED";case"expired":return"EXPIRED";default:throw new Error("unexpected local run status")}}(t.status),e=t.endedAt?new Date(t.endedAt):null;return{runId:t.runId,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:r,model:t.model??null,startCheckpointRef:t.startCheckpointRef?u(t.startCheckpointRef):null,latestCheckpointRef:t.latestCheckpointRef?u(t.latestCheckpointRef):null,errorCode:t.error??null,result:t.result??null,usageRef:t.usageRef??null,usage:t.usage??null,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),startedAt:t.startedAt?new Date(t.startedAt):null,finishedAt:"FINISHED"===r?e:null,cancelledAt:"CANCELLED"===r?e:null,expiredAt:"EXPIRED"===r?e:null}}function a(t){return{schemaVersion:1,rootBlobId:t.blobId}}function u(t){return{blobId:t.rootBlobId,storeKind:"local-agent-store"}}function c(t){switch(t){case"IDLE":return"idle";case"RUNNING":return"running";case"ERROR":return"error";case"ARCHIVED":return"archived";default:throw new Error("unexpected agent lifecycle status")}}function l(t){switch(t){case"idle":return"IDLE";case"running":return"RUNNING";case"error":return"ERROR";case"archived":return"ARCHIVED";default:throw new Error("unexpected local agent status")}}function m(t){switch(t){case"QUEUED":return"queued";case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"ERROR":return"error";case"CANCELLED":return"cancelled";case"EXPIRED":return"expired";default:throw new Error("unexpected run lifecycle status")}}e.d(r,{EB:()=>n,R:()=>o,UY:()=>i,xu:()=>s})},"./src/agent/store/local-agent-store.ts"(t,r,e){e.d(r,{HL:()=>p,In:()=>m,Jg:()=>J,S$:()=>_,f1:()=>S,hA:()=>w,oc:()=>l,tg:()=>y});var n=e("../agent-kv/dist/agent-store.js"),s=e("../agent-kv/dist/blob-store.js"),i=e("../agent-kv/dist/serde.js"),o=e("../context/dist/core.js"),a=e("../proto/dist/generated/agent/v1/agent_pb.js"),u=e("../utils/dist/fresh-uuid.js"),c=e("./src/agent/store/local-agent-record-conversion.ts");function l(t){const r=new d(t.localStore,t.workspaceRef,t.scopedWorkspaceRef);return{store:r,checkpointStore:r,eventStore:new f(t.localStore.runEvents)}}function m(t){return{agents:t.agents,checkpoints:t.checkpoints,runs:t.runs,runEvents:t.runEvents}}class f{constructor(t){this.runEvents=t}appendRunEvent(t){return this.runEvents.append({runId:t.runId,eventType:t.eventType,payload:t.payload,payloadRef:t.payloadRef,idempotencyKey:t.idempotencyKey}).then(b)}listRunEvents(t){return this.runEvents.list({runId:t.runId,afterOffset:t.afterOffset,limit:t.limit}).then(R)}deleteRunEvents(t){return this.runEvents.delete({filter:{runIds:[t.runId]}})}}class d{constructor(t,r,e){this.localStore=t,this.workspaceRef=r,this.scopedWorkspaceRef=e,this.blobStores=new Map}async createAgent(t){const r=t.agentId??`agent-${(0,u.C)()}`;if(await this.localStore.agents.get({agentId:r}))throw new Error(`Agent ${r} already exists`);const e=this.workspaceRefForPersist(t.workspaceRef),n=Date.now(),s=x({agentId:r,requestId:t.requestId,turnNumber:1,model:t.model??null,timestamp:n}),i={agentId:r,cwd:e,status:"idle",activeRunId:null,name:t.name??null,createdAt:n,updatedAt:n,sdkMetadata:t.metadata??{}};await this.localStore.agents.create({agent:i});try{await this.localStore.runs.create({run:s}),await this.localStore.agents.update({agent:{...i,activeRunId:s.runId,updatedAt:Date.now()}})}catch(t){try{await this.localStore.runs.delete({filter:{agentIds:[r]}}),await this.localStore.agents.delete({filter:{agentIds:[r]}})}catch{}throw t}return{agent:k(await this.requireAgent(r)),run:E(s)}}async createFollowUpRun(t,r={}){const e=await this.requireAgent(t);if("archived"===e.status)throw new Error(`Cannot create follow-up run on archived agent ${t}. Unarchive it first.`);if(e.activeRunId){const r=await this.localStore.runs.get({agentId:t,runId:e.activeRunId});if(r&&!C(r.status))throw new Error(`Agent ${t} already has active run`)}const n=await async function(t,r){let e,n=0;do{const s=await t.runs.list({filter:{agentIds:[r],cursor:e}});n+=s.items.length,e=s.nextCursor}while(e);return n+1}(this.localStore,t),s=Date.now(),i=e.latestCheckpoint??null,o=x({agentId:t,requestId:r.requestId,turnNumber:n,model:r.model??null,timestamp:s,startCheckpointRef:i,latestCheckpointRef:i});return await this.localStore.runs.create({run:o}),await this.localStore.agents.update({agent:{...e,status:"idle",activeRunId:o.runId,sdkMetadata:{...e.sdkMetadata,...r.metadata},updatedAt:s}}),E(o)}async listAgents(t){const r=await this.localStore.agents.list({filter:{cursor:t?.cursor,limit:t?.limit,...void 0!==this.scopedWorkspaceRef?{cwd:this.scopedWorkspaceRef}:{}}});return{items:r.items.map(k),nextCursor:r.nextCursor}}async getAgent(t){const r=await this.getScopedAgentDocument(t);return r?k(r):null}async listRuns(t,r){await this.requireAgent(t);const e=await this.localStore.runs.list({filter:{agentIds:[t],cursor:r?.cursor,limit:r?.limit}});return{items:e.items.map((t=>E(t))),nextCursor:e.nextCursor}}async getRun(t,r){await this.requireAgent(t);const e=await this.localStore.runs.get({agentId:t,runId:r});return e?E(e):null}async markRunStarting(t,r,e){await this.updateRun(t,r,(t=>{if(C(t.status))throw new Error(`Cannot start terminal run ${r}`);const n=Date.now();return{run:{...t,requestId:e?.requestId??t.requestId??null,status:"running",startedAt:t.startedAt??n,updatedAt:n},agent:{status:"running",activeRunId:r,updatedAt:n}}}))}async patchCheckpoint(t,r,e){const n={schemaVersion:1,rootBlobId:e.blobId};await this.updateRun(t,r,(t=>{const r=Date.now();return{run:{...t,latestCheckpointRef:n,updatedAt:r},agent:{latestCheckpoint:n,updatedAt:r}}}))}async markRunTerminal(t,r,e){await this.updateRun(t,r,(t=>{if(C(t.status))return void 0===e.usage||null!==t.usage&&void 0!==t.usage?{run:t,agent:{}}:{run:{...t,usage:e.usage},agent:{}};const r=Date.now(),n=function(t){switch(t){case"FINISHED":return"finished";case"ERROR":return"error";case"CANCELLED":return"cancelled";case"EXPIRED":return"expired";default:throw new Error("unexpected run lifecycle status")}}(e.status);return{run:{...t,status:n,error:e.errorCode??t.error??null,usageRef:e.usageRef??t.usageRef??null,usage:void 0!==e.usage?e.usage:t.usage??null,result:e.result??t.result??null,updatedAt:r,endedAt:r},agent:{activeRunId:null,status:"ERROR"===e.status?"error":"idle",updatedAt:r}}}))}async cancelRun(t,r){await this.markRunTerminal(t,r,{status:"CANCELLED"})}async archiveAgent(t){const r=await this.requireAgent(t);await this.localStore.agents.update({agent:{...r,status:"archived",updatedAt:Date.now()}})}async unarchiveAgent(t){const r=await this.requireAgent(t);await this.localStore.agents.update({agent:{...r,status:"idle",updatedAt:Date.now()}})}async deleteAgent(t){const r=await this.requireAgent(t);if(r.activeRunId){const e=await this.localStore.runs.get({agentId:t,runId:r.activeRunId});if(e&&!C(e.status))throw new Error(`Cannot delete agent ${t}: active run ${r.activeRunId} is not terminal. Call run.cancel() first.`)}const e=[];let n;do{const r=await this.localStore.runs.list({filter:{agentIds:[t],cursor:n}});for(const t of r.items)e.push(t.runId);n=r.nextCursor}while(n);this.blobStores.delete(t),await this.localStore.runs.delete({filter:{agentIds:[t]}});for(const t of e)await this.localStore.runEvents.delete({filter:{runIds:[t]}});await this.localStore.checkpoints.delete({filter:{agentIds:[t]}}),await this.localStore.agents.delete({filter:{agentIds:[t]}})}async loadLatest(t){const r=await this.getScopedAgentDocument(t);if(!r?.latestCheckpoint)return this.blobStores.delete(t),null;const e=await g(this.localStore,t,r.latestCheckpoint),n=this.setBlobStore(t,e),s=await n.getBlob((0,o.q6)(),T(e.rootBlobId));if(!s)throw h(t,r.latestCheckpoint.rootBlobId);return a.Y9z.fromBinary(s)}async saveCheckpoint(t,r){const e=await this.getOrCreateBlobStore(t),n=r.toBinary(),a=await(0,s.Bk)(n);await e.setBlob((0,o.q6)(),a,n);const u=(0,i.nj)(a),c=await this.requireAgent(t);return await this.localStore.agents.update({agent:{...c,latestCheckpoint:{schemaVersion:1,rootBlobId:u},updatedAt:Date.now()}}),{blobId:u,storeKind:"local-agent-store"}}async getBlobStore(t){return this.getOrCreateBlobStore(t)}async getFullConversation(t){const r=await this.getScopedAgentDocument(t);if(!r?.latestCheckpoint)return new a.ljj;const e=await g(this.localStore,t,r.latestCheckpoint),i=new s.We;!function(t,r){const e=(0,n.sh)(r);t.set("agentId",e.agentId),t.set("latestRootBlobId",e.latestRootBlobId),t.set("name",e.name),t.set("createdAt",e.createdAt),t.set("mode",e.mode),t.set("isRunEverything",e.isRunEverything),t.set("approvalMode",e.approvalMode),t.set("lastUsedModel",e.lastUsedModel),t.set("lastDebugServerPort",e.lastDebugServerPort),t.set("currentPlanUri",e.currentPlanUri)}(i,t),i.set("latestRootBlobId",T(e.rootBlobId));const u=new n.pH(this.setBlobStore(t,e),i);return await u.resetFromDb((0,o.q6)()),u.getFullConversation((0,o.q6)())}async getScopedAgentDocument(t){const r=await this.localStore.agents.get({agentId:t});return r&&this.agentMatchesScope(r)?r:null}agentMatchesScope(t){return void 0===this.scopedWorkspaceRef||t.cwd===this.scopedWorkspaceRef}workspaceRefForPersist(t){if(void 0!==this.scopedWorkspaceRef&&t!==this.scopedWorkspaceRef)throw new Error(`Cannot create agent: workspaceRef "${t}" does not match scoped workspace "${this.scopedWorkspaceRef}"`);return this.scopedWorkspaceRef??t}async requireAgent(t){const r=await this.getScopedAgentDocument(t);if(!r)throw new Error(`Agent ${t} not found`);return r}async updateRun(t,r,e){await this.requireAgent(t);const n=await this.localStore.runs.get({agentId:t,runId:r});if(!n)throw new Error(`Run ${r} not found for agent ${t}`);const s=e(n);await this.localStore.runs.update({run:s.run});const i=s.agent;if(Object.keys(i).length>0){const r=await this.requireAgent(t),e=r.latestCheckpoint??s.run.latestCheckpointRef??null;await this.localStore.agents.update({agent:{...r,...i,latestCheckpoint:e,status:"archived"===r.status&&void 0!==i.status?"archived":i.status??r.status}})}}async getOrCreateBlobStore(t){const r=this.blobStores.get(t);if(r)return r;const e=await this.getScopedAgentDocument(t);return e?.latestCheckpoint?this.setBlobStore(t,await g(this.localStore,t,e.latestCheckpoint)):this.createPersistingBlobStore(t)}setBlobStore(t,r){const e=v.fromBundle(r,this.createPersistBlob(t));return this.blobStores.set(t,e),e}createPersistingBlobStore(t){const r=new v(this.createPersistBlob(t));return this.blobStores.set(t,r),r}createPersistBlob(t){return async(r,e)=>{null!==await this.localStore.checkpoints.get({agentId:t,blobId:r})?await this.localStore.checkpoints.update({agentId:t,blobId:r,data:e}):await this.localStore.checkpoints.create({agentId:t,blobId:r,data:e})}}}function p(t,r){return!r?.agentIds?.length&&void 0===r?.cwd||!(r.agentIds?.length&&!r.agentIds.includes(t.agentId))&&(void 0===r.cwd||t.cwd===r.cwd)}function h(t,r){return new Error(`Corrupt local agent checkpoint: missing root blob ${r} for agent ${t}`)}async function g(t,r,e){const n=await t.checkpoints.get({agentId:r,blobId:e.rootBlobId});if(!n)throw h(r,e.rootBlobId);const s={[e.rootBlobId]:U(n)};let i;do{const n=await t.checkpoints.list({filter:{agentIds:[r],cursor:i}});for(const i of n.items){if(i===e.rootBlobId)continue;const n=await t.checkpoints.get({agentId:r,blobId:i});n&&(s[i]=U(n))}i=n.nextCursor}while(i);return{schemaVersion:1,rootBlobId:e.rootBlobId,blobs:s}}function _(t,r){return!((r?.agentIds?.length||r?.blobIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.blobIds?.length&&!r.blobIds.includes(t.blobId)))}function J(t,r){const e=[...t].sort(((t,r)=>t.localeCompare(r))),n=r?.limit??50;let s=e;r?.cursor&&(s=e.filter((t=>t>r.cursor)));const i=s.slice(0,n),o=i.at(-1);return{items:i,...s.length>n&&o?{nextCursor:o}:{}}}function w(t,r){return!((r?.agentIds?.length||r?.runIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.runIds?.length&&!r.runIds.includes(t.runId)))}function y(t,r){const e=[...void 0===r?.cwd?t:t.filter((t=>t.cwd===r.cwd))].sort(q),n=r?.limit??50;let s=e;if(r?.cursor){const t=function(t){const r=P(t);if("number"!=typeof r.updatedAt||"string"!=typeof r.agentId)throw new Error("Invalid agent list cursor");return{updatedAt:r.updatedAt,agentId:r.agentId}}(r.cursor);s=e.filter((r=>function(t,r){return t.updatedAtr.updatedAt)&&t.agentIdstructuredClone(t))),...s.length>n&&o?{nextCursor:I({updatedAt:o.updatedAt,agentId:o.agentId})}:{}}}function S(t,r){const e=[...t].sort(B),n=r?.limit??50;let s=e;if(r?.cursor){const t=function(t){const r=P(t);if("number"!=typeof r.turnNumber||"string"!=typeof r.runId)throw new Error("Invalid run list cursor");return{turnNumber:r.turnNumber,runId:r.runId}}(r.cursor);s=e.filter((r=>function(t,r){return t.turnNumber>r.turnNumber||!(t.turnNumberr.runId}(r,t)))}const i=s.slice(0,n),o=i.at(-1);return{items:i.map((t=>structuredClone(t))),...s.length>n&&o?{nextCursor:I({turnNumber:o.turnNumber,runId:o.runId})}:{}}}function q(t,r){return r.updatedAt!==t.updatedAt?r.updatedAt-t.updatedAt:r.agentId.localeCompare(t.agentId)}function B(t,r){return t.turnNumber!==r.turnNumber?t.turnNumber-r.turnNumber:t.runId.localeCompare(r.runId)}function I(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function P(t){try{const r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}(r))return r}catch{}throw new Error("Invalid list cursor")}function b(t){return{runId:t.runId,seq:t.seq,offset:t.offset,eventType:t.eventType,payload:t.payload,payloadRef:t.payloadRef,idempotencyKey:t.idempotencyKey,createdAt:new Date(t.createdAt)}}function R(t){return{events:t.items.map(b),...void 0!==t.nextOffset?{nextOffset:t.nextOffset}:{}}}class v{constructor(t){this.persistBlob=t,this.blobs=new Map}static fromBundle(t,r){const e=new v(r);for(const[r,s]of Object.entries(t.blobs))e.blobs.set(r,(n=s,new Uint8Array(Buffer.from(n,"base64"))));var n;return e}async getBlob(t,r){return this.blobs.get((0,i.nj)(r))}async setBlob(t,r,e){const n=(0,i.nj)(r),s=A(e);this.blobs.set(n,s),await(this.persistBlob?.(n,s))}async setBlobLocallyOnly(t,r,e){this.blobs.set((0,i.nj)(r),A(e))}async flush(t){}}function x(t){return{runId:`run-${(0,u.C)()}`,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:"queued",model:t.model,result:null,error:null,usageRef:null,usage:null,createdAt:t.timestamp,updatedAt:t.timestamp,startedAt:null,endedAt:null,startCheckpointRef:t.startCheckpointRef??null,latestCheckpointRef:t.latestCheckpointRef??null}}function k(t){return(0,c.UY)(t)}function E(t){return(0,c.R)(t)}function C(t){return"finished"===t||"error"===t||"cancelled"===t||"expired"===t}function T(t){const r=new Uint8Array(t.length/2);for(let e=0;ei,kP:()=>s})},"./src/agent/store/sdk-state-root.ts"(t,r,e){e.d(r,{V:()=>u});var n=e("node:crypto"),s=e("node:fs"),i=e("node:os"),o=e("node:path"),a=e("../utils/dist/workspace-paths.js");function u(t){const r=(0,o.join)((0,a.Rv)((0,i.homedir)(),t),"sdk-agent-store"),e=(0,o.join)(r,(0,n.createHash)("sha256").update(t).digest("hex"));if((0,s.existsSync)(e))return e;const u=function(t){try{return(0,n.createHash)("md5").update(t).digest("hex")}catch(t){if(function(t){if(!(t instanceof Error))return!1;return"ERR_OSSL_EVP_UNSUPPORTED"===t.code||"Digest method not supported"===t.message}(t))return;throw t}}(t);if(void 0===u)return e;const c=(0,o.join)(r,u);if(!(0,s.existsSync)(c))return e;try{return(0,s.renameSync)(c,e),e}catch{return(0,s.existsSync)(c)?c:e}}},"./src/agent/subagent-conversion.ts"(t,r,e){e.d(r,{DB:()=>o,SB:()=>i});var n=e("./src/agent/errors.ts");function s(t){if(void 0===t)return;const r=Object.entries(t);if(0===r.length)return;const e=[];for(const[t,s]of r){if(void 0!==s.mcpServers)for(const r of s.mcpServers)if("string"!=typeof r)throw new n.j1(`Custom subagent "${t}" has an inline McpServerConfig in mcpServers; SDK custom subagents only support string references in v1.`);const r=void 0===s.model||"inherit"===s.model?"inherit":s.model;e.push({name:t,description:s.description,prompt:s.prompt,model:r})}return e}function i(t){return s(t)}function o(t){const r=s(t);if(void 0!==r)return r.map((t=>({name:t.name,description:t.description,prompt:t.prompt,model:"inherit"===t.model?"inherit":t.model.id})))}},"./src/agent/team-id.ts"(t,r,e){e.d(r,{E:()=>s,P:()=>n});const n="x-cursor-team-id";function s(t){if("number"==typeof t&&Number.isSafeInteger(t)&&!(t<=0))return t}},"./src/agent/tool-call-utils.ts"(t,r,e){function n(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function s(t){return!!n(t)&&!(void 0!==t.args&&"boolean"!=typeof t.args||void 0!==t.result&&"boolean"!=typeof t.result)}e.d(r,{D:()=>s,u:()=>n})},"./src/agent/tools-option.ts"(t,r,e){e.d(r,{$$:()=>i,TX:()=>m,VJ:()=>o,db:()=>f});var n=e("../proto/dist/generated/agent/v1/agent_pb.js"),s=e("./src/agent/errors.ts");const i="x-cursor-agent-allowed-tools",o="x-cursor-agent-exclude-tools",a={shell:["shell_tool_call","write_shell_stdin_tool_call"],mcp:["mcp_tool_call","get_mcp_tools_tool_call","list_mcp_resources_tool_call","read_mcp_resource_tool_call","mcp_auth_tool_call"]};let u,c;function l(){if(void 0===u){u=new Map,c=[];for(const t of n.Dm_.fields.list()){if("tool"!==t.oneof?.localName)continue;const r=t.localName.replace(/ToolCall$/,""),e=a[r]??[t.name];u.set(r,e),u.set(t.name,[t.name]),u.set(t.localName,[t.name]),c.push(r)}c.sort()}return u}function m(t){return d(t,"tools")}function f(t){return d(t,"disallowedTools")}function d(t,r){if(void 0===t)return;const e=l(),n=new Set,i=[];for(const r of t){const t=e.get(r.trim());if(void 0!==t)for(const r of t)n.add(r);else i.push(r)}if(i.length>0)throw new s.j1(`Unknown tool name(s) in \`${r}\`: ${i.join(", ")}. Valid tool names: ${(l(),c??[]).join(", ")}.`,{isRetryable:!1});return[...n]}},"./src/agent/transport.ts"(t,r,e){e.d(r,{cf:()=>s});const n=async t=>{if(function(){const t=Object.getOwnPropertyDescriptor(globalThis,"Deno");return void 0!==t&&(void 0!==t.get||void 0!==t.value)}()){const{createConnectTransport:r}=await Promise.resolve().then(e.t.bind(e,"@connectrpc/connect-web",23));return r({baseUrl:t.baseUrl,interceptors:t.interceptors})}const{createSafeConnectTransport:r}=await Promise.all([e.e(154),e.e(441)]).then(e.bind(e,"./src/agent/safe-connect-transport.ts"));return r({baseUrl:t.baseUrl,httpVersion:t.httpVersion,interceptors:t.interceptors})};function s(t){let r;const e=()=>(r??=function(t){return n(t)}(t),r);return{unary:(t,r,n,s,i,o,a)=>e().then((e=>e.unary(t,r,n,s,i,o,a))),stream:(t,r,n,s,i,o,a)=>e().then((e=>e.stream(t,r,n,s,i,o,a)))}}},"./src/agent/types/delta-types.ts"(t,r,e){e.d(r,{Zs:()=>P,Dx:()=>w,tq:()=>B,ON:()=>f,M7:()=>_,uj:()=>g,Wf:()=>h,XP:()=>p,yP:()=>o,Y3:()=>l,p$:()=>c,IO:()=>d,EC:()=>u,fr:()=>I,a7:()=>a,Ed:()=>J,Sb:()=>m});var n=e("zod/v3"),s=e("../cursor-sdk-shared/dist/message-schemas.js"),i=e("../cursor-sdk-shared/dist/tool-call-types.js");const o=n.object({type:n.literal("text-delta"),text:n.string()}),a=n.object({type:n.literal("tool-call-started"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),u=n.object({type:n.literal("tool-call-completed"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),c=n.object({type:n.literal("thinking-delta"),text:n.string()}),l=n.object({type:n.literal("thinking-completed"),thinkingDurationMs:n.number()}),m=n.object({type:n.literal("user-message-appended"),userMessage:s.Kx}),f=n.object({type:n.literal("partial-tool-call"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),d=n.object({type:n.literal("token-delta"),tokens:n.number()}),p=n.object({type:n.literal("summary"),summary:n.string()}),h=n.object({type:n.literal("summary-started")}),g=n.object({type:n.literal("summary-completed"),failed:n.boolean().optional(),fallback:n.boolean().optional()}),_=n.object({type:n.literal("shell-output-delta"),event:n.record(n.string(),n.unknown())}),J=n.object({type:n.literal("turn-ended"),usage:n.object({inputTokens:n.number(),outputTokens:n.number(),cacheReadTokens:n.number(),cacheWriteTokens:n.number(),reasoningTokens:n.number().optional()}).optional()}),w=n.object({type:n.literal("model-call-completed"),modelCallId:n.string(),usage:n.object({inputTokens:n.number(),outputTokens:n.number(),cacheReadTokens:n.number(),cacheWriteTokens:n.number(),reasoningTokens:n.number().optional()})}),y=n.object({type:n.literal("step-started"),stepId:n.number()}),S=n.object({type:n.literal("tool-requests-listed"),callCount:n.number()}),q=n.object({type:n.literal("step-completed"),stepId:n.number(),stepDurationMs:n.number()}),B=n.discriminatedUnion("type",[o,a,u,c,l,f,y,q,S]),I=n.object({type:n.literal("tool-call-delta"),callId:n.string(),modelCallId:n.string(),taskUpdate:B}),P=n.discriminatedUnion("type",[o,a,u,c,l,m,f,d,p,h,g,_,J,w,y,q,S,I])},"./src/agent/usage-types.ts"(t,r,e){function n(t){if(!t)return;const{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,reasoningTokens:i}=t;return{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,totalTokens:r+e,...void 0!==i?{reasoningTokens:i}:{}}}function s(t){let r=0,e=0,n=0,s=0,i=0,o=!1,a=!1;for(const u of t)u&&(o=!0,r+=u.inputTokens,e+=u.outputTokens,n+=u.cacheReadTokens,s+=u.cacheWriteTokens,void 0!==u.reasoningTokens&&(a=!0,i+=u.reasoningTokens));if(o)return{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,totalTokens:r+e,...a?{reasoningTokens:i}:{}}}function i(t){if(t)return"number"==typeof t.inputTokens&&"number"==typeof t.outputTokens&&"number"==typeof t.cacheReadTokens&&"number"==typeof t.cacheWriteTokens?n(t):t}e.d(r,{g8:()=>i,qI:()=>n,wV:()=>s})},"./src/agent/utils/logger.ts"(t,r,e){e.d(r,{v:()=>n});const n={log:(...t)=>{},error:(...t)=>{},warn:(...t)=>{},info:(...t)=>{},debug:(...t)=>{}}},"@bufbuild/protobuf"(t){t.exports=require("@bufbuild/protobuf")},"@connectrpc/connect"(t){t.exports=require("@connectrpc/connect")},"@connectrpc/connect-web"(t){t.exports=require("@connectrpc/connect-web")},"bun:sqlite"(t){t.exports=require("bun:sqlite")},"node:sqlite"(t){t.exports=require("node:sqlite")},zod(t){t.exports=require("zod")},"zod/v3"(t){t.exports=require("zod/v3")},"zod/v4"(t){t.exports=require("zod/v4")},"zod/v4-mini"(t){t.exports=require("zod/v4-mini")},assert(t){t.exports=require("assert")},buffer(t){t.exports=require("buffer")},child_process(t){t.exports=require("child_process")},crypto(t){t.exports=require("crypto")},events(t){t.exports=require("events")},fs(t){t.exports=require("fs")},http(t){t.exports=require("http")},http2(t){t.exports=require("http2")},https(t){t.exports=require("https")},"node:assert"(t){t.exports=require("node:assert")},"node:async_hooks"(t){t.exports=require("node:async_hooks")},"node:buffer"(t){t.exports=require("node:buffer")},"node:child_process"(t){t.exports=require("node:child_process")},"node:constants"(t){t.exports=require("node:constants")},"node:crypto"(t){t.exports=require("node:crypto")},"node:events"(t){t.exports=require("node:events")},"node:fs"(t){t.exports=require("node:fs")},"node:fs/promises"(t){t.exports=require("node:fs/promises")},"node:module"(t){t.exports=require("node:module")},"node:net"(t){t.exports=require("node:net")},"node:os"(t){t.exports=require("node:os")},"node:path"(t){t.exports=require("node:path")},"node:perf_hooks"(t){t.exports=require("node:perf_hooks")},"node:process"(t){t.exports=require("node:process")},"node:readline"(t){t.exports=require("node:readline")},"node:stream"(t){t.exports=require("node:stream")},"node:stream/promises"(t){t.exports=require("node:stream/promises")},"node:string_decoder"(t){t.exports=require("node:string_decoder")},"node:timers/promises"(t){t.exports=require("node:timers/promises")},"node:url"(t){t.exports=require("node:url")},"node:util"(t){t.exports=require("node:util")},"node:zlib"(t){t.exports=require("node:zlib")},path(t){t.exports=require("path")},stream(t){t.exports=require("stream")},string_decoder(t){t.exports=require("string_decoder")},util(t){t.exports=require("util")},zlib(t){t.exports=require("zlib")},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"(t,r,e){var n;e.d(r,{C:()=>n}),function(t){t[t.Canceled=1]="Canceled",t[t.Unknown=2]="Unknown",t[t.InvalidArgument=3]="InvalidArgument",t[t.DeadlineExceeded=4]="DeadlineExceeded",t[t.NotFound=5]="NotFound",t[t.AlreadyExists=6]="AlreadyExists",t[t.PermissionDenied=7]="PermissionDenied",t[t.ResourceExhausted=8]="ResourceExhausted",t[t.FailedPrecondition=9]="FailedPrecondition",t[t.Aborted=10]="Aborted",t[t.OutOfRange=11]="OutOfRange",t[t.Unimplemented=12]="Unimplemented",t[t.Internal=13]="Internal",t[t.Unavailable=14]="Unavailable",t[t.DataLoss=15]="DataLoss",t[t.Unauthenticated=16]="Unauthenticated"}(n||(n={}))},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"(t,r,e){e.d(r,{T:()=>i});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js");class i extends Error{constructor(t,r=n.C.Unknown,e,i,o){super(function(t,r){return t.length?`[${(0,s.s)(r)}] ${t}`:`[${(0,s.s)(r)}]`}(t,r)),this.name="ConnectError",Object.setPrototypeOf(this,new.target.prototype),this.rawMessage=t,this.code=r,this.metadata=new Headers(null!=e?e:{}),this.details=null!=i?i:[],this.cause=o}static from(t,r=n.C.Unknown){return t instanceof i?t:t instanceof Error?"AbortError"==t.name?new i(t.message,n.C.Canceled):new i(t.message,r,void 0,void 0,t):new i(String(t),r,void 0,void 0,t)}findDetails(t){const r="typeName"in t?{findMessage:r=>r===t.typeName?t:void 0}:t,e=[];for(const t of this.details){if("getType"in t){r.findMessage(t.getType().typeName)&&e.push(t);continue}const n=r.findMessage(t.type);if(n)try{e.push(n.fromBinary(t.value))}catch(t){}}return e}}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js"(t,r,e){e.d(r,{X:()=>o,s:()=>s});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js");function s(t){const r=n.C[t];return"string"!=typeof r?t.toString():r[0].toLowerCase()+r.substring(1).replace(/[A-Z]/g,(t=>"_"+t.toLowerCase()))}let i;function o(t){if(!i){i={};for(const t of Object.values(n.C))"string"!=typeof t&&(i[s(t)]=t)}return i[t]}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"(t,r,e){e.d(r,{T$:()=>I,Jt:()=>B,Fs:()=>h,WK:()=>d,SM:()=>p,fM:()=>J,ew:()=>w,yQ:()=>y,uv:()=>_,XO:()=>g,pY:()=>S});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"),i=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js");class o{constructor(t){this.readMaxBytes=t,this.header=new Uint8Array(5),this.headerView=new DataView(this.header.buffer),this.buf=[]}get byteLength(){return this.buf.reduce(((t,r)=>t+r.byteLength),0)}decode(t){this.buf.push(t);const r=[];for(;;){let t=this.pop();if(!t)break;r.push(t)}return r}pop(){if((this.env||(this.env=this.head(),this.env))&&this.cons(this.env.data)){const t=this.env;return this.env=void 0,t}}head(){if(!this.cons(this.header))return;const t=this.headerView.getUint8(0),r=this.headerView.getUint32(1);return(0,i.kk)(this.readMaxBytes,r,!0),{flags:t,data:new Uint8Array(r)}}cons(t){const r=t.byteLength;if(this.byteLengthr-e?(t.set(n.subarray(0,r-e),e),this.buf.unshift(n.subarray(r-e)),e+=r-e):(t.set(n,e),e+=n.byteLength)}return!0}}async function a(t,r,e){let{flags:i,data:o}=t;if(!(1&~i))throw new s.T("invalid envelope, already compressed",n.C.Internal);return r&&o.byteLength>=e&&(o=await r.compress(o),i|=1),{data:o,flags:i}}async function u(t,r,e){let{flags:i,data:o}=t;if(!(1&~i)){if(!r)throw new s.T("received compressed envelope, but do not know how to decompress",n.C.Internal);o=await r.decompress(o,e),i^=1}return{data:o,flags:i}}function c(t,r){const e=new Uint8Array(r.length+5);e.set(r,5);const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setUint8(0,t),n.setUint32(1,r.length),e}var l=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,e=t[Symbol.asyncIterator];return e?e.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(e){r[e]=t[e]&&function(r){return new Promise((function(n,s){!function(t,r,e,n){Promise.resolve(n).then((function(r){t({value:r,done:e})}),r)}(n,s,(r=t[e](r)).done,r.value)}))}}},m=function(t){return this instanceof m?(this.v=t,this):new m(t)},f=function(t,r,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=e.apply(t,r||[]),i=[];return n={},o("next"),o("throw"),o("return",(function(t){return function(r){return Promise.resolve(r).then(t,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function o(t,r){s[t]&&(n[t]=function(r){return new Promise((function(e,n){i.push([t,r,e,n])>1||a(t,r)}))},r&&(n[t]=r(n[t])))}function a(t,r){try{(e=s[t](r)).value instanceof m?Promise.resolve(e.value.v).then(u,c):l(i[0][2],e)}catch(t){l(i[0][3],t)}var e}function u(t){a("next",t)}function c(t){a("throw",t)}function l(t,r){t(r),i.shift(),i.length&&a(i[0][0],i[0][1])}};function d(t,...r){const[e,n,s]=function(t){let r;"function"!=typeof t[t.length-1]&&(r=t.pop());const e=t.pop();return[t,e,r]}(r);let i,o=t;return!0===(null==s?void 0:s.propagateDownStreamError)&&(o=i=q(o)),o=h(o,...e,{propagateDownStreamError:!1}),n(o).catch((t=>i?i.abort(t).then((()=>Promise.reject(t))):Promise.reject(t)))}function p(t,r){return async function(e){return await async function(t,r,e){var o,a,u,c,m,f,d,p;const[h,g]=function(t){if(null==t)return[!1,0];const r="string"==typeof t?parseInt(t,10):t;return!Number.isSafeInteger(r)||r<0?[!1,r]:[!0,r]}(e);if(h){g>r&&(0,i.kk)(r,g,!0);const e=new Uint8Array(g);let m=0;try{for(var _,J=!0,w=l(t);!(o=(_=await w.next()).done);J=!0){c=_.value,J=!1;const t=c;if(m+t.byteLength>g)throw new s.T(`protocol error: promised ${g} bytes, received ${m+t.byteLength}`,n.C.InvalidArgument);e.set(t,m),m+=t.byteLength}}catch(t){a={error:t}}finally{try{J||o||!(u=w.return)||await u.call(w)}finally{if(a)throw a.error}}if(mo};!0===(null==s?void 0:s.propagateDownStreamError)&&(a=i=q(a));for(const t of n)a=t(a);const u=a[Symbol.asyncIterator]();try{for(;;){const t=yield m(u.next());if(!0===t.done)break;if(i)try{yield yield m(t.value)}catch(t){throw yield m(i.abort(t)),t}else yield yield m(t.value)}}finally{!0===(null==s?void 0:s.propagateDownStreamError)&&(null===(e=o.return)||void 0===e||e.call(o).catch((()=>{})))}}))}function g(t,r,e){return void 0===r||void 0===e?function(r){return f(this,arguments,(function*(){var e,n,s,i;try{for(var o,a=!0,u=l(r);!(e=(o=yield m(u.next())).done);a=!0){i=o.value,a=!1;const r=i,e=t.serialize(r);yield yield m({flags:0,data:e})}}catch(t){n={error:t}}finally{try{a||e||!(s=u.return)||(yield m(s.call(u)))}finally{if(n)throw n.error}}}))}:function(n){return f(this,arguments,(function*(){var s,i,o,a;try{for(var u,c=!0,f=l(n);!(s=(u=yield m(f.next())).done);c=!0){a=u.value,c=!1;const n=a;let s,i=0;n.end?(i|=r,s=e.serialize(n.value)):s=t.serialize(n.value),yield yield m({flags:i,data:s})}}catch(t){i={error:t}}finally{try{c||s||!(o=f.return)||(yield m(o.call(f)))}finally{if(i)throw i.error}}}))}}function _(t,r,e){return e&&void 0!==r?function(n){return f(this,arguments,(function*(){var s,i,o,a;try{for(var u,c=!0,f=l(n);!(s=(u=yield m(f.next())).done);c=!0){a=u.value,c=!1;const{flags:n,data:s}=a;(n&r)===r?yield yield m({value:e.parse(s),end:!0}):yield yield m({value:t.parse(s),end:!1})}}catch(t){i={error:t}}finally{try{c||s||!(o=f.return)||(yield m(o.call(f)))}finally{if(i)throw i.error}}}))}:function(i){return f(this,arguments,(function*(){var o,a,u,c;try{for(var f,d=!0,p=l(i);!(o=(f=yield m(p.next())).done);d=!0){c=f.value,d=!1;const{flags:i,data:o}=c;if(void 0===r||(i&r)!==r)yield yield m(t.parse(o));else if(null===e)throw new s.T("unexpected end flag",n.C.InvalidArgument)}}catch(t){a={error:t}}finally{try{d||o||!(u=p.return)||(yield m(u.call(p)))}finally{if(a)throw a.error}}}))}}function J(t,r){return function(e){return f(this,arguments,(function*(){var n,s,i,o;try{for(var u,c=!0,f=l(e);!(n=(u=yield m(f.next())).done);c=!0){o=u.value,c=!1;const e=o;yield yield m(yield m(a(e,t,r)))}}catch(t){s={error:t}}finally{try{c||n||!(i=f.return)||(yield m(i.call(f)))}finally{if(s)throw s.error}}}))}}function w(t,r){return function(e){return f(this,arguments,(function*(){var n,s,i,o;try{for(var a,c=!0,f=l(e);!(n=(a=yield m(f.next())).done);c=!0){o=a.value,c=!1;const e=o;yield yield m(yield m(u(e,t,r)))}}catch(t){s={error:t}}finally{try{c||n||!(i=f.return)||(yield m(i.call(f)))}finally{if(s)throw s.error}}}))}}function y(){return function(t){return f(this,arguments,(function*(){var r,e,n,s;try{for(var i,o=!0,a=l(t);!(r=(i=yield m(a.next())).done);o=!0){s=i.value,o=!1;const{flags:t,data:r}=s;yield yield m(c(t,r))}}catch(t){e={error:t}}finally{try{o||r||!(n=a.return)||(yield m(n.call(a)))}finally{if(e)throw e.error}}}))}}function S(t){return function(r){return f(this,arguments,(function*(){var e,i,a,u;const c=function(t){return new o(t)}(t);try{for(var f,d=!0,p=l(r);!(e=(f=yield m(p.next())).done);d=!0){u=f.value,d=!1;const t=u;for(const r of c.decode(t))yield yield m(r)}}catch(t){i={error:t}}finally{try{d||e||!(a=p.return)||(yield m(a.call(p)))}finally{if(i)throw i.error}}if(c.byteLength>0)throw new s.T("protocol error: incomplete envelope",n.C.InvalidArgument)}))}}function q(t){const r=t[Symbol.asyncIterator]();if(void 0===r.throw)throw new Error("AsyncIterable does not implement throw");const e=r;let n,s,i={next:()=>(s=e.next().finally((()=>{s=void 0})),s),throw:t=>e.throw(t)};void 0!==r.return&&(i=Object.assign(Object.assign({},i),{return:t=>e.return(t)}));let o=!1;return{abort(t){if(n)return n.state;const r=()=>e.throw(t).then((t=>!0===t.done?"completed":"caught"),(()=>"rethrown"));return s?(n={reason:t,state:s.then(r,r)},n.state):(n={reason:t,state:r()},n.state)},[Symbol.asyncIterator](){if(o)throw new Error("AsyncIterable cannot be re-used");return o=!0,i}}}function B(){const t=[],r=[];let e,n,s,i=new Promise(((t,r)=>{n=t,s=r})),o=!1;function a(){for(const r of t.splice(0,t.length))r({done:!0,value:void 0})}return{close(){o=!0,a()},async write(n){if(o)throw null!=e?e:new Error("cannot write, WritableIterable already closed");const s=t.shift();if(void 0===s)r.push(n);else if(s({done:!1,value:n}),t.length>0)return;const a=r.length+1;for(let t=0;t({next(){n(),i=new Promise(((t,r)=>{n=t,s=r}));const e=r.shift();if(void 0!==e)return Promise.resolve({done:!1,value:e});if(o)return Promise.resolve({done:!0,value:void 0});let a;const u=new Promise((t=>a=t));return t.push(a),u},throw:t=>(e=t,o=!0,r.splice(0,r.length),i.catch((()=>{})),s(e),a(),Promise.resolve({done:!0,value:void 0})),return:()=>(o=!0,r.splice(0,r.length),n(),i=Promise.reject(new Error("cannot write, consumer called return")),i.catch((()=>{})),a(),Promise.resolve({done:!0,value:void 0}))})}}function I(t){return f(this,arguments,(function*(){yield m(yield*function(t){var r,e;return r={},n("next"),n("throw",(function(t){throw t})),n("return"),r[Symbol.iterator]=function(){return this},r;function n(n,s){r[n]=t[n]?function(r){return(e=!e)?{value:m(t[n](r)),done:!1}:s?s(r):r}:s}}(l(t)))}))}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js"(t,r,e){e.d(r,{NL:()=>a,Tw:()=>u,kk:()=>c});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js");const i=4294967295,o=i;function a(t,r,e){if(null!=r||(r=o),null!=t||(t=i),null!=e||(e=1024),r<1||r>o)throw new n.T(`writeMaxBytes ${r} must be >= 1 and <= 4294967295`,s.C.Internal);if(t<1||t>i)throw new n.T(`readMaxBytes ${t} must be >= 1 and <= 4294967295`,s.C.Internal);return{readMaxBytes:t,writeMaxBytes:r,compressMinBytes:e}}function u(t,r){if(r>t)throw new n.T(`message size ${r} is larger than configured writeMaxBytes ${t}`,s.C.ResourceExhausted)}function c(t,r,e=!1){if(r>t){let i=`message size is larger than configured readMaxBytes ${t}`;throw e&&(i=`message size ${r} is larger than configured readMaxBytes ${t}`),new n.T(i,s.C.ResourceExhausted)}}},"../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js"(t,r,e){e.d(r,{fT:()=>x});const n=(t,r,e)=>{const n=t instanceof RegExp?s(t,e):t,o=r instanceof RegExp?s(r,e):r,a=null!==n&&null!=o&&i(n,o,e);return a&&{start:a[0],end:a[1],pre:e.slice(0,a[0]),body:e.slice(a[0]+n.length,a[1]),post:e.slice(a[1]+o.length)}},s=(t,r)=>{const e=r.match(t);return e?e[0]:null},i=(t,r,e)=>{let n,s,i,o,a,u=e.indexOf(t),c=e.indexOf(r,u+1),l=u;if(u>=0&&c>0){if(t===r)return[u,c];for(n=[],i=e.length;l>=0&&!a;){if(l===u)n.push(l),u=e.indexOf(t,l+1);else if(1===n.length){const t=n.pop();void 0!==t&&(a=[t,c])}else s=n.pop(),void 0!==s&&s=0?u:c}n.length&&void 0!==o&&(a=[i,o])}return a},o="\0SLASH"+Math.random()+"\0",a="\0OPEN"+Math.random()+"\0",u="\0CLOSE"+Math.random()+"\0",c="\0COMMA"+Math.random()+"\0",l="\0PERIOD"+Math.random()+"\0",m=new RegExp(o,"g"),f=new RegExp(a,"g"),d=new RegExp(u,"g"),p=new RegExp(c,"g"),h=new RegExp(l,"g"),g=/\\\\/g,_=/\\{/g,J=/\\}/g,w=/\\,/g,y=/\\\./g,S=1e5,q=4e6,B=1e3,I=1e3;function P(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function b(t){return t.replace(m,"\\").replace(f,"{").replace(d,"}").replace(p,",").replace(h,".")}function R(t,r){for(let e=0;e=r}function U(t,r,e,n,s,i){const o=[];let a=0;for(let u=0;u=n)return o;const l=t[u]+r+e[c];if(!i||l){if(a+l.length>s)return o;o.push(l),a+=l.length}}return o}function A(t,r,e,n){const s=t.split(/\.\./),i=[];if(void 0===s[0]||void 0===s[1])return i;const o=P(s[0]),a=P(s[1]),u=Math.max(s[0].length,s[1].length);let c=3===s.length&&void 0!==s[2]?Math.max(Math.abs(P(s[2])),1):1,l=C;a0){const n=new Array(r+1).join("0");e=t<0?"-"+n+e.slice(1):n+e}}if(f+e.length>n)break;i.push(e),f+=e.length}return i}function $(t,r,e,s,i,o,a){if(i>s)return[t];let c=[""],l=0,m=!1,f=!0;for(;;){const d=n("{","}",t);if(!d)return U(c,t,[""],r,e,m);const p=d.pre;if(/\$$/.test(p)){if(c=U(c,p+"{"+d.body+"}",[""],r,e,m&&!d.post.length),f=!1,!d.post.length)break;t=d.post;continue}const h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(d.body),g=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(d.body),_=h||g,J=d.body.indexOf(",")>=0;if(!_&&!J){if(l=r||u+n.length>e)break t;w.push(n),u+=n.length}}}}if(c=U(c,p,w,r,e,m&&!d.post.length),!d.post.length)break;t=d.post}return c}},"../agent-kv/dist/agent-store.js"(t,r,e){e.d(r,{TU:()=>p,aY:()=>y,pH:()=>v,sh:()=>g});var n=e("../proto/dist/generated/agent/v1/agent_pb.js"),s=e("../proto/dist/generated/agent/v1/todo_tool_pb.js"),i=e("../utils/dist/disposable.js"),o=e("zod/v4"),a=e("../agent-kv/dist/blob-store.js"),u=e("../agent-kv/dist/serde.js"),c=e("../agent-kv/dist/subagent-states.js");const l=["default","plan","debug","search"],m=["allowlist","unrestricted","auto-review"],f=/^[0-9a-f]+$/;function d(){const t=new Uint8Array(32);return crypto.getRandomValues(t),(0,u.nj)(t)}function p(t){return"string"==typeof t&&64===t.length&&f.test(t)}let h=null;const g=t=>({agentId:t??crypto.randomUUID(),latestRootBlobId:new Uint8Array,name:"New Agent",mode:"default",isRunEverything:!1,approvalMode:void 0,createdAt:Date.now(),lastUsedModel:void 0,lastDebugServerPort:void 0,currentPlanUri:void 0,subagentInfo:void 0,blobEncryptionKey:d()}),_=new Set(l),J=new Set(m);function w(t,r){const e=function(t){return"object"==typeof t&&null!==t}(t)&&r in t?t[r]:void 0;return"string"==typeof e&&e.length>0?e:void 0}class y{serialize(t){const r=(0,u.nj)(t.latestRootBlobId);return u.bO.serialize(JSON.stringify({...t,latestRootBlobId:r}))}deserialize(t){const r=JSON.parse(u.bO.deserialize(t)),e=g(r.agentId),n="string"==typeof r.latestRootBlobId?(0,u.aD)(r.latestRootBlobId):e.latestRootBlobId;let s=!0===r.isRunEverything,i=r.mode;"auto-run"===i&&(i="default",s=!0);const a="string"==typeof i&&(c=i,_.has(c))?i:"default";var c;const f=r.approvalMode,d="string"==typeof f&&function(t){return J.has(t)}(f)?f:void 0,y=function(t){if(!t||"object"!=typeof t)return;const r=w(t,"parentAgentId"),e=w(t,"rootParentAgentId"),n=w(t,"toolCallId"),s=w(t,"typeName");return void 0!==r&&void 0!==e&&void 0!==n&&void 0!==s?{parentAgentId:r,rootParentAgentId:e,toolCallId:n,typeName:s}:void 0}(r.subagentInfo),S=p(r.blobEncryptionKey)?r.blobEncryptionKey:e.blobEncryptionKey;return(null===h&&(h=o.object({agentId:o.string(),latestRootBlobId:o.custom((t=>t instanceof Uint8Array),{error:"Expected Uint8Array"}),name:o.string(),createdAt:o.number(),mode:o.enum(l),isRunEverything:o.boolean(),approvalMode:o.enum(m).optional(),lastUsedModel:o.string().optional(),lastDebugServerPort:o.number().int().positive().optional(),currentPlanUri:o.string().optional(),subagentInfo:o.object({parentAgentId:o.string().min(1),rootParentAgentId:o.string().min(1),toolCallId:o.string().min(1),typeName:o.string().min(1)}).optional(),blobEncryptionKey:o.string().optional()})),h).parse({...e,...r,mode:a,isRunEverything:s,approvalMode:d,latestRootBlobId:n,subagentInfo:y,blobEncryptionKey:S})}getBlobType(){return{kind:"json"}}}const S=new u.cm(s.kW),q=new u.cm(n.RGk),B=new u.cm(n.kJk),I=new u.cm(n.cmU),P=new u.cm(n.KRq),b=new u.cm(n.oIR),R=new u.cm(n.qKL);class v{constructor(t,r,e={}){this.blobStore=t,this.metadataStore=r,this.serde=new u.cm(n.Y9z),this.conversationStateStructure=new n.Y9z,this.fixedRootBlobId=e.fixedRootBlobId}subscribeToMetadata(t,r){return this.metadataStore.subscribe(t,(()=>{r(this.metadataStore.get(t))}))}setMetadata(t,r){this.metadataStore.set(t,r)}getMetadata(t){return this.metadataStore.get(t)}getId(){return this.getMetadata("agentId")}getBlobStore(){return this.blobStore}getConversationStateStructure(){return this.conversationStateStructure}async getLastRequestIdFromConversation(t){const r=this.conversationStateStructure.turns;if(0===r.length)return null;for(let e=r.length-1;e>=0;e--){const n=r[e],s=await this.blobStore.getBlob(t,n);if(!s)continue;const i=I.deserialize(s);if("agentConversationTurn"===i.turn.case)return i.turn.value.requestId??null}return null}async getFullConversation(t){return this.deserializeConversationStateStructure(t,this.conversationStateStructure)}async deserializeConversationStateStructure(t,r){return async function(t,r,e){const s=new n.ljj,i=[],o=r.turns;for(const r of o){const s=await e.getBlob(t,r);if(!s)continue;const o=I.deserialize(s);let a;switch(o.turn.case){case"agentConversationTurn":{const r=o.turn.value,s=await e.getBlob(t,r.userMessage);if(!s)continue;const i=q.deserialize(s),u=[];for(const n of r.steps){const r=await e.getBlob(t,n);if(r){const t=B.deserialize(r);u.push(t)}}const c=new n.i9c({userMessage:i,steps:u});a=new n.j97({turn:{case:"agentConversationTurn",value:c}});break}case"shellConversationTurn":{const r=o.turn.value,s=await e.getBlob(t,r.shellCommand);if(!s)continue;const i=b.deserialize(s),u=await e.getBlob(t,r.shellOutput);if(!u)continue;const c=R.deserialize(u),l=new n.tms({shellCommand:i,shellOutput:c});a=new n.j97({turn:{case:"shellConversationTurn",value:l}});break}}a&&i.push(a)}s.turns=i;const a=[];for(const n of r.todos){const r=await e.getBlob(t,n);if(r){const t=S.deserialize(r);a.push(t)}}if(s.todos=a,r.summary){const n=await e.getBlob(t,r.summary);if(n){const t=P.deserialize(n);s.summary=t}}return s}(t,r,this.blobStore)}async getFullConversationWithSubagents(t){const r=this.conversationStateStructure,e=await this.deserializeConversationStateStructure(t,r),n={},s=await(0,c.Vn)(t,r,this.blobStore);for(const[r,e]of Object.entries(s))if(e.conversationState){const s=await this.deserializeConversationStateStructure(t,e.conversationState);n[r]={conversationState:s,createdTimestampMs:e.createdTimestampMs,lastUsedTimestampMs:e.lastUsedTimestampMs,subagentType:e.subagentType}}return{conversationState:e,subagentStates:n}}getLatestCheckpoint(){return this.getConversationStateStructure()}async handleCheckpoint(t,r){const e=this.serde.serialize(r),n=this.fixedRootBlobId??await(0,a.Bk)(e);await this.blobStore.setBlob(t,n,e),this.setMetadata("latestRootBlobId",n),this.conversationStateStructure=r}async resetFromDb(t){await this.tryResetFromDb(t)}async tryResetFromDb(t){try{const r=this.getMetadata("latestRootBlobId");if(!r||0===r.length)return this.conversationStateStructure=new n.Y9z,!1;const e=await this.blobStore.getBlob(t,r);if(!e)return this.conversationStateStructure=new n.Y9z,!1;const s=this.serde.deserialize(e);return this.conversationStateStructure=s,!0}catch(t){return this.conversationStateStructure=new n.Y9z,!1}}async dispose(){this.blobStore instanceof i.j&&await this.blobStore.dispose()}}},"../agent-kv/dist/blob-store.js"(t,r,e){e.d(r,{Bk:()=>o,Fo:()=>i,We:()=>l,ve:()=>c});var n=e("../metrics/dist/index.js"),s=e("../agent-kv/dist/serde.js");function i(t){const r=t.buffer;return r instanceof ArrayBuffer?new Uint8Array(r,t.byteOffset,t.byteLength):new Uint8Array(t)}async function o(t){const r=await crypto.subtle.digest("SHA-256",i(t));return new Uint8Array(r)}const a=(0,n.v5)("agent_kv.in_memory.get_blob.duration_ms",{description:"Duration of InMemoryBlobStore getBlob operations in milliseconds"}),u=(0,n.v5)("agent_kv.in_memory.set_blob.duration_ms",{description:"Duration of InMemoryBlobStore setBlob operations in milliseconds"});class c{constructor(){this.blobs=new Map}getBlob(t,r){const e=performance.now();try{const t=this.blobs.get((0,s.nj)(r));return Promise.resolve(t)}finally{const r=performance.now()-e;a.histogram(t,r)}}setBlob(t,r,e){const n=performance.now();try{return this.blobs.set((0,s.nj)(r),e),Promise.resolve()}finally{const r=performance.now()-n;u.histogram(t,r)}}setBlobLocallyOnly(t,r,e){return this.setBlob(t,r,e)}flush(t){return Promise.resolve()}}class l{constructor(){this.store=new Map}set(t,r){this.store.set(t,r)}subscribe(t,r){return()=>{}}get(t){const r=this.store.get(t);if(void 0===r)throw new Error(`Key ${String(t)} not found in store`);return r}}},"../agent-kv/dist/serde.js"(t,r,e){e.d(r,{aD:()=>c,bO:()=>i,cm:()=>o,nj:()=>u});const n=new TextDecoder,s=new TextEncoder,i=new class{serialize(t){return s.encode(t)}deserialize(t){return n.decode(t)}getBlobType(){return{kind:"string"}}};class o{constructor(t){this.proto=t}serialize(t){return t.toBinary()}deserialize(t){return this.proto.fromBinary(t)}getBlobType(){return{kind:"proto",typeName:this.proto.typeName}}}const a=Array.from({length:256},((t,r)=>r.toString(16).padStart(2,"0")));function u(t){if("undefined"!=typeof Buffer)return Buffer.from(t).toString("hex");let r="";for(let e=0;e=64&&"undefined"!=typeof Buffer){const t=function(t){if(Buffer.byteLength(t,"utf8")===t.length)try{const r=new Uint8Array(t.length/2);if(Buffer.from(r.buffer,r.byteOffset,r.byteLength).write(t,"hex")===r.length)return r}catch{}}(r);if(void 0!==t)return t}const e=new Uint8Array(r.length/2);for(let t=0;tm});var n=e("../context/dist/logger.js"),s=e("../metrics/dist/index.js"),i=e("../proto/dist/generated/agent/v1/agent_pb.js"),o=e("../utils/dist/promise-extras.js"),a=e("../agent-kv/dist/serde.js");const u=(0,n.h)("@anysphere/agent-kv:subagent-states"),c=(0,s.Pu)("agent_kv.subagent_state_ref.missing_blob",{description:"Subagent state refs whose blob was missing, counted per read until a checkpoint rewrites the ref. fallback=inline kept the entry saved beside the ref (usually a transcript-free summary), dropped omitted the subagent, superseded kept a newer in-memory state.",labelNames:["reader","fallback"]});function l(t,r){u.warn(t,"Subagent state ref blob not found; restoring without its transcript",r),c.increment(t,1,{reader:r.reader,fallback:r.fallback})}async function m(t,r,e){const n={...r.subagentStates??{}},s=Object.entries(r.subagentStateRefs??{});if(0===s.length)return n;const u=await(0,o.PH)(s,(async([r,n])=>{const s=await e.getBlob(t,n);if(void 0===s)return{kind:"missing",subagentId:r,blobIdHex:(0,a.nj)(n)};try{return{kind:"loaded",subagentId:r,state:i.aK_.fromBinary(s)}}catch(t){return{kind:"failed",error:t}}}),{max:8}),c=u.find((t=>"failed"===t.kind));if(void 0!==c&&"failed"===c.kind)throw c.error;for(const r of u)if("loaded"===r.kind)n[r.subagentId]=r.state;else if("missing"===r.kind){const e=void 0!==n[r.subagentId];l(t,{reader:"resolve",fallback:e?"inline":"dropped",subagentId:r.subagentId,blobIdHex:r.blobIdHex})}return n}},"../context/dist/core.js"(t,r,e){function n(t,r){return{symbol:t,defaultValue:r}}function s(t){const r=new AbortController;if(t.aborted)return r.abort(t.reason),{signal:r.signal,abort(t){r.abort(t)},unlink(){}};const e=()=>r.abort(t.reason);return t.addEventListener("abort",e,{once:!0}),{signal:r.signal,abort(n){t.removeEventListener("abort",e),r.abort(n)},unlink(){t.removeEventListener("abort",e)}}}e.d(r,{cF:()=>n,q6:()=>o,uk:()=>a});class i{constructor(t,r,e,n){this.parent=t,this.values=e||new Map,this.name=n,this.signal=r||(t?t.signal:(new AbortController).signal)}get canceled(){return this.signal.aborted}get reason(){return this.signal.reason}get(t){return this.values.has(t.symbol)?this.values.get(t.symbol):this.parent?this.parent.get(t):t.defaultValue}with(t,r){const e=new Map(this.values);return e.set(t.symbol,r),new i(this,void 0,e)}withCancel(){const t=s(this.signal);return[new i(this,t.signal),r=>t.abort(r)]}withUnlinkableCancel(){const t=s(this.signal);return[new i(this,t.signal),r=>t.abort(r),()=>t.unlink()]}withTimeout(t){const r=s(this.signal),e=new i(this,r.signal),n=setTimeout((()=>{r.abort(new Error("context deadline exceeded"))}),t);return r.signal.addEventListener("abort",(()=>{clearTimeout(n)}),{once:!0}),e}withDeadline(t){const r=t.getTime()-Date.now();if(r<=0){const t=s(this.signal);return t.abort(new Error("context deadline exceeded")),new i(this,t.signal)}return this.withTimeout(r)}withTimeoutAndCancel(t){const[r,e]=this.withCancel();return[r.withTimeout(t),e]}withName(t){return new i(this,void 0,void 0,t)}withDetached(){return new i(this,(new AbortController).signal)}getParent(){return this.parent}getPath(){const t=[];let r=this;for(;r;)r.name&&t.unshift(r.name),r=r.getParent();return t}}function o(){return new i}function a(t){return new Promise((r=>{t.canceled?r():t.signal.addEventListener("abort",(()=>r()),{once:!0})}))}},"../context/dist/logger.js"(t,r,e){e.d(r,{_O:()=>m,h:()=>f});var n=e("../context/dist/core.js");function s(t){return"object"==typeof t&&null!==t&&"getPath"in t&&"function"==typeof t.getPath}function i(t){return"object"==typeof t&&null!==t&&("message"in t||"stack"in t||"name"in t||"cause"in t)}function o(t,r,e,n,s,c){const l=function(t,r,e,n){if(!r.inlineSerializer)return t;try{const s=r.inlineSerializer(t,{path:e,depth:n});return void 0===s?t:s}catch{return t}}(t,r,c,n);if(function(t){return"object"==typeof t&&null!==t&&"kind"in t&&"summary"===t.kind&&"summary"in t&&"string"==typeof t.summary}(l))return e.dim(`<${l.summary}>`);if(null===(t=l))return e.gray("null");if(void 0===t)return e.gray("undefined");if("string"==typeof t){const n=function(t,r){return t.length<=r?t:`${t.slice(0,r)}...`}(t,r.maxStringLength);return e.green(JSON.stringify(n))}if("number"==typeof t)return e.yellow(String(t));if("boolean"==typeof t)return e.magenta(String(t));if("bigint"==typeof t)return e.yellow(`${t}n`);if("symbol"==typeof t)return e.cyan(t.toString());if("function"==typeof t){const r=t.name?` ${t.name}`:"";return e.dim(`[Function${r}]`)}if(t instanceof Date){const r=Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();return e.green(r)}if(t instanceof RegExp)return e.cyan(t.toString());if(i(t))return a(t,r,e,n,s,c);if(Array.isArray(t))return u(t,r,e,n,s,c);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer)return e.dim(`ArrayBuffer(${t.byteLength})`);if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)){const r=t,n=r.constructor?.name??"TypedArray";return e.dim(`${n}(${r.byteLength})`)}return t instanceof Map?function(t,r,e,n,s,i){if(n>=r.maxDepth)return e.dim(`Map(${t.size})`);if(s.has(t))return e.dim("[Circular]");s.add(t);const a=Array.from(t.entries()),u=Math.min(a.length,r.maxEntries),c=a.slice(0,u).map((([t,a])=>{const u=o(t,r,e,n+1,s,i.concat("")),c=o(a,r,e,n+1,s,i.concat(String(t)));return`${u} ${e.dim("=>")} ${c}`}));a.length>u&&c.push(e.dim(`... ${a.length-u} more`));const l=e.dim(", "),m=`${e.dim("Map{")}${c.join(l)}${e.dim("}")}`;return s.delete(t),m}(t,r,e,n,s,c):t instanceof Set?u(Array.from(t.values()),r,e,n,s,c):"object"==typeof t?function(t,r,e,n,s,i){if(n>=r.maxDepth){const r=t?.constructor?.name??"Object";return e.dim(`[${r}]`)}if(s.has(t))return e.dim("[Circular]");s.add(t);const a=Object.entries(t);if(0===a.length){const r=e.dim("{}");return s.delete(t),r}const u=Math.min(a.length,r.maxEntries),c=a.slice(0,u).map((([t,a])=>{const u=o(a,r,e,n+1,s,i.concat(t));return`${e.cyan(t)}: ${u}`}));a.length>u&&c.push(e.dim(`... ${a.length-u} more`));const l=e.dim(", "),m=`${e.dim("{")}${c.join(l)}${e.dim("}")}`;return s.delete(t),m}(t,r,e,n,s,c):e.dim(`[${typeof t}]`)}function a(t,r,e,n,s,i){if(s.has(t))return e.dim("[Circular]");s.add(t);const a="string"==typeof t.name?t.name:"Error",u="string"==typeof t.message?t.message:"",c=u?`${a}: ${u}`:a;let l=e.red(c);if("cause"in t&&void 0!==t.cause){const a=o(t.cause,r,e,n+1,s,i.concat("cause"));l=`${l} ${e.dim("cause=")}${a}`}return s.delete(t),l}function u(t,r,e,n,s,i){if(n>=r.maxDepth)return e.dim(`[Array(${t.length})]`);if(s.has(t))return e.dim("[Circular]");if(s.add(t),0===t.length){const r=e.dim("[]");return s.delete(t),r}const a=Math.min(t.length,r.maxArrayLength),u=t.slice(0,a).map(((t,a)=>o(t,r,e,n+1,s,i.concat(a))));t.length>a&&u.push(e.dim(`... ${t.length-a} more`));const c=e.dim(", "),l=`${e.dim("[")}${u.join(c)}${e.dim("]")}`;return s.delete(t),l}let c=function(t={}){const r=function(t){return{indent:" ".repeat(t.indent??2),maxDepth:t.maxDepth??6,maxEntries:t.maxEntries??50,maxArrayLength:t.maxArrayLength??40,maxStringLength:t.maxStringLength??200,includeTimestamp:t.includeTimestamp??!0,timestampFormat:t.timestampFormat??"time",includeContextPath:t.includeContextPath??!0,inlineSerializer:t.inlineSerializer}}(t),e=function(t){const r=r=>e=>t?`[${r.join(";")}m${e}`:e,e=r([2]),n=r([90]),s=r([31]),i=r([32]),o=r([33]),a=r([34]),u=r([35]),c=r([36]),l=r([1]),m=r([1,31]);return{dim:e,gray:n,red:s,green:i,yellow:o,blue:a,magenta:u,cyan:c,bold:l,level:(t,r)=>{switch(t){case"debug":return u(r);case"info":return a(r);case"warn":return o(r);case"error":return m(r);default:return t}}}}(function(t){if("boolean"==typeof t)return t;if("undefined"==typeof process)return!1;const r=process.env??{};if("NO_COLOR"in r)return!1;if("dumb"===r.TERM)return!1;const e=r.FORCE_COLOR;return"1"===e||"true"===e||"0"!==e&&(process.stdout?.isTTY??!1)}(t.useColors)),n=t.console??console;return{log:(t,u)=>{const c=[];r.includeTimestamp&&c.push(e.dim(function(t,r){const e=t.toISOString();return"date-time"===r?e:e.slice(11,23)}(u.timestamp,r.timestampFormat)));const l=u.level.toUpperCase().padEnd(5);c.push(e.level(u.level,l));const m="error"===u.level?e.bold(u.message):u.message;if(c.push(m),r.includeContextPath&&s(u.context)){const t=u.context.getPath();t.length>0&&c.push(e.dim(`ctx=${t.join("/")}`))}const f=new WeakSet;if(!s(u.context)&&u.context&&Object.keys(u.context).length>0){const t=o(u.context,r,e,0,f,["context"]);c.push(`${e.dim("context=")}${t}`)}if(u.metadata&&Object.keys(u.metadata).length>0){const t=o(u.metadata,r,e,0,f,["metadata"]);c.push(`${e.dim("meta=")}${t}`)}const d=[c.join(" ")];if(void 0!==u.error){const t=i(u.error)?a(u.error,r,e,0,f,["error"]):o(u.error,r,e,0,f,["error"]);if(d[0]=`${d[0]} ${e.dim("error=")}${t}`,i(u.error)&&"string"==typeof u.error.stack){const t=u.error.stack.split("\n").slice(1);for(const n of t){const t=n.trim();t&&d.push(`${r.indent}${e.dim(t)}`)}}}const p=d.join("\n");switch(u.level){case"debug":case"info":n.log(p);break;case"warn":n.warn(p);break;case"error":n.error(p);break;default:{const t=u.level;throw new Error(`Unhandled log level: ${String(t)}`)}}}}}();const l={log:(t,r)=>c.log(t,r)},m=(0,n.cF)(Symbol("loggerBackend"),l);function f(t){function r(r,e){const n=new Date,s=function(t){return t.get(m)}(r);s.log(r,{...e,timestamp:n,logger:t})}return{debug:(t,e,n)=>{r(t,{level:"debug",message:e,context:t,metadata:n})},info:(t,e,n)=>{r(t,{level:"info",message:e,context:t,metadata:n})},warn:(t,e,n)=>{r(t,{level:"warn",message:e,context:t,metadata:n})},error:(t,e,n,s)=>{r(t,{level:"error",message:e,context:t,error:n,metadata:s})}}}},"../cursor-sdk-local-runtime/dist/run-store/id.js"(t,r,e){e.d(r,{M2:()=>i,WQ:()=>s,nq:()=>o});var n=e("../utils/dist/fresh-uuid.js");function s(){return`agent-${(0,n.C)()}`}function i(){return`bc-${(0,n.C)()}`}function o(){return`run-${(0,n.C)()}`}},"../cursor-sdk-local-runtime/dist/run-store/in-memory-run-event-notifier.js"(t,r,e){e.d(r,{U:()=>n,y:()=>s});class n{constructor(){this.subscribersByRun=new Map}async publishRunEventAppended(t){const r=this.subscribersByRun.get(t.runId);if(r)for(const e of r){if(e.closed)continue;const r=e.waiters.shift();r?r({value:t,done:!1}):e.queue.push(t)}}subscribeRunEvents(t){const r={closed:!1,queue:[],waiters:[]},e=this.subscribersByRun.get(t.runId)??new Set;e.add(r),this.subscribersByRun.set(t.runId,e);const n=t.signal,s=()=>{if(n?.removeEventListener("abort",s),!r.closed)for(r.closed=!0,e.delete(r),0===e.size&&this.subscribersByRun.delete(t.runId);r.waiters.length>0;)r.waiters.shift()?.({value:void 0,done:!0})};return n?.aborted?s():n?.addEventListener("abort",s,{once:!0}),{[Symbol.asyncIterator]:()=>({next:async()=>{const t=r.queue.shift();return t?{value:t,done:!1}:r.closed||n?.aborted?(s(),{value:void 0,done:!0}):new Promise((t=>{r.waiters.push(t)}))},return:async()=>(s(),{value:void 0,done:!0})})}}}function s(){return new n}},"../cursor-sdk-local-runtime/dist/run-store/index.js"(t,r,e){e.d(r,{U1:()=>s.U,tY:()=>u,w:()=>c,M2:()=>n.M2,WQ:()=>n.WQ});var n=e("../cursor-sdk-local-runtime/dist/run-store/id.js");e("../cursor-sdk-local-runtime/dist/run-store/status.js");var s=e("../cursor-sdk-local-runtime/dist/run-store/in-memory-run-event-notifier.js"),i=e("node:fs"),o=e("node:net"),a=e("node:path");class u{constructor(t){this.socketPath=t.socketPath,this.connectTimeoutMs=t.connectTimeoutMs??1e3,this.requestTimeoutMs=t.requestTimeoutMs??5e3}async publishRunEventAppended(t){const r=await d({socketPath:this.socketPath,timeoutMs:this.connectTimeoutMs});try{f(r,{type:"publish",hint:t});const e=await async function(t,r){const e=new AbortController,n=setTimeout((()=>e.abort()),r);try{for await(const r of p(t,e.signal))return r}catch(t){if(e.signal.aborted)throw new Error("Timed out waiting for notifier response");throw t}finally{clearTimeout(n)}throw new Error("Notifier closed before sending a response")}(r,this.requestTimeoutMs);if("error"===e.type)throw new Error(e.message);if("ack"!==e.type)throw new Error(`Unexpected notifier response ${e.type}`)}finally{r.destroy()}}subscribeRunEvents(t){const r=function(){let t,r;return{promise:new Promise(((e,n)=>{t=e,r=n})),resolve:t,reject:r}}(),e=this.createSubscription(t,r);return{ready:r.promise,[Symbol.asyncIterator]:()=>e[Symbol.asyncIterator]()}}async*createSubscription(t,r){let e;try{e=await d({socketPath:this.socketPath,timeoutMs:this.connectTimeoutMs,signal:t.signal});const n=p(e,t.signal)[Symbol.asyncIterator]();try{f(e,{type:"subscribe",runId:t.runId});const s=await n.next();if(s.done)throw new Error("Notifier closed before confirming subscription");if("error"===s.value.type)throw new Error(s.value.message);if("ack"!==s.value.type)throw new Error(`Unexpected notifier response ${s.value.type}`);r.resolve();for await(const t of{[Symbol.asyncIterator]:()=>n})if("hint"===t.type&&(yield t.hint),"error"===t.type)throw new Error(t.message)}catch(t){throw r.reject(t),t}finally{await(n.return?.())}}catch(t){throw r.reject(t),t}finally{e?.destroy()}}}class c{static async listen(t){const r=new c(t);return await r.listen(),r}constructor(t){this.options=t,this.subscribersByRun=new Map,this.runBySubscriber=new Map,this.sockets=new Set,this.server=(0,o.createServer)((t=>this.handleSocket(t)))}async listen(){var t;m(t=this.options.socketPath)||((0,i.mkdirSync)((0,a.dirname)(t),{recursive:!0}),l(t)),await new Promise(((t,r)=>{const e=t=>{s(),r(t)},n=()=>{s(),t()},s=()=>{this.server.off("error",e),this.server.off("listening",n)};this.server.once("error",e),this.server.once("listening",n),this.server.listen(this.options.socketPath)}))}async close(){for(const t of this.sockets)t.destroy();this.sockets.clear(),this.subscribersByRun.clear(),this.runBySubscriber.clear(),await new Promise(((t,r)=>{this.server.close((e=>{e?r(e):t()}))})).catch((t=>{if("ERR_SERVER_NOT_RUNNING"!==("object"==typeof t&&null!==t&&"code"in t?t.code:void 0))throw t})),l(this.options.socketPath)}handleSocket(t){this.sockets.add(t);let r="";t.on("data",(e=>{for(r+=e.toString("utf8");;){const e=r.indexOf("\n");if(-1===e)return;const n=r.slice(0,e);r=r.slice(e+1),this.handleLine(t,n)}})),t.on("close",(()=>this.cleanupSocket(t))),t.on("error",(()=>this.cleanupSocket(t)))}handleLine(t,r){const e=function(t){const r=g(t);if(r)return"subscribe"===r.type&&"string"==typeof r.runId?{type:"subscribe",runId:r.runId}:"publish"===r.type&&_(r.hint)?{type:"publish",hint:r.hint}:void 0}(r);return e?"subscribe"===e.type?(this.subscribe(t,e.runId),void f(t,{type:"ack"})):(this.publish(e.hint),f(t,{type:"ack"}),void t.end()):(f(t,{type:"error",message:"Invalid notifier message"}),void t.end())}subscribe(t,r){this.unsubscribe(t);const e=this.subscribersByRun.get(r)??new Set;e.add(t),this.subscribersByRun.set(r,e),this.runBySubscriber.set(t,r)}publish(t){const r=this.subscribersByRun.get(t.runId);if(r)for(const e of r)e.destroyed||f(e,{type:"hint",hint:t})}cleanupSocket(t){this.unsubscribe(t),this.sockets.delete(t)}unsubscribe(t){const r=this.runBySubscriber.get(t);if(!r)return;const e=this.subscribersByRun.get(r);e?.delete(t),0===e?.size&&this.subscribersByRun.delete(r),this.runBySubscriber.delete(t)}}function l(t){m(t)||(0,i.existsSync)(t)&&(0,i.unlinkSync)(t)}function m(t){return t.startsWith("\\\\.\\pipe\\")}function f(t,r){t.write(`${JSON.stringify(r)}\n`)}async function d(t){if(t.signal?.aborted)throw J(t.signal);return new Promise(((r,e)=>{const n=(0,o.createConnection)(t.socketPath),s=setTimeout((()=>{c(),n.destroy(),e(new Error(`Timed out connecting to ${t.socketPath}`))}),t.timeoutMs),i=()=>{c(),r(n)},a=t=>{c(),e(t)},u=()=>{c(),n.destroy(),e(J(t.signal))},c=()=>{clearTimeout(s),n.off("connect",i),n.off("error",a),t.signal?.removeEventListener("abort",u)};n.once("connect",i),n.once("error",a),t.signal?.addEventListener("abort",u,{once:!0})}))}async function*p(t,r){let e="";const n=[];let s,i,o=!1;const a=()=>{s?.(),s=void 0},u=r=>{for(e+=r.toString("utf8");;){const r=e.indexOf("\n");if(-1===r)break;const s=e.slice(0,r);e=e.slice(r+1);const a=h(s);if(!a){i=new Error("Invalid notifier server message"),o=!0,t.destroy();break}n.push(a)}a()},c=()=>{o=!0,a()},l=t=>{i=t,o=!0,a()},m=()=>{i=J(r),o=!0,t.destroy(),a()};t.on("data",u),t.on("close",c),t.on("error",l),r?.addEventListener("abort",m,{once:!0});try{for(;;){const t=n.shift();if(t)yield t;else{if(i)throw i;if(o)return;await new Promise((t=>{s=t}))}}}finally{t.off("data",u),t.off("close",c),t.off("error",l),r?.removeEventListener("abort",m)}}function h(t){const r=g(t);if(r)return"ack"===r.type?{type:"ack"}:"error"===r.type&&"string"==typeof r.message?{type:"error",message:r.message}:"hint"===r.type&&_(r.hint)?{type:"hint",hint:r.hint}:void 0}function g(t){try{const r=JSON.parse(t);if("object"!=typeof r||null===r||Array.isArray(r))return;const e={};for(const[t,n]of Object.entries(r))e[t]=n;return e}catch{return}}function _(t){return Boolean(t&&"object"==typeof t&&"string"==typeof t.runId&&"string"==typeof t.offset)}function J(t){const r=t?.reason;return r instanceof Error?r:new Error("Run event notifier aborted")}},"../cursor-sdk-local-runtime/dist/run-store/sqlite-blob-store.js"(t,r,e){e.d(r,{B_:()=>h,SQLiteBlobStoreWithMetadata:()=>g,hI:()=>p,rZ:()=>f});var n=e("node:fs"),s=e("node:path"),i=e("../agent-kv/dist/agent-store.js"),o=e("../agent-kv/dist/serde.js"),a=e("../utils/dist/disposable.js"),u=e("../cursor-sdk-local-runtime/dist/utils/logger.js"),c=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"),l=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js");const m=new i.aY,f="Local agent storage could not open its database, so this run is continuing in memory. Its checkpoint may be unavailable after the process exits.",d="unable to open database file";function p(t){const r=new Set;let e=t;for(;null!=e&&!r.has(e);){if(r.add(e),"object"!=typeof e)return"string"==typeof e&&e.toLowerCase().includes(d);const t=e;if("SQLITE_CANTOPEN"===t.code)return!0;if("ERR_SQLITE_ERROR"===t.code&&"number"==typeof t.errcode&&14==(255&t.errcode))return!0;if("string"==typeof t.message&&t.message.toLowerCase().includes(d))return!0;e=t.cause}return!1}function h(t,r){const e=t;return"function"!=typeof e.onLocalStoreDegraded?()=>{}:e.onLocalStoreDegraded(r)}class g extends a.j{static async initAndLoad(t){const r=new g(t);return await r.getDriver(),r}constructor(t,r){super(),this.dbPath=t,this.openDisabled=!1,this.memoryBlobs=new Map,this.deletedBlobIds=new Set,this.degradationListeners=new Set,this.listeners={agentId:new Set,latestRootBlobId:new Set,name:new Set,createdAt:new Set,mode:new Set,isRunEverything:new Set,approvalMode:new Set,lastUsedModel:new Set,lastDebugServerPort:new Set,currentPlanUri:new Set,subagentInfo:new Set},this.persistScheduled=!1,this.metadataUnpersisted=!1,this.isDisposing=!1,this.openDriver=r?.openDriver??c.d;const e=(0,s.basename)((0,s.dirname)(this.dbPath));this.metadata=(0,i.sh)(e)}onLocalStoreDegraded(t){return this.degradationListeners.add(t),void 0!==this.degradationWarning&&this.notifyDegradationListener(t,this.degradationWarning),()=>{this.degradationListeners.delete(t)}}async getDriver(){if(!this.openDisabled){if(this.driver)return this.driver;if(!this.driverPromise){const t=(async()=>{const t=(0,s.dirname)(this.dbPath);(0,n.existsSync)(t)||(0,n.mkdirSync)(t,{recursive:!0});const r=await this.openDriver(this.dbPath);try{this.initializeDriver(r)}catch(t){throw r.close(),t}return this.driver=r,r})().catch((r=>{throw this.driverPromise===t&&(this.driverPromise=void 0),r}));this.driverPromise=t}try{return await this.driverPromise}catch(t){if(p(t))return this.openDisabled=!0,void this.degrade(t);throw t}}}degrade(t){if(void 0===this.degradationWarning){this.degradationWarning=f,u.Jz.warn(f,t instanceof Error?t.message:String(t));for(const t of this.degradationListeners)this.notifyDegradationListener(t,this.degradationWarning)}}notifyDegradationListener(t,r){try{t(r)}catch{}}rememberBlob(t,r){this.memoryBlobs.set(t,Uint8Array.from(r))}readRememberedBlob(t){const r=this.memoryBlobs.get(t);return void 0===r?void 0:Uint8Array.from(r)}async withDriver(t,r){try{const e=await this.getDriver();return e?r(e):t()}catch(r){if(!p(r))throw r;return this.degrade(r),t()}}initializeDriver(t){t.exec("PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 5000;\n PRAGMA user_version = 1;\n CREATE TABLE IF NOT EXISTS blobs (id TEXT PRIMARY KEY, data BLOB);\n CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);");const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);if(r?.value)this.metadata=m.deserialize((0,o.aD)(r.value)),this.storedMetadataHex=r.value;else{const r=(0,o.nj)(m.serialize(this.metadata));t.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",r]),this.storedMetadataHex=r}this.metadataUnpersisted=!1}async getBlob(t,r){if(this.isDisposing)return;const e=(0,o.nj)(r);if(this.deletedBlobIds.has(e))return;const n=this.readRememberedBlob(e);return void 0!==n?n:this.withDriver((()=>{}),(t=>{const r=t.get("SELECT data FROM blobs WHERE id = ?",[e]);return null==r?.data?void 0:new Uint8Array(r.data)}))}async listBlobIds(){if(this.isDisposing)return[];const t=new Set(this.memoryBlobs.keys()),r=await this.withDriver((()=>[]),(t=>t.all("SELECT id FROM blobs ORDER BY id ASC").map((t=>t.id))));for(const e of r)t.add(e);return[...t].filter((t=>!this.deletedBlobIds.has(t))).sort()}async deleteBlob(t){this.isDisposing||(this.memoryBlobs.delete(t),await this.withDriver((()=>{this.deletedBlobIds.add(t)}),(r=>{r.run("DELETE FROM blobs WHERE id = ?",[t]),this.deletedBlobIds.delete(t)})))}async setBlob(t,r,e){if(this.isDisposing)return;const n=(0,o.nj)(r);await this.withDriver((()=>{this.deletedBlobIds.delete(n),this.rememberBlob(n,e)}),(t=>{t.run("INSERT OR REPLACE INTO blobs (id, data) VALUES (?, ?)",[n,Buffer.from(e)]),this.memoryBlobs.delete(n),this.deletedBlobIds.delete(n)}))}async setBlobLocallyOnly(t,r,e){return Promise.resolve()}async compareAndSetRoot({expected:t,next:r,blobs:e=[],metadata:n={}}){if(this.isDisposing)return!1;const s=await this.withDriver((()=>{}),(s=>(0,l.R)(s,(()=>{const i=s.get("SELECT value FROM meta WHERE key = ?",["0"]),a=i?.value?m.deserialize((0,o.aD)(i.value)):this.metadata;if((0,o.nj)(a.latestRootBlobId)!==(0,o.nj)(t))return;const u=[];for(const[t,r]of e)s.run("INSERT OR IGNORE INTO blobs (id, data) VALUES (?, ?)",[t,Buffer.from(r)]),u.push(t);const c={...a,...n,latestRootBlobId:r},l=(0,o.nj)(m.serialize(c));return s.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",l]),{updated:c,hex:l,ids:u}}))));if(void 0===s)return!1;for(const t of s.ids)this.deletedBlobIds.delete(t);return this.metadata=s.updated,this.storedMetadataHex=s.hex,this.metadataUnpersisted=!1,!0}async flush(t){return Promise.resolve()}get(t){return this.metadata[t]}reloadMetadata(){const t=this.driver;if(void 0===t||this.isDisposing||this.metadataUnpersisted)return;const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);r?.value&&r.value!==this.storedMetadataHex&&(this.metadata=m.deserialize((0,o.aD)(r.value)),this.storedMetadataHex=r.value)}valuesEqual(t,r,e){if("latestRootBlobId"===t){if(!(r instanceof Uint8Array&&e instanceof Uint8Array))return r===e;const t=r,n=e;if(t===n)return!0;if(!t||!n)return!1;if(t.length!==n.length)return!1;for(let r=0;r{this.persistScheduled=!1,!this.isDisposing&&this.driver&&this.persistMetadata()}))))}set(t,r){const e=this.metadata[t];if(this.valuesEqual(t,e,r))return;this.metadata={...this.metadata,[t]:r},this.metadataUnpersisted=!0,this.driver&&this.schedulePersist();const n=this.listeners[t];n&&n.size>0&&queueMicrotask((()=>{n.forEach((t=>{t()}))}))}persistMetadata(){const t=this.driver;if(!t)return;const r=(0,o.nj)(m.serialize(this.metadata));try{t.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",r]),this.storedMetadataHex=r,this.metadataUnpersisted=!1}catch(t){if(!p(t))throw t;this.degrade(t)}}subscribe(t,r){const e=this.listeners[t];return e?(e.add(r),()=>e.delete(r)):()=>{}}async dispose(){return this.disposePromise?this.disposePromise:this.driverPromise?(this.disposePromise=this.cleanup().then((()=>{this.driverPromise=void 0,this.driver=void 0})),this.disposePromise):void 0}async cleanup(){if(!this.driverPromise)return;const t=await this.driverPromise.catch((()=>{}));if(!t)return this.driverPromise=void 0,void(this.driver=void 0);this.persistScheduled=!1,this.metadataUnpersisted&&this.persistMetadata(),this.isDisposing=!0;const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);let e=0;if(r?.value){const t=(0,o.aD)(r.value);e=m.deserialize(t).latestRootBlobId.length}const i=t.get("SELECT COUNT(*) AS count FROM blobs"),a=i?.count??0;if(t.close(),0===e&&0===a){this.driverPromise=void 0,this.driver=void 0;const t=(0,s.dirname)(this.dbPath);try{(0,n.rmSync)(t,{recursive:!0,force:!0})}catch{}}}}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"(t,r,e){e.d(r,{d:()=>i});var n=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js"),s=e("node:path");async function i(t){const r=function(t,r=process.platform){if("win32"!==r)return t;const e=s.win32.resolve(t);return t.length+8>259||e.length+8>259?s.win32.toNamespacedPath(e):t}(t);if("Bun"in globalThis)return(await e.e(914).then(e.bind(e,"../cursor-sdk-local-runtime/dist/run-store/sqlite/bun-sqlite-driver.js"))).openBunSqliteDriver(r);let i;try{i=await e.e(343).then(e.bind(e,"../cursor-sdk-local-runtime/dist/run-store/sqlite/node-sqlite-driver.js"))}catch(t){if(function(t){return"ERR_UNKNOWN_BUILTIN_MODULE"===("object"==typeof t&&null!==t&&"code"in t&&"string"==typeof t.code?t.code:void 0)||(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("node:sqlite")}(t))throw new n.Y("node:sqlite is not available in this runtime. The default local agent store requires Node >= 22.13 (or another runtime that implements node:sqlite). Configure a JsonlLocalAgentStore instead.",{cause:t});throw t}return i.openNodeSqliteDriver(r)}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js"(t,r,e){e.d(r,{R:()=>s,Y:()=>n});class n extends Error{constructor(t,r){super(t,r),this.name="NoSqliteDriverError"}}function s(t,r){t.exec("BEGIN IMMEDIATE");try{const e=r();return t.exec("COMMIT"),e}catch(r){try{t.exec("ROLLBACK")}catch{}throw r}}},"../cursor-sdk-local-runtime/dist/run-store/status.js"(t,r,e){e.d(r,{Qb:()=>s});const n=new Set(["FINISHED","ERROR","CANCELLED","EXPIRED"]);function s(t){return n.has(t)}},"../cursor-sdk-local-runtime/dist/utils/logger.js"(t,r,e){e.d(r,{Jz:()=>u,ni:()=>o});var n=e("node:async_hooks");let s={warn:console.warn.bind(console),error:console.error.bind(console)};const i=new n.AsyncLocalStorage;function o(t,r){return i.run(t,r)}function a(){return i.getStore()??s}const u={warn(...t){a().warn(...t)},error(...t){a().error(...t)}}},"../cursor-sdk-shared/dist/message-schemas.js"(t,r,e){e.d(r,{JY:()=>s,K8:()=>l,Kx:()=>i,RB:()=>a,d0:()=>u,lK:()=>o,mj:()=>c});var n=e("zod/v3");const s=n.strictObject({type:n.literal("base64"),data:n.string()}),i=n.strictObject({type:n.literal("user_message"),session_id:n.string(),text:n.string(),images:n.array(s).optional()}),o=n.strictObject({type:n.literal("assistant_message"),session_id:n.string(),text:n.string()}),a=n.union([i,o]);function u(t){return i.safeParse(t).success}function c(t){return o.safeParse(t).success}function l(t){return a.safeParse(t).success}},"../cursor-sdk-shared/dist/tool-call-types.js"(t,r,e){e.d(r,{C6:()=>vt});var n=e("zod/v3");const s=n.object({message:n.string()});function i(t,r=s){return n.discriminatedUnion("status",[n.object({status:n.literal("success"),value:t}),n.object({status:n.literal("error"),error:r})])}const o=n.object({command:n.string(),workingDirectory:n.string().optional(),timeout:n.number().optional()}),a=i(n.object({exitCode:n.number(),signal:n.string(),stdout:n.string(),stderr:n.string(),executionTime:n.number()})),u=n.object({type:n.literal("shell"),args:o,result:a.optional()}),c=n.object({path:n.string(),fileText:n.string(),returnFileContentAfterWrite:n.boolean().optional()}),l=i(n.object({path:n.string(),linesCreated:n.number(),fileSize:n.number(),fileContentAfterWrite:n.string().optional()})),m=n.object({type:n.literal("write"),args:c,result:l.optional()}),f=n.object({path:n.string()}),d=i(n.object({fileSize:n.number()})),p=n.object({type:n.literal("delete"),args:f,result:d.optional()}),h=n.object({targetDirectory:n.string().optional(),globPattern:n.string()}),g=i(n.object({files:n.array(n.string()),totalFiles:n.number(),clientTruncated:n.boolean(),ripgrepTruncated:n.boolean()})),_=n.object({type:n.literal("glob"),args:h,result:g.optional()}),J=n.object({pattern:n.string(),path:n.string().optional(),glob:n.string().optional(),outputMode:n.string().optional(),contextBefore:n.number().optional(),contextAfter:n.number().optional(),context:n.number().optional(),caseInsensitive:n.boolean().optional(),type:n.string().optional(),headLimit:n.number().optional(),offset:n.number().optional(),multiline:n.boolean().optional(),sort:n.string().optional(),sortAscending:n.boolean().optional()}),w=n.object({file:n.string(),lineNumber:n.number().optional(),line:n.string(),beforeContext:n.array(n.string()).optional(),afterContext:n.array(n.string()).optional()}),y=n.object({file:n.string(),count:n.number()}),S=n.object({matches:n.array(w),totalMatches:n.number()}),q=n.object({files:n.array(n.string()),count:n.number()}),B=n.object({counts:n.array(y),total:n.number()}),I=n.discriminatedUnion("type",[n.object({type:n.literal("content"),output:S}),n.object({type:n.literal("files"),output:q}),n.object({type:n.literal("count"),output:B})]),P=i(n.object({workspaceResults:n.record(n.string(),I).optional(),activeEditorResult:I.optional()})),b=n.object({type:n.literal("grep"),args:J,result:P.optional()}),R=n.object({path:n.string()}),v=i(n.object({content:n.string(),totalLines:n.number(),fileSize:n.number()})),x=n.object({type:n.literal("read"),args:R,result:v.optional()}),k=(n.object({oldText:n.string(),newText:n.string()}),n.object({oldText:n.string(),newText:n.string(),replaceAll:n.boolean().optional()})),E=(n.object({edits:n.array(k)}),n.object({patchContent:n.string()}),n.object({}),n.object({path:n.string()})),C=i(n.object({linesAdded:n.number().optional(),linesRemoved:n.number().optional(),diffString:n.string().optional()})),T=n.object({type:n.literal("edit"),args:E,result:C.optional()}),U=n.object({path:n.string(),ignore:n.array(n.string()).optional()}),A=n.object({name:n.string()}),$=n.lazy((()=>n.object({absPath:n.string(),childrenDirs:n.array($),childrenFiles:n.array(A),childrenWereProcessed:n.boolean(),fullSubtreeExtensionCounts:n.record(n.string(),n.number()),numFiles:n.number()}))),M=i(n.object({directoryTreeRoot:$})),O=n.object({type:n.literal("ls"),args:U,result:M.optional()}),D=n.enum(["error","warning","information","hint"]),N=n.object({line:n.number().optional(),character:n.number().optional()}),G=n.object({start:N.optional(),end:N.optional()}),L=n.object({severity:D,range:G.optional(),message:n.string(),source:n.string(),code:n.string()}),F=n.object({path:n.string(),diagnostics:n.array(L),diagnosticsCount:n.number()}),K=n.object({paths:n.array(n.string())}),z=i(n.object({fileDiagnostics:n.array(F),totalFiles:n.number(),totalDiagnostics:n.number()})),j=n.object({type:n.literal("readLints"),args:K,result:z.optional()}),H=n.object({args:n.record(n.string(),n.unknown()).optional(),providerIdentifier:n.string().optional(),toolName:n.string().optional()}),W=n.object({text:n.object({text:n.string()}).optional(),image:n.object({data:n.string(),mimeType:n.string().optional()}).optional()}),Q=i(n.object({content:n.array(W),isError:n.boolean()})),V=n.object({type:n.literal("mcp"),args:H,result:Q.optional()}),X=n.object({query:n.string(),targetDirectories:n.array(n.string()).optional(),explanation:n.string().optional()}),Y=i(n.object({results:n.string()})),Z=n.object({type:n.literal("semSearch"),args:X,result:Y.optional()}),tt=n.object({description:n.string(),filePath:n.string().optional()}),rt=i(n.object({filePath:n.string(),imageData:n.string()}),n.object({error:n.string()})),et=n.object({type:n.literal("generateImage"),args:tt,result:rt.optional()}),nt=n.object({plan:n.string()}),st=i(n.object({})),it=n.object({type:n.literal("createPlan"),args:nt,result:st.optional()}),ot=n.object({mode:n.enum(["START_RECORDING","SAVE_RECORDING","DISCARD_RECORDING"])}),at=i(n.object({wasPriorRecordingCancelled:n.boolean().optional(),path:n.string().optional(),recordingDurationMs:n.number().optional()})),ut=n.object({type:n.literal("recordScreen"),args:ot,result:at.optional()}),ct=n.object({x:n.number(),y:n.number()}),lt=n.enum(["unspecified","left","right","middle","back","forward"]),mt=n.enum(["unspecified","up","down","left","right"]),ft=n.enum(["unspecified","tap","down","up"]),dt=n.discriminatedUnion("type",[n.object({type:n.literal("mouseMove"),coordinate:ct.optional()}),n.object({type:n.literal("click"),coordinate:ct.optional(),button:lt,count:n.number(),modifierKeys:n.string().optional()}),n.object({type:n.literal("mouseDown"),button:lt}),n.object({type:n.literal("mouseUp"),button:lt}),n.object({type:n.literal("drag"),path:n.array(ct),button:lt,modifierKeys:n.string().optional()}),n.object({type:n.literal("scroll"),coordinate:ct.optional(),direction:mt,amount:n.number(),modifierKeys:n.string().optional()}),n.object({type:n.literal("type"),text:n.string()}),n.object({type:n.literal("key"),key:n.string(),holdDurationMs:n.number().optional(),stroke:ft}),n.object({type:n.literal("wait"),durationMs:n.number()}),n.object({type:n.literal("screenshot")}),n.object({type:n.literal("cursorPosition")})]),pt=n.object({actions:n.array(dt),description:n.string().optional()}),ht=i(n.object({actionCount:n.number(),durationMs:n.number(),settleMs:n.number().optional(),screenshotPath:n.string().optional(),cursorPosition:ct.optional(),log:n.string().optional()}),n.object({message:n.string(),actionCount:n.number(),durationMs:n.number(),screenshotPath:n.string().optional(),log:n.string().optional()})),gt=n.object({type:n.literal("computerUse"),args:pt,result:ht.optional()}),_t=n.enum(["pending","inProgress","completed","cancelled"]),Jt=n.object({content:n.string(),status:_t}),wt=n.object({todos:n.array(Jt)}),yt=i(n.object({todos:n.array(Jt),totalCount:n.number()})),St=n.object({type:n.literal("updateTodos"),args:wt,result:yt.optional()}),qt=n.object({kind:n.string(),name:n.string().optional()}),Bt=n.enum(["unspecified","agent","plan"]),It=n.object({description:n.string(),prompt:n.string(),subagentType:qt.optional(),model:n.string().optional(),resume:n.string().optional(),agentId:n.string().optional(),attachments:n.array(n.string()).optional(),mode:Bt.optional(),respondingToMessageIds:n.array(n.string()).optional()}),Pt=n.enum(["unspecified","agentRequest","userRequest","queuedFollowUp"]),bt=i(n.object({conversationSteps:n.array(n.unknown()).optional(),agentId:n.string().optional(),isBackground:n.boolean(),durationMs:n.number().optional(),resultSuffix:n.string().optional(),backgroundReason:Pt,transcriptPath:n.string().optional()})),Rt=n.object({type:n.literal("task"),args:It,result:bt.optional()}),vt=n.discriminatedUnion("type",[u,m,p,_,b,x,T,O,j,V,et,ut,gt,Z,it,St,Rt])},"../metrics/dist/index.js"(t,r,e){e.d(r,{Pu:()=>o,v5:()=>u,wt:()=>a});const n=(0,e("../context/dist/core.js").cF)(Symbol("metricsBackend"),{record:()=>{},increment:()=>{},gauge:()=>{},histogram:()=>{}});function s(t){return t.get(n)}function i(t){t instanceof Promise&&t.catch((()=>{}))}function o(t,r){const e={name:t,type:"counter",description:r?.description,labelNames:r?.labelNames};return{increment:(t,r,n)=>{i(s(t).increment(t,e,r??1,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}function a(t,r){const e={name:t,type:"gauge",description:r?.description,labelNames:r?.labelNames};return{gauge:(t,r,n)=>{i(s(t).gauge(t,e,r,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}function u(t,r){const e={name:t,type:"histogram",description:r?.description,labelNames:r?.labelNames};return{histogram:(t,r,n)=>{i(s(t).histogram(t,e,r,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}},"../proto/dist/generated/agent/v1/agent_pb.js"(t,r,e){e.d(r,{PSN:()=>Yu,i9c:()=>Ha,xyI:()=>Ki,Mpn:()=>xu,zT:()=>pc,KFq:()=>$o,Kwc:()=>Ao,aZc:()=>zi,uHL:()=>ji,TTG:()=>Sa,Ibo:()=>Pu,QFf:()=>To,ljj:()=>mu,Y9z:()=>Ju,kJk:()=>Co,KRq:()=>Ya,Anz:()=>Za,j97:()=>La,cmU:()=>ja,o7L:()=>_a,QVp:()=>ju,nnk:()=>no,apn:()=>rc,Mzv:()=>ou,ih1:()=>Lu,hGJ:()=>aa,Pd7:()=>mc,Y5:()=>fc,nh0:()=>va,Uq:()=>ac,D$r:()=>$a,c2D:()=>Xu,Gmx:()=>bu,fxF:()=>Au,onr:()=>vu,d2k:()=>su,HXb:()=>Zi,qKo:()=>qa,oIR:()=>Na,tms:()=>Va,qKL:()=>Ga,Nn_:()=>Ku,c_h:()=>Xi,Lrv:()=>Vu,dwJ:()=>Wu,Bjv:()=>Ru,aK_:()=>pu,gan:()=>xa,vns:()=>Yi,Scs:()=>Ia,ZM9:()=>Fu,lWT:()=>Gu,ECk:()=>Nu,aon:()=>wo,PtE:()=>ku,tr3:()=>Mu,cHB:()=>$u,Y$k:()=>Ou,Fyz:()=>Du,Dm_:()=>Po,LLS:()=>Tu,V1v:()=>Eo,I0n:()=>Uu,xuG:()=>Cu,BU$:()=>Qu,iHX:()=>Uo,lJj:()=>zu,oW$:()=>ua,RGk:()=>Ua,Vtf:()=>sa,v$T:()=>Hu});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/subagents_pb.js"),i=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),o=e("../proto/dist/runtime/compact.js");class a extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class u extends a{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ShellToolCall|1 args #0|2 result #1|3 description 9?",i.a,i.W4]}}class c extends a{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ShellToolCallStdoutDelta|1 content 9"]}}class l extends a{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ShellToolCallStderrDelta|1 content 9"]}}class m extends a{constructor(t){super(),this.delta={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ShellToolCallDelta|1 stdout #0 delta|2 stderr #1 delta",c,l]}}var f=e("../proto/dist/generated/agent/v1/delete_exec_pb.js");class d extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class p extends d{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DeleteToolCall|1 args #0|2 result #1",f.dn,f.Pi]}}class h extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class g extends h{constructor(t){super(),this.globPattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GlobToolArgs|1 target_directory 9?|2 glob_pattern 9"]}}class _ extends h{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["GlobToolResult|1 success #0 result|2 error #1 result",w,J]}}class J extends h{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["GlobToolError|1 error 9"]}}class w extends h{constructor(t){super(),this.pattern="",this.path="",this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GlobToolSuccess|1 pattern 9|2 path 9|3 files 9*|4 total_files 5|5 client_truncated 8|6 ripgrep_truncated 8"]}}class y extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["GlobToolCall|1 args #0|2 result #1",g,_]}}var S=e("../proto/dist/generated/agent/v1/grep_exec_pb.js");class q extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class B extends q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["GrepToolCall|1 args #0|2 result #1",S.Qj,S.Ud]}}var I=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js");class P extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class b extends P{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ReadToolCall|1 args #0|2 result #1",R,v]}}class R extends P{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ReadToolArgs|1 path 9|2 offset 5?|3 limit 5?|5 include_line_numbers 8?"]}}class v extends P{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ReadToolResult|1 success #0 result|2 error #1 result",k,E]}}class x extends P{constructor(t){super(),this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ReadRange|1 start_line 13|2 end_line 13"]}}class k extends P{constructor(t){super(),this.output={case:void 0},this.isEmpty=!1,this.exceededLimit=!1,this.totalLines=0,this.fileSize=0,this.path="",this.relatedCursorRulePaths=[],this.relatedCursorRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ReadToolSuccess|1 content 9 output|6 data 12 output|9 data_blob_id 12 output|10 content_blob_id 12 output|2 is_empty 8|3 exceeded_limit 8|4 total_lines 13|5 file_size 13|7 path 9|8 read_range #0?|11 include_line_numbers 8?|12 related_cursor_rule_paths 9*|13 related_cursor_rules #1*",x,I.DX]}}class E extends P{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ReadToolError|1 error_message 9"]}}var C=e("../proto/dist/generated/agent/v1/todo_tool_pb.js");class T extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class U extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["EditArgs|1 path 9|6 stream_content 9?"]}}class A extends T{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["EditResult|1 success #0 result|2 file_not_found #1 result|3 read_permission_denied #2 result|4 write_permission_denied #3 result|6 rejected #4 result|7 error #5 result",$,M,O,D,N,G]}}class $ extends T{constructor(t){super(),this.path="",this.afterFullFileContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["EditSuccess|1 path 9|3 lines_added 5?|4 lines_removed 5?|5 diff_string 9?|6 before_full_file_content 9?|7 after_full_file_content 9|8 message 9?"]}}class M extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["EditFileNotFound|1 path 9"]}}class O extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["EditReadPermissionDenied|1 path 9"]}}class D extends T{constructor(t){super(),this.path="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["EditWritePermissionDenied|1 path 9|2 error 9|3 is_readonly 8"]}}class N extends T{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["EditRejected|1 path 9|2 reason 9"]}}class G extends T{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["EditError|1 path 9|2 error 9|5 model_visible_error 9?"]}}class L extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["EditToolCall|1 args #0|2 result #1",U,A]}}class F extends T{constructor(t){super(),this.streamContentDelta="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["EditToolCallDelta|1 stream_content_delta 9"]}}var K=e("../proto/dist/generated/agent/v1/ls_exec_pb.js");class z extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class j extends z{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["LsToolCall|1 args #0|2 result #1",K.xe,K.fv]}}var H=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),W=e("../proto/dist/generated/agent/v1/utils_pb.js");class Q extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class V extends Q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["ReadLintsToolCall|1 args #0|2 result #1",X,Y]}}class X extends Q{constructor(t){super(),this.paths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["ReadLintsToolArgs|1 paths 9*"]}}class Y extends Q{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["ReadLintsToolResult|1 success #0 result|2 error #1 result",Z,nt]}}class Z extends Q{constructor(t){super(),this.fileDiagnostics=[],this.totalFiles=0,this.totalDiagnostics=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["ReadLintsToolSuccess|1 file_diagnostics #0*|2 total_files 5|3 total_diagnostics 5",tt]}}class tt extends Q{constructor(t){super(),this.path="",this.diagnostics=[],this.diagnosticsCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["FileDiagnostics|1 path 9|2 diagnostics #0*|3 diagnostics_count 5",rt]}}class rt extends Q{constructor(t){super(),this.severity=H.h_.UNSPECIFIED,this.message="",this.source="",this.code="",this.isStale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["DiagnosticItem|1 severity #0|2 range #1|3 message 9|4 source 9|5 code 9|6 is_stale 8",H.h_,et]}}class et extends Q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["DiagnosticRange|1 start #0|2 end #0",W.yX]}}class nt extends Q{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ReadLintsToolError|1 error_message 9"]}}var st=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js");class it extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ot extends it{constructor(t){super(),this.error="",this.readToolDefReminder="",this.systemReminders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["McpToolError|1 error 9|2 read_tool_def_reminder 9|3 system_reminders #0*",st.Kp]}}class at extends it{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["McpToolResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result",st.QW,ot,st.xo,st.HQ]}}class ut extends it{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["McpToolCall|1 args #0|2 result #1|3 description 9?",st.E_,at]}}var ct=e("../proto/dist/generated/aiserver/v1/repository_pb.js");class lt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class mt extends lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["SemSearchToolCall|1 args #0|2 result #1",ft,dt]}}class ft extends lt{constructor(t){super(),this.query="",this.targetDirectories=[],this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["SemSearchToolArgs|1 query 9|2 target_directories 9*|3 explanation 9"]}}class dt extends lt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["SemSearchToolResult|1 success #0 result|2 error #1 result",pt,ht]}}class pt extends lt{constructor(t){super(),this.results="",this.codeResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["SemSearchToolSuccess|1 results 9|2 code_results #0*",ct.PT]}}class ht extends lt{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["SemSearchToolError|1 error_message 9"]}}var gt=e("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),_t=e("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Jt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class wt extends Jt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["ListMcpResourcesToolCall|1 args #0|2 result #1",st.kj,st.kP]}}class yt extends Jt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["ReadMcpResourceToolCall|1 args #0|2 result #1",st.DI,st.ZD]}}var St=e("../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"),qt=e("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Bt=e("../proto/dist/generated/agent/v1/fetch_exec_pb.js");class It extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Pt extends It{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["FetchToolCall|1 args #0|2 result #1",Bt.UM,Bt.uN]}}var bt=e("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Rt=e("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),vt=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js");class xt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class kt extends xt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["RecordScreenToolCall|1 args #0|2 result #1",vt.zH,vt.Tj]}}var Et=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),Ct=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js");class Tt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ut extends Tt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["WriteShellStdinToolCall|1 args #0|2 result #1",Ct.LL,Ct.nt]}}class At extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class $t extends At{constructor(t){super(),this.unexpectedActionOutcomes="",this.relevantInstructions="",this.scenarioAnalysis="",this.criticalSynthesis="",this.nextSteps="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["ReflectArgs|1 unexpected_action_outcomes 9|2 relevant_instructions 9|3 scenario_analysis 9|4 critical_synthesis 9|5 next_steps 9|6 tool_call_id 9"]}}class Mt extends At{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["ReflectResult|1 success #0 result|2 error #1 result",Ot,Dt]}}class Ot extends At{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["ReflectSuccess"]}}class Dt extends At{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["ReflectError|1 error 9"]}}class Nt extends At{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["ReflectToolCall|1 args #0|2 result #1",$t,Mt]}}var Gt=e("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class Lt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ft extends Lt{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["StartGrindExecutionArgs|1 explanation 9?|2 tool_call_id 9"]}}class Kt extends Lt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["StartGrindExecutionResult|1 success #0 result|2 error #1 result",zt,jt]}}class zt extends Lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zt,t,r)}static $(){return["StartGrindExecutionSuccess"]}}class jt extends Lt{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["StartGrindExecutionError|1 error 9"]}}class Ht extends Lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["StartGrindExecutionToolCall|1 args #0|2 result #1",Ft,Kt]}}class Wt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Qt extends Wt{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["StartGrindPlanningArgs|1 explanation 9?|2 tool_call_id 9"]}}class Vt extends Wt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["StartGrindPlanningResult|1 success #0 result|2 error #1 result",Xt,Yt]}}class Xt extends Wt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["StartGrindPlanningSuccess"]}}class Yt extends Wt{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["StartGrindPlanningError|1 error 9"]}}class Zt extends Wt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["StartGrindPlanningToolCall|1 args #0|2 result #1",Qt,Vt]}}var tr=e("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),rr=e("../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"),er=e("../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"),nr=e("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),sr=e("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js");class ir extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class or extends ir{constructor(t){super(),this.taskId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["AwaitArgs|1 task_id 9|2 block_until_ms 13?|3 regex 9?"]}}class ar extends ir{constructor(t){super(),this.taskId="",this.runtimeMs=n.protoInt64.zero,this.outputFilePath="",this.outputLength=n.protoInt64.zero,this.regexRequested=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["AwaitTaskComplete|1 task_id 9|2 runtime_ms 4|3 output_file_path 9|4 output_length 4|5 regex_requested 8|6 regex_match 9?|7 exit_code 17?|8 wake_reason 9?"]}}class ur extends ir{constructor(t){super(),this.taskId="",this.runtimeMs=n.protoInt64.zero,this.outputFilePath="",this.outputLength=n.protoInt64.zero,this.regexRequested=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["AwaitTaskStillRunning|1 task_id 9|2 runtime_ms 4|3 output_file_path 9|4 output_length 4|5 regex_requested 8|6 regex_match 9?|7 wake_reason 9?"]}}class cr extends ir{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["AwaitError|1 error 9"]}}class lr extends ir{constructor(t){super(),this.awaitResult={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["AwaitSuccess|1 complete #0 await_result|2 still_running #1 await_result",ar,ur]}}class mr extends ir{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["AwaitResult|1 complete #0 result|2 still_running #1 result|3 error #2 result|4 success #3 result",ar,ur,cr,lr]}}class fr extends ir{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["AwaitToolCall|1 args #0|2 result #1",or,mr]}}class dr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class pr extends dr{constructor(t){super(),this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["BlameByFilePathArgs|1 file_path 9|2 start_line 5?|3 end_line 5?"]}}class hr extends dr{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["BlameByFilePathSuccess|1 content 9"]}}class gr extends dr{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["BlameByFilePathError|1 error_message 9"]}}class _r extends dr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["BlameByFilePathResult|1 success #0 result|2 error #1 result",hr,gr]}}class Jr extends dr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jr,t,r)}static $(){return["BlameByFilePathToolCall|1 args #0|2 result #1",pr,_r]}}class wr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class yr extends wr{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yr,t,r)}static $(){return["GetMcpToolsArgs|1 server 9?|2 tool_name 9?|3 pattern 9?|4 tool_call_id 9"]}}class Sr extends wr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sr,t,r)}static $(){return["GetMcpToolsAgentResult|1 success #0 result|2 error #1 result",qr,Br]}}class qr extends wr{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qr,t,r)}static $(){return["GetMcpToolsSuccess|1 content 9|2 output_file_path 9?"]}}class Br extends wr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Br,t,r)}static $(){return["GetMcpToolsError|1 error 9"]}}class Ir extends wr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ir,t,r)}static $(){return["GetMcpToolsToolCall|1 args #0|2 result #1",yr,Sr]}}class Pr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class br extends Pr{constructor(t){super(),this.title="",this.file="",this.startLine=0,this.endLine=0,this.description="",this.severity="",this.category="",this.rationale="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(br,t,r)}static $(){return["ReportBugArgs|1 title 9|2 file 9|3 start_line 5|4 end_line 5|5 description 9|6 severity 9|7 category 9|8 rationale 9"]}}class Rr extends Pr{constructor(t){super(),this.output="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rr,t,r)}static $(){return["ReportBugSuccess|1 output 9"]}}class vr extends Pr{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vr,t,r)}static $(){return["ReportBugError|1 error_message 9"]}}class xr extends Pr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xr,t,r)}static $(){return["ReportBugResult|1 success #0 result|2 error #1 result",Rr,vr]}}class kr extends Pr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kr,t,r)}static $(){return["ReportBugToolCall|1 args #0|2 result #1",br,xr]}}class Er extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Cr extends Er{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cr,t,r)}static $(){return["CommunicateUpdateArgs|1 current_step 9?|3 final_summary 9?|4 completed_subtitle 9?"]}}class Tr extends Er{constructor(t){super(),this.currentStep="",this.messageIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tr,t,r)}static $(){return["CommunicateUpdateSuccess|1 current_step 9|3 message_index 13"]}}class Ur extends Er{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ur,t,r)}static $(){return["CommunicateUpdateError|1 error 9"]}}class Ar extends Er{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ar,t,r)}static $(){return["CommunicateUpdateResult|1 success #0 result|2 error #1 result",Tr,Ur]}}class $r extends Er{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($r,t,r)}static $(){return["CommunicateUpdateToolCall|1 args #0|2 result #1",Cr,Ar]}}class Mr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Or extends Mr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Or,t,r)}static $(){return["SendFinalSummaryArgs|1 final_summary 9?"]}}class Dr extends Mr{constructor(t){super(),this.finalSummary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dr,t,r)}static $(){return["SendFinalSummarySuccess|1 final_summary 9"]}}class Nr extends Mr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nr,t,r)}static $(){return["SendFinalSummaryError|1 error 9"]}}class Gr extends Mr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gr,t,r)}static $(){return["SendFinalSummaryResult|1 success #0 result|2 error #1 result",Dr,Nr]}}class Lr extends Mr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lr,t,r)}static $(){return["SendFinalSummaryToolCall|1 args #0|2 result #1",Or,Gr]}}var Fr=e("../proto/dist/generated/agent/v1/replace_env_tool_pb.js");class Kr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class zr extends Kr{constructor(t){super(),this.toolCallId="",this.prUrl="",this.addLabels=[],this.removeLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zr).fromBinary(t,r)}static fromJson(t,r){return(new zr).fromJson(t,r)}static fromJsonString(t,r){return(new zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zr,t,r)}static $(){return["EditPrLabelsArgs|1 tool_call_id 9|2 pr_url 9|4 add_labels 9*|5 remove_labels 9*"]}}class jr extends Kr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jr,t,r)}static $(){return["EditPrLabelsResult|1 success #0 result|2 error #1 result",Hr,Wr]}}class Hr extends Kr{constructor(t){super(),this.prUrl="",this.prNumber=0,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hr,t,r)}static $(){return["EditPrLabelsSuccess|1 pr_url 9|2 pr_number 5|3 message 9"]}}class Wr extends Kr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wr,t,r)}static $(){return["EditPrLabelsError|1 error 9"]}}class Qr extends Kr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qr,t,r)}static $(){return["EditPrLabelsToolCall|1 args #0|2 result #1",zr,jr]}}class Vr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Xr extends Vr{constructor(t){super(),this.checkName="",this.tldr="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xr,t,r)}static $(){return["RecordCiInvestigationFinding|1 check_name 9|2 details_url 9?|3 tldr 9|4 root_cause 9?|5 failing_signal 9?|6 suggested_next_step 9?|7 diff_relation 9?|8 diff_relation_evidence 9?|9 flake_assessment 9?|10 flake_evidence 9?|11 rerun_available 8?|12 rerun_evidence 9?|13 recommended_action 9?|14 recommended_action_evidence 9?|15 confidence 9?"]}}class Yr extends Vr{constructor(t){super(),this.summary="",this.themes=[],this.checkKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yr,t,r)}static $(){return["RecordCiInvestigationOverall|1 summary 9|2 themes 9*|3 recommended_action 9?|4 recommended_action_evidence 9?|5 check_keys 9*"]}}class Zr extends Vr{constructor(t){super(),this.findings=[],this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zr,t,r)}static $(){return["RecordCiInvestigationFindingsArgs|1 findings #0*|2 overall #1?|3 tool_call_id 9",Xr,Yr]}}class te extends Vr{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(te,t,r)}static $(){return["RecordCiInvestigationFindingsSuccess|1 message 9"]}}class re extends Vr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(re,t,r)}static $(){return["RecordCiInvestigationFindingsError|1 error 9"]}}class ee extends Vr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ee,t,r)}static $(){return["RecordCiInvestigationFindingsResult|1 success #0 result|2 error #1 result",te,re]}}class ne extends Vr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ne,t,r)}static $(){return["RecordCiInvestigationFindingsToolCall|1 args #0|2 result #1",Zr,ee]}}class se extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ie extends se{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ie,t,r)}static $(){return["SendMessageText|1 content 9"]}}class oe extends se{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oe,t,r)}static $(){return["SendMessageAttachment|1 url 9|2 alt 9?"]}}class ae extends se{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ae,t,r)}static $(){return["SendMessageArgs|1 text #0 message|2 attachment #1 message|3 reply_to 9?|4 replace_previous_message 8?",ie,oe]}}class ue extends se{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.messageId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ue,t,r)}static $(){return["SendMessageSuccess|1 timestamp 4|2 message_id 9|3 thread_id 9?"]}}class ce extends se{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ce,t,r)}static $(){return["SendMessageError|1 error 9"]}}class le extends se{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(le,t,r)}static $(){return["SendMessageResult|1 success #0 result|2 error #1 result",ue,ce]}}class me extends se{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(me,t,r)}static $(){return["SendMessageToolCall|1 args #0|2 result #1",ae,le]}}class fe extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class de extends fe{constructor(t){super(),this.bcIds=[],this.sources=[],this.statuses=[],this.includeTeamWide=!1,this.includeArchived=!1,this.includeTranscript=!1,this.activeSince="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(de,t,r)}static $(){return["FetchCloudAgentDataArgs|4 bc_ids 9*|6 sources 9*|7 statuses 9*|8 include_team_wide 8|9 include_archived 8|10 limit 5?|12 include_transcript 8|13 active_since 9"]}}class pe extends fe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pe,t,r)}static $(){return["FetchCloudAgentDataResult|1 success #0 result|2 error #1 result",he,ge]}}class he extends fe{constructor(t){super(),this.summary="",this.agentCount=0,this.writtenPaths=[],this.unavailableBcIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(he,t,r)}static $(){return["FetchCloudAgentDataSuccess|1 summary 9|2 agent_count 5|3 written_paths 9*|4 unavailable_bc_ids 9*"]}}class ge extends fe{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ge,t,r)}static $(){return["FetchCloudAgentDataError|1 error 9"]}}class _e extends fe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_e,t,r)}static $(){return["FetchCloudAgentDataToolCall|1 args #0|2 result #1",de,pe]}}class Je extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class we extends Je{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(we,t,r)}static $(){return["SendToUserArgs|1 message 9"]}}class ye extends Je{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ye,t,r)}static $(){return["SendToUserSuccess"]}}class Se extends Je{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Se,t,r)}static $(){return["SendToUserError|1 error 9"]}}class qe extends Je{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qe,t,r)}static $(){return["SendToUserResult|1 success #0 result|2 error #1 result",ye,Se]}}class Be extends Je{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Be,t,r)}static $(){return["SendToUserToolCall|1 args #0|2 result #1",we,qe]}}var Ie=e("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Pe=e("../proto/dist/generated/agent/v1/conversation_search_exec_pb.js");class be extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Re extends be{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Re,t,r)}static $(){return["SearchConversationsToolCall|1 args #0|2 result #1",Pe.$m,Pe.pT]}}const ve="agent.v1.";class xe extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return ve}}var ke=(0,o.QT)(n.proto3,ve,"GoalStatus",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"PAUSED"],[3,"COMPLETE"],[4,"CLEARED"]],1);class Ee extends xe{constructor(t){super(),this.objective="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ee,t,r)}static $(){return["CreateGoalArgs|1 objective 9"]}}class Ce extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ce,t,r)}static $(){return["CreateGoalSuccess"]}}class Te extends xe{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Te,t,r)}static $(){return["GoalError|1 error 9"]}}class Ue extends xe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ue,t,r)}static $(){return["CreateGoalResult|1 success #0 result|2 error #1 result",Ce,Te]}}class Ae extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ae,t,r)}static $(){return["CreateGoalToolCall|1 args #0|2 result #1",Ee,Ue]}}class $e extends xe{constructor(t){super(),this.status=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($e,t,r)}static $(){return["UpdateGoalArgs|1 status #0",ke]}}class Me extends xe{constructor(t){super(),this.status=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Me,t,r)}static $(){return["UpdateGoalSuccess|1 status #0",ke]}}class Oe extends xe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oe,t,r)}static $(){return["UpdateGoalResult|1 success #0 result|2 error #1 result",Me,Te]}}class De extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(De,t,r)}static $(){return["UpdateGoalToolCall|1 args #0|2 result #1",$e,Oe]}}const Ne="agent.v1.";class Ge extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Ne}}var Le=(0,o.QT)(n.proto3,Ne,"CreateAgentPlacementApprovalState",[[0,"UNSPECIFIED"],[1,"REQUIRED"],[2,"DENIED"]],1);class Fe extends Ge{constructor(t){super(),this.toolCallId="",this.agentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fe,t,r)}static $(){return["GetAgentStatusArgs|1 tool_call_id 9|2 agent_ids 9*"]}}class Ke extends Ge{constructor(t){super(),this.bcId="",this.name="",this.lifecycle="",this.turnInFlight=!1,this.lastTerminalTurnStatus="",this.prUrl="",this.lastActivityAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ke,t,r)}static $(){return["GetAgentStatusWorker|1 bc_id 9|2 name 9|3 lifecycle 9|4 turn_in_flight 8|5 last_terminal_turn_status 9|6 pr_url 9|7 last_activity_at_ms 4"]}}class ze extends Ge{constructor(t){super(),this.workers=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ze,t,r)}static $(){return["GetAgentStatusSuccess|1 workers #0*|2 message 9",Ke]}}class je extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(je,t,r)}static $(){return["GetAgentStatusError|1 error 9"]}}class He extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(He,t,r)}static $(){return["GetAgentStatusResult|1 success #0 result|2 error #1 result",ze,je]}}class We extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(We,t,r)}static $(){return["GetAgentStatusToolCall|1 args #0|2 result #1",Fe,He]}}class Qe extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",this.message="",this.delivery="",this.title="",this.trackedTaskKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qe,t,r)}static $(){return["SendToAgentArgs|1 tool_call_id 9|2 agent_id 9|3 message 9|4 delivery 9|5 title 9|6 model 9?|7 tracked_task_keys 9*"]}}class Ve extends Ge{constructor(t){super(),this.workerBcId="",this.deliveredAs="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ve,t,r)}static $(){return["SendToAgentSuccess|1 worker_bc_id 9|2 delivered_as 9|3 message 9|4 recipient #0?",Xe]}}class Xe extends Ge{constructor(t){super(),this.kind=Ye.UNSPECIFIED,this.id="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xe,t,r)}static $(){return["SendToAgentRecipient|1 kind #0|2 id 9|3 display_name 9",Ye]}}var Ye=(0,o.QT)(n.proto3,Ne,"SendToAgentRecipient.Kind",[[0,"UNSPECIFIED"],[1,"MAIN_BOT"],[2,"PROJECT_SESSION"]],1);class Ze extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ze,t,r)}static $(){return["SendToAgentError|1 error 9"]}}class tn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tn,t,r)}static $(){return["SendToAgentResult|1 success #0 result|2 error #1 result",Ve,Ze]}}class rn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rn,t,r)}static $(){return["SendToAgentToolCall|1 args #0|2 result #1",Qe,tn]}}class en extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",this.mode="",this.maxTurns=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(en,t,r)}static $(){return["ReadAgentTranscriptArgs|1 tool_call_id 9|2 agent_id 9|3 mode 9|4 max_turns 13"]}}class nn extends Ge{constructor(t){super(),this.transcript="",this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nn,t,r)}static $(){return["ReadAgentTranscriptSuccess|1 transcript 9|2 truncated 8"]}}class sn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sn,t,r)}static $(){return["ReadAgentTranscriptError|1 error 9"]}}class on extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(on,t,r)}static $(){return["ReadAgentTranscriptResult|1 success #0 result|2 error #1 result",nn,sn]}}class an extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(an,t,r)}static $(){return["ReadAgentTranscriptToolCall|1 args #0|2 result #1",en,on]}}class un extends Ge{constructor(t){super(),this.toolCallId="",this.prompt="",this.labels={},this.trackedTaskKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(un,t,r)}static $(){return["CreateAgentArgs|1 tool_call_id 9|2 prompt 9|3 name 9?|4 model 9?|5 base_branch 9?|6 machine_type 9?|7 worker_id 9?|8 pool 9?|9 labels 9,9|10 environment_build_id 9?|11 environment_id 9?|12 repo_url 9?|13 tracked_task_keys 9*|14 fork_from 9?|15 fork_turns 13?"]}}class cn extends Ge{constructor(t){super(),this.agentId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cn,t,r)}static $(){return["CreateAgentSuccess|1 agent_id 9|2 message 9"]}}class ln extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ln,t,r)}static $(){return["CreateAgentError|1 error 9|2 placement_approval_state #0?",Le]}}class mn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mn,t,r)}static $(){return["CreateAgentResult|1 success #0 result|2 error #1 result",cn,ln]}}class fn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fn,t,r)}static $(){return["CreateAgentToolCall|1 args #0|2 result #1",un,mn]}}class dn extends Ge{constructor(t){super(),this.toolCallId="",this.prompt="",this.labels={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dn,t,r)}static $(){return["CreateProjectArgs|1 tool_call_id 9|2 prompt 9|3 name 9?|4 model 9?|5 base_branch 9?|6 machine_type 9?|7 worker_id 9?|8 pool 9?|9 labels 9,9|10 environment_build_id 9?|11 environment_id 9?|12 repo_url 9?"]}}class pn extends Ge{constructor(t){super(),this.agentId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pn,t,r)}static $(){return["CreateProjectSuccess|1 agent_id 9|2 message 9"]}}class hn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hn,t,r)}static $(){return["CreateProjectError|1 error 9|2 placement_approval_state #0?",Le]}}class gn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gn,t,r)}static $(){return["CreateProjectResult|1 success #0 result|2 error #1 result",pn,hn]}}class _n extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_n,t,r)}static $(){return["CreateProjectToolCall|1 args #0|2 result #1",dn,gn]}}class Jn extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["StartProjectUpdatesArgs|1 tool_call_id 9|2 agent_id 9"]}}class wn extends Ge{constructor(t){super(),this.agentId="",this.untilMs=n.protoInt64.zero,this.wasOn=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wn,t,r)}static $(){return["StartProjectUpdatesSuccess|1 agent_id 9|2 until_ms 3|3 was_on 8|4 message 9"]}}class yn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["StartProjectUpdatesError|1 error 9"]}}class Sn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["StartProjectUpdatesResult|1 success #0 result|2 error #1 result",wn,yn]}}class qn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["StartProjectUpdatesToolCall|1 args #0|2 result #1",Jn,Sn]}}class Bn extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["StopProjectUpdatesArgs|1 tool_call_id 9|2 agent_id 9"]}}class In extends Ge{constructor(t){super(),this.agentId="",this.wasOn=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(In,t,r)}static $(){return["StopProjectUpdatesSuccess|1 agent_id 9|2 was_on 8|3 message 9"]}}class Pn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pn,t,r)}static $(){return["StopProjectUpdatesError|1 error 9"]}}class bn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["StopProjectUpdatesResult|1 success #0 result|2 error #1 result",In,Pn]}}class Rn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["StopProjectUpdatesToolCall|1 args #0|2 result #1",Bn,bn]}}class vn extends Ge{constructor(t){super(),this.kind="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["ManageAccessTarget|1 kind 9|2 id 9"]}}class xn extends Ge{constructor(t){super(),this.toolCallId="",this.action="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xn,t,r)}static $(){return["ManageAccessArgs|1 tool_call_id 9|2 action 9|3 target #0?",vn]}}class kn extends Ge{constructor(t){super(),this.name="",this.grantedBy="",this.grantedAtMs=n.protoInt64.zero,this.scope="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["ManageAccessGrant|1 target #0|2 name 9|3 granted_by 9|4 granted_at_ms 4|5 scope 9",vn]}}class En extends Ge{constructor(t){super(),this.decision="",this.grants=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["ManageAccessSuccess|1 decision 9|2 grants #0*|3 message 9",kn]}}class Cn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["ManageAccessError|1 error 9"]}}class Tn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["ManageAccessResult|1 success #0 result|2 error #1 result",En,Cn]}}class Un extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["ManageAccessToolCall|1 args #0|2 result #1",xn,Tn]}}class An extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["StopAgentArgs|1 tool_call_id 9|2 agent_id 9"]}}class $n extends Ge{constructor(t){super(),this.workerBcId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["StopAgentSuccess|1 worker_bc_id 9|2 message 9"]}}class Mn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["StopAgentError|1 error 9"]}}class On extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["StopAgentResult|1 success #0 result|2 error #1 result",$n,Mn]}}class Dn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["StopAgentToolCall|1 args #0|2 result #1",An,On]}}class Nn extends Ge{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["TrackedTaskDocumentInput|1 path 9|2 label 9?"]}}class Gn extends Ge{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["TrackedTaskUrlInput|1 url 9|2 label 9?"]}}class Ln extends Ge{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["TrackedTaskLinkInput|1 agent_id 9 target|2 pr_url 9 target|3 document #0 target|4 url #1 target",Nn,Gn]}}class Fn extends Ge{constructor(t){super(),this.url="",this.openedByAgentId="",this.countsForCompletion=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["TrackedTaskPrLinkView|1 url 9|2 opened_by_agent_id 9|3 counts_for_completion 8"]}}class Kn extends Ge{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["TrackedTaskLinkView|1 agent_id 9 target|2 pr #0 target|3 document #1 target|4 url #2 target",Fn,Nn,Gn]}}class zn extends Ge{constructor(t){super(),this.key="",this.title="",this.statusId="",this.statusLabel="",this.owner="",this.parentKey="",this.links=[],this.updatedAtMs=n.protoInt64.zero,this.ownerSessionId="",this.version=n.protoInt64.zero,this.tag="",this.internalNotes="",this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["TrackedTaskView|1 key 9|2 title 9|3 status_id 9|4 status_label 9|5 owner 9|6 parent_key 9|7 links #0*|8 updated_at_ms 4|9 owner_session_id 9|10 version 4|11 tag 9|12 internal_notes 9|13 tags 9*",Kn]}}class jn extends Ge{constructor(t){super(),this.id="",this.label="",this.category="",this.taskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["TrackedTaskStatusView|1 id 9|2 label 9|3 category 9|4 task_count 13|5 description 9?"]}}class Hn extends Ge{constructor(t){super(),this.id="",this.label="",this.color="",this.taskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["TrackedTaskTagView|1 id 9|2 label 9|3 color 9|4 task_count 13"]}}class Wn extends Ge{constructor(t){super(),this.name="",this.sessionId="",this.isYou=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["TrackedTaskMemberView|1 name 9|2 session_id 9|3 is_you 8"]}}class Qn extends Ge{constructor(t){super(),this.toolCallId="",this.keys=[],this.statusCategories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["ListTrackedTasksArgs|1 tool_call_id 9|2 keys 9*|3 status_categories 9*|4 owner 9?|5 linked_agent_id 9?|6 cursor 9?"]}}class Vn extends Ge{constructor(t){super(),this.tasks=[],this.statuses=[],this.members=[],this.olderClosedCount=0,this.truncated=!1,this.matchingCount=0,this.message="",this.tags=[],this.nextCursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["ListTrackedTasksSuccess|1 tasks #0*|2 statuses #1*|3 members #2*|4 older_closed_count 13|5 truncated 8|6 matching_count 13|7 message 9|8 tags #3*|9 next_cursor 9",zn,jn,Wn,Hn]}}class Xn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["ListTrackedTasksError|1 error 9"]}}class Yn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ListTrackedTasksResult|1 success #0 result|2 error #1 result",Vn,Xn]}}class Zn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ListTrackedTasksToolCall|1 args #0|2 result #1",Qn,Yn]}}class ts extends Ge{constructor(t){super(),this.title="",this.links=[],this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["NewTrackedTask|1 client_ref 9?|2 title 9|3 status 9?|4 owner 9?|5 parent 9?|6 links #0*|7 tag 9?|8 internal_notes 9?|9 tags 9*",Ln]}}class rs extends Ge{constructor(t){super(),this.toolCallId="",this.tasks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["CreateTrackedTasksArgs|1 tool_call_id 9|2 tasks #0*",ts]}}class es extends Ge{constructor(t){super(),this.clientRef="",this.key="",this.version=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["TrackedTaskCreated|1 client_ref 9|2 key 9|3 version 4"]}}class ns extends Ge{constructor(t){super(),this.created=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["CreateTrackedTasksSuccess|1 created #0*|2 message 9",es]}}class ss extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["CreateTrackedTasksError|1 error 9"]}}class is extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["CreateTrackedTasksResult|1 success #0 result|2 error #1 result",ns,ss]}}class os extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["CreateTrackedTasksToolCall|1 args #0|2 result #1",rs,is]}}class as extends Ge{constructor(t){super(),this.anchor={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["TrackedTaskPosition|1 before_key 9 anchor|2 after_key 9 anchor"]}}class us extends Ge{constructor(t){super(),this.key="",this.addLinks=[],this.removeLinks=[],this.version=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["TrackedTaskUpdate|1 key 9|2 title 9?|3 status 9?|4 owner 9?|5 parent 9?|6 position #0?|7 add_links #1*|8 remove_links #1*|9 version 4|10 tag 9?|11 internal_notes 9?|12 tags #2?",as,Ln,cs]}}class cs extends Ge{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["TrackedTaskTagIds|1 ids 9*"]}}class ls extends Ge{constructor(t){super(),this.toolCallId="",this.updates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["UpdateTrackedTasksArgs|1 tool_call_id 9|2 updates #0*",us]}}class ms extends Ge{constructor(t){super(),this.key="",this.field="",this.currentValue="",this.changedBy="",this.changedAtMs=n.protoInt64.zero,this.currentVersion=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["TrackedTaskConflict|1 key 9|2 field 9|3 current_value 9|4 changed_by 9|5 changed_at_ms 4|6 current_version 4"]}}class fs extends Ge{constructor(t){super(),this.key="",this.version=n.protoInt64.zero,this.title="",this.statusLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["TrackedTaskUpdated|1 key 9|2 version 4|3 title 9|4 status_label 9"]}}class ds extends Ge{constructor(t){super(),this.updated=[],this.conflicts=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["UpdateTrackedTasksSuccess|1 updated #0*|2 conflicts #1*|3 message 9",fs,ms]}}class ps extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["UpdateTrackedTasksError|1 error 9"]}}class hs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["UpdateTrackedTasksResult|1 success #0 result|2 error #1 result",ds,ps]}}class gs extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["UpdateTrackedTasksToolCall|1 args #0|2 result #1",ls,hs]}}class _s extends Ge{constructor(t){super(),this.toolCallId="",this.keys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["DeleteTrackedTasksArgs|1 tool_call_id 9|2 keys 9*"]}}class Js extends Ge{constructor(t){super(),this.deletedKeys=[],this.unparentedKeys=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["DeleteTrackedTasksSuccess|1 deleted_keys 9*|2 unparented_keys 9*|3 message 9"]}}class ws extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["DeleteTrackedTasksError|1 error 9"]}}class ys extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["DeleteTrackedTasksResult|1 success #0 result|2 error #1 result",Js,ws]}}class Ss extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["DeleteTrackedTasksToolCall|1 args #0|2 result #1",_s,ys]}}class qs extends Ge{constructor(t){super(),this.label="",this.category="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["TrackedTaskStatusInput|1 id 9?|2 label 9|3 icon 9?|4 category 9|5 description 9?"]}}class Bs extends Ge{constructor(t){super(),this.toolCallId="",this.statuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["UpdateTrackedTaskStatusesArgs|1 tool_call_id 9|2 statuses #0*",qs]}}class Is extends Ge{constructor(t){super(),this.statuses=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["UpdateTrackedTaskStatusesSuccess|1 statuses #0*|2 message 9",jn]}}class Ps extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["UpdateTrackedTaskStatusesError|1 error 9"]}}class bs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["UpdateTrackedTaskStatusesResult|1 success #0 result|2 error #1 result",Is,Ps]}}class Rs extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["UpdateTrackedTaskStatusesToolCall|1 args #0|2 result #1",Bs,bs]}}class vs extends Ge{constructor(t){super(),this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["TrackedTaskTagInput|1 id 9?|2 label 9|3 color 9?"]}}class xs extends Ge{constructor(t){super(),this.toolCallId="",this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["UpdateTrackedTaskTagsArgs|1 tool_call_id 9|2 tags #0*",vs]}}class ks extends Ge{constructor(t){super(),this.tags=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["UpdateTrackedTaskTagsSuccess|1 tags #0*|2 message 9",Hn]}}class Es extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["UpdateTrackedTaskTagsError|1 error 9"]}}class Cs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["UpdateTrackedTaskTagsResult|1 success #0 result|2 error #1 result",ks,Es]}}class Ts extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["UpdateTrackedTaskTagsToolCall|1 args #0|2 result #1",xs,Cs]}}const Us="agent.v1.";class As extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Us}}var $s=(0,o.QT)(n.proto3,Us,"WriteCanvasFailReason",[[0,"UNSPECIFIED"],[1,"TYPECHECK_FAILED"],[2,"COMPILE_FAILED"],[3,"TOO_LARGE"],[4,"UNAVAILABLE"],[5,"NOT_FOUND"],[6,"REFUSED"]],1),Ms=(0,o.QT)(n.proto3,Us,"ReadCanvasFailReason",[[0,"UNSPECIFIED"],[1,"NOT_FOUND"],[2,"UNAVAILABLE"],[3,"REFUSED"],[4,"INVALID_REFERENCE"]],1);class Os extends As{constructor(t){super(),this.line=0,this.character=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["CloudCanvasToolDiagnosticPosition|1 line 5|2 character 5"]}}class Ds extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["CloudCanvasToolDiagnosticRange|1 start #0|2 end #0",Os]}}class Ns extends As{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["CloudCanvasToolDiagnostic|1 message 9|2 code 9?|3 severity 5?|4 range #0?",Ds]}}class Gs extends As{constructor(t){super(),this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["WriteCanvasArgs|1 contents 9|2 canvas_id 9?|3 title 9?"]}}class Ls extends As{constructor(t){super(),this.canvasId="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["WriteCanvasSuccess|1 canvas_id 9|2 title 9?|3 url 9|4 page_url 9?|5 audience_notice 9?"]}}class Fs extends As{constructor(t){super(),this.reason=$s.UNSPECIFIED,this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["WriteCanvasFailure|1 reason #0|2 diagnostics #1*|3 detail 9?",$s,Ns]}}class Ks extends As{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["WriteCanvasResult|1 success #0 result|2 failure #1 result",Ls,Fs]}}class zs extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["WriteCanvasToolCall|1 args #0|2 result #1",Gs,Ks]}}class js extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["ReadCanvasArgs|1 canvas_id 9?|2 url 9?"]}}class Hs extends As{constructor(t){super(),this.canvasId="",this.url="",this.source="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["ReadCanvasSuccess|1 canvas_id 9|2 title 9?|3 url 9|4 source 9"]}}class Ws extends As{constructor(t){super(),this.reason=Ms.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["ReadCanvasFailure|1 reason #0|2 detail 9?",Ms]}}class Qs extends As{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["ReadCanvasResult|1 success #0 result|2 failure #1 result",Hs,Ws]}}class Vs extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["ReadCanvasToolCall|1 args #0|2 result #1",js,Qs]}}class Xs extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ys extends Xs{constructor(t){super(),this.prompt="",this.referenceImagePaths=[],this.keyframes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ys,t,r)}static $(){return["GenerateVideoArgs|1 prompt 9|2 file_path 9?|3 image_path 9?|4 reference_image_paths 9*|5 duration_seconds 13?|6 aspect_ratio 9?|7 resolution 9?|8 last_frame_path 9?|9 keyframes #0*",Zs]}}class Zs extends Xs{constructor(t){super(),this.imagePath="",this.timestampSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zs,t,r)}static $(){return["GenerateVideoKeyframe|1 image_path 9|2 timestamp_seconds 1"]}}class ti extends Xs{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ti,t,r)}static $(){return["GenerateVideoResult|1 success #0 result|2 error #1 result",ri,ei]}}class ri extends Xs{constructor(t){super(),this.filePath="",this.durationSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ri,t,r)}static $(){return["GenerateVideoSuccess|1 file_path 9|2 duration_seconds 13"]}}class ei extends Xs{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ei,t,r)}static $(){return["GenerateVideoError|1 error 9"]}}class ni extends Xs{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ni,t,r)}static $(){return["GenerateVideoToolCall|1 args #0|2 result #1",Ys,ti]}}class si extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ii extends si{constructor(t){super(),this.query="",this.allowedXHandles=[],this.excludedXHandles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ii,t,r)}static $(){return["XSearchArgs|1 query 9|2 from_date 9?|3 to_date 9?|4 allowed_x_handles 9*|5 excluded_x_handles 9*"]}}class oi extends si{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oi,t,r)}static $(){return["XSearchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",ai,ci,li]}}class ai extends si{constructor(t){super(),this.answer="",this.citations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ai,t,r)}static $(){return["XSearchSuccess|1 answer 9|2 citations #0*",ui]}}class ui extends si{constructor(t){super(),this.url="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ui,t,r)}static $(){return["XSearchCitation|1 url 9|2 title 9"]}}class ci extends si{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ci,t,r)}static $(){return["XSearchError|1 error 9"]}}class li extends si{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new li).fromBinary(t,r)}static fromJson(t,r){return(new li).fromJson(t,r)}static fromJsonString(t,r){return(new li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(li,t,r)}static $(){return["XSearchRejected|1 reason 9"]}}class mi extends si{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mi).fromBinary(t,r)}static fromJson(t,r){return(new mi).fromJson(t,r)}static fromJsonString(t,r){return(new mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mi,t,r)}static $(){return["XSearchToolCall|1 args #0|2 result #1",ii,oi]}}class fi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class di extends fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new di).fromBinary(t,r)}static fromJson(t,r){return(new di).fromJson(t,r)}static fromJsonString(t,r){return(new di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(di,t,r)}static $(){return["GetPrCodeTourArgs|1 tool_call_id 9|2 revision_id 9?|3 section_id 9?|4 head_sha 9?|5 pr_url 9?"]}}class pi extends fi{constructor(t){super(),this.revisionId="",this.status="",this.headSha="",this.feedback="",this.updatedAtMs=n.protoInt64.zero,this.isCurrent=!1,this.markdown="",this.source="",this.prUrl="",this.editedByBcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pi,t,r)}static $(){return["PrCodeTourRevisionSnapshot|1 revision_id 9|2 status 9|3 head_sha 9|4 feedback 9|5 updated_at_ms 3|6 is_current 8|7 markdown 9|8 source 9|9 pr_url 9|10 edited_by_bc_id 9"]}}class hi extends fi{constructor(t){super(),this.revisions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hi,t,r)}static $(){return["GetPrCodeTourSuccess|1 revisions #0*|2 section_id 9?",pi]}}class gi extends fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gi).fromBinary(t,r)}static fromJson(t,r){return(new gi).fromJson(t,r)}static fromJsonString(t,r){return(new gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gi,t,r)}static $(){return["GetPrCodeTourError|1 error 9"]}}class _i extends fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_i,t,r)}static $(){return["GetPrCodeTourResult|1 success #0 result|2 error #1 result",hi,gi]}}class Ji extends fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ji,t,r)}static $(){return["GetPrCodeTourToolCall|1 args #0|2 result #1",di,_i]}}const wi="agent.v1.";class yi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return wi}}var Si=(0,o.QT)(n.proto3,wi,"UpdatePrCodeTourExecutionMode",[[0,"UNSPECIFIED"],[1,"SERVER_SCHEDULED"],[2,"CLIENT_REQUIRED"],[3,"SKIPPED"],[4,"EDITED"]],1);class qi extends yi{constructor(t){super(),this.feedback="",this.toolCallId="",this.scopeCommitHashes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qi,t,r)}static $(){return["UpdatePrCodeTourArgs|1 feedback 9|2 tool_call_id 9|3 base_sha 9?|4 head_sha 9?|5 source_revision_id 9?|6 revision_id 9?|7 markdown 9?|8 heading 9?|9 artifact_path 9?|10 artifact_alt 9?|11 scope_commit_hashes 9*|12 explicit_user_prompt 9?|13 pr_url 9?"]}}class Bi extends yi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bi,t,r)}static $(){return["UpdatePrCodeTourResult|1 success #0 result|2 error #1 result",Ii,Pi]}}class Ii extends yi{constructor(t){super(),this.revisionId="",this.message="",this.executionMode=Si.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ii,t,r)}static $(){return["UpdatePrCodeTourSuccess|1 revision_id 9|2 message 9|3 execution_mode #0",Si]}}class Pi extends yi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pi,t,r)}static $(){return["UpdatePrCodeTourError|1 error 9"]}}class bi extends yi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bi,t,r)}static $(){return["UpdatePrCodeTourToolCall|1 args #0|2 result #1",qi,Bi]}}const Ri="agent.v1.";class vi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Ri}}var xi=(0,o.QT)(n.proto3,Ri,"ExecuteOutcome",[[0,"UNSPECIFIED"],[1,"COMPLETED"],[2,"FAILED"],[3,"CANCELLED"]],1);class ki extends vi{constructor(t){super(),this.code="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ki,t,r)}static $(){return["ExecuteArgs|1 code 9|2 tool_call_id 9"]}}class Ei extends vi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ei,t,r)}static $(){return["ExecuteResult|1 success #0 result|2 error #1 result|3 rejected #2 result",Ci,Ti,Ui]}}class Ci extends vi{constructor(t){super(),this.output="",this.outcome=xi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ci,t,r)}static $(){return["ExecuteSuccess|1 output 9|2 outcome #0",xi]}}class Ti extends vi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ti,t,r)}static $(){return["ExecuteError|1 error 9"]}}class Ui extends vi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ui,t,r)}static $(){return["ExecuteRejected|1 reason 9"]}}class Ai extends vi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ai,t,r)}static $(){return["ExecuteToolCall|1 args #0|2 result #1",ki,Ei]}}var $i=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),Mi=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Oi=e("../proto/dist/generated/agent/v1/selected_context_pb.js"),Di=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),Ni=e("../proto/dist/generated/agent/v1/mcp_pb.js"),Gi=e("../proto/dist/generated/agent/v1/system_prompt_pb.js");const Li="agent.v1.";class Fi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Li}}var Ki=(0,o.QT)(n.proto3,Li,"AgentMode",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"ASK"],[3,"PLAN"],[4,"DEBUG"],[5,"TRIAGE"],[7,"MULTITASK"],[8,"CUSTOM"]],1),zi=(0,o.QT)(n.proto3,Li,"BackgroundTaskKind",[[0,"UNSPECIFIED"],[1,"SHELL"],[2,"SUBAGENT"]],1),ji=(0,o.QT)(n.proto3,Li,"BackgroundTaskStatus",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ERROR"],[3,"ABORTED"]],1),Hi=(0,o.QT)(n.proto3,Li,"BackgroundTaskNotificationContext",[[0,"UNSPECIFIED"],[1,"USER_DRIVEN_INTERACTIVE_CHILD"]],1),Wi=(0,o.QT)(n.proto3,Li,"SubagentRunStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"BACKGROUNDED"],[3,"SUCCESS"],[4,"ERROR"],[5,"ABORTED"]],1),Qi=(0,o.QT)(n.proto3,Li,"SubagentDispatchTool",[[0,"UNSPECIFIED"],[1,"TASK"],[2,"CREATE_AGENT"],[3,"SEND_TO_AGENT"],[4,"CREATE_PROJECT"]],1),Vi=(0,o.QT)(n.proto3,Li,"CustomModeSource",[[0,"UNSPECIFIED"],[1,"AGENT_SKILL"],[2,"PLUGIN_SKILL"],[3,"REPO_SKILL"],[4,"MANAGED_SKILL"]],1),Xi=(0,o.QT)(n.proto3,Li,"SimulatedMsgReason",[[0,"UNSPECIFIED"],[1,"PLAN_EXECUTION"],[2,"COMMIT_REMINDER"],[3,"BACKGROUND_TASK_COMPLETION"],[4,"DIFF_TAB_COMMIT"],[5,"DIFF_TAB_COMMIT_AND_PUSH"],[6,"DIFF_TAB_PUSH"],[7,"DIFF_TAB_CREATE_PR"],[8,"DIFF_TAB_FIX_MERGE_CONFLICTS"],[9,"USER_SENT_TO_SUBAGENT"],[10,"USER_INTERRUPTED_SUBAGENT"],[11,"USER_QUEUED_TO_SUBAGENT"],[12,"BABYSIT_PR_IN_CLOUD"],[13,"CI_PANEL_INVESTIGATE_FAILURE"],[14,"MULTITASK"],[15,"BUILD_IN_PARALLEL"],[16,"MULTITASK_SPLIT_PRS"],[17,"APPLY_LOCALLY"],[18,"CHECKOUT_BRANCH"],[19,"DIFF_TAB_UPDATE_BRANCH"],[20,"PR_TAB_BUGBOT_FIX"],[22,"RUN_BUGBOT_REVIEW"],[23,"RUN_SECURITY_REVIEW"],[24,"FSD_APPLY_FINDING"],[25,"FSD_UNDO_FINDING"],[26,"FSD_START"],[27,"FSD_PR_INTERRUPT"],[28,"SUBSCRIPTION"],[29,"DIFF_TAB_CREATE_BRANCH"],[30,"AGENT_STORE_CONFLICT"],[31,"GOAL_CONTINUATION"],[32,"PROJECT_KICKOFF"],[33,"MARKDOWN_PROMPT_BUTTON"],[34,"USER_QUICK_ACTION"],[35,"INTERACTION_RESPONSE"],[36,"DESKTOP_CONTROL"]],1),Yi=(0,o.QT)(n.proto3,Li,"SubscriptionSource",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"GITHUB"],[3,"LINEAR"],[4,"ORIGIN"],[5,"FACTORY"]],1),Zi=(0,o.QT)(n.proto3,Li,"ReplyAudience",[[0,"UNSPECIFIED"],[1,"USER"],[2,"AGENT"]],1),to=(0,o.QT)(n.proto3,Li,"TurnRunStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"COMPLETED"],[3,"FAILED"],[4,"INTERRUPTED"]],1),ro=(0,o.QT)(n.proto3,Li,"TurnInterruptReason",[[0,"UNSPECIFIED"],[1,"CANCELLED"],[2,"MAX_STEPS"]],1),eo=(0,o.QT)(n.proto3,Li,"ThinkingStyle",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"CODEX"],[3,"GPT5"]],1),no=(0,o.QT)(n.proto3,Li,"EstimatedCostSource",[[0,"UNSPECIFIED"],[1,"CATALOG"],[2,"USAGE"]],1),so=(0,o.QT)(n.proto3,Li,"ResponseComparisonDisplayOrder",[[0,"UNSPECIFIED"],[1,"PARENT_FIRST"],[2,"ALTERNATE_FIRST"]],1),io=(0,o.QT)(n.proto3,Li,"ResponseComparisonSkipReason",[[0,"UNSPECIFIED"],[1,"ALTERNATE_TOOL_CALL"],[2,"INFERENCE_ERROR"],[3,"TIMEOUT"],[4,"CANCELLED"]],1),oo=(0,o.QT)(n.proto3,Li,"PostRequestPromptButtonAction",[[0,"UNSPECIFIED"],[1,"UPDATE_CLIENT"]],1);class ao extends Fi{constructor(t){super(),this.description="",this.prompt="",this.attachments=[],this.mode=s.FL.UNSPECIFIED,this.respondingToMessageIds=[],this.environment=s.dU.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ao,t,r)}static $(){return["TaskArgs|1 description 9|2 prompt 9|3 subagent_type #0|4 model 9?|5 resume 9?|6 agent_id 9?|7 attachments 9*|8 mode #1|9 responding_to_message_ids 9*|10 environment #2|11 machine #3?",s._L,s.FL,s.dU,uo]}}class uo extends Fi{constructor(t){super(),this.machine={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uo,t,r)}static $(){return["TargetMachine|1 same_machine #0 machine|2 new_cloud_vm #1 machine|3 self_hosted_worker #2 machine|4 self_hosted_pool #3 machine",co,lo,mo,fo]}}class co extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(co,t,r)}static $(){return["SameMachineTarget"]}}class lo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lo,t,r)}static $(){return["NewCloudVmTarget|1 environment_build_id 9?|2 base_branch 9?|4 environment_id 9?|5 repo_url 9?"]}}class mo extends Fi{constructor(t){super(),this.workerId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mo,t,r)}static $(){return["SelfHostedWorkerTarget|1 worker_id 9"]}}class fo extends Fi{constructor(t){super(),this.labels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fo,t,r)}static $(){return["SelfHostedPoolTarget|1 pool 9?|2 labels #0*",po]}}class po extends Fi{constructor(t){super(),this.key="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(po,t,r)}static $(){return["SelfHostedWorkerLabel|1 key 9|2 value 9"]}}class ho extends Fi{constructor(t){super(),this.conversationSteps=[],this.isBackground=!1,this.backgroundReason=s.qL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ho,t,r)}static $(){return["TaskSuccess|1 conversation_steps #0*|2 agent_id 9?|3 is_background 8|4 duration_ms 4?|5 result_suffix 9?|6 background_reason #1|7 transcript_path 9?",Co,s.qL]}}class go extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(go,t,r)}static $(){return["TaskError|1 error 9"]}}class _o extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_o,t,r)}static $(){return["TaskResult|1 success #0 result|2 error #1 result",ho,go]}}class Jo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jo,t,r)}static $(){return["TaskToolCall|1 args #0|2 result #1|3 cloud_agent_bc_id 9?",ao,_o]}}class wo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wo,t,r)}static $(){return["TaskToolCallDelta|1 interaction_update #0",ac]}}class yo extends Fi{constructor(t){super(),this.path="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yo,t,r)}static $(){return["SetActiveBranchArgs|1 path 9|2 branch_name 9"]}}class So extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new So).fromBinary(t,r)}static fromJson(t,r){return(new So).fromJson(t,r)}static fromJsonString(t,r){return(new So).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(So,t,r)}static $(){return["SetActiveBranchSuccess"]}}class qo extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qo,t,r)}static $(){return["SetActiveBranchError|1 error 9"]}}class Bo extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bo,t,r)}static $(){return["SetActiveBranchResult|1 success #0 result|2 error #1 result",So,qo]}}class Io extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Io,t,r)}static $(){return["SetActiveBranchToolCall|1 args #0|2 result #1",yo,Bo]}}class Po extends Fi{constructor(t){super(),this.tool={case:void 0},this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Po,t,r)}static $(){return["ToolCall|1 shell_tool_call #0 tool|3 delete_tool_call #1 tool|4 glob_tool_call #2 tool|5 grep_tool_call #3 tool|8 read_tool_call #4 tool|9 update_todos_tool_call #5 tool|10 read_todos_tool_call #6 tool|12 edit_tool_call #7 tool|13 ls_tool_call #8 tool|14 read_lints_tool_call #9 tool|15 mcp_tool_call #10 tool|16 sem_search_tool_call #11 tool|17 create_plan_tool_call #12 tool|18 web_search_tool_call #13 tool|19 task_tool_call #14 tool|20 list_mcp_resources_tool_call #15 tool|21 read_mcp_resource_tool_call #16 tool|22 apply_agent_diff_tool_call #17 tool|23 ask_question_tool_call #18 tool|24 fetch_tool_call #19 tool|25 switch_mode_tool_call #20 tool|28 generate_image_tool_call #21 tool|29 record_screen_tool_call #22 tool|30 computer_use_tool_call #23 tool|31 write_shell_stdin_tool_call #24 tool|32 reflect_tool_call #25 tool|33 setup_vm_environment_tool_call #26 tool|34 truncated_tool_call #27 tool|35 start_grind_execution_tool_call #28 tool|36 start_grind_planning_tool_call #29 tool|37 web_fetch_tool_call #30 tool|38 report_bugfix_results_tool_call #31 tool|39 ai_attribution_tool_call #32 tool|40 pr_management_tool_call #33 tool|41 mcp_auth_tool_call #34 tool|42 await_tool_call #35 tool|43 blame_by_file_path_tool_call #36 tool|44 get_mcp_tools_tool_call #37 tool|45 report_bug_tool_call #38 tool|46 set_active_branch_tool_call #39 tool|48 communicate_update_tool_call #40 tool|49 send_final_summary_tool_call #41 tool|51 replace_env_tool_call #42 tool|52 edit_pr_labels_tool_call #43 tool|53 record_ci_investigation_findings_tool_call #44 tool|55 send_message_tool_call #45 tool|56 fetch_cloud_agent_data_tool_call #46 tool|58 send_to_user_tool_call #47 tool|68 connect_scm_tool_call #48 tool|69 search_conversations_tool_call #49 tool|70 create_goal_tool_call #50 tool|71 update_goal_tool_call #51 tool|73 get_agent_status_tool_call #52 tool|74 send_to_agent_tool_call #53 tool|75 read_agent_transcript_tool_call #54 tool|76 create_agent_tool_call #55 tool|77 stop_agent_tool_call #56 tool|79 write_canvas_tool_call #57 tool|80 read_canvas_tool_call #58 tool|81 generate_video_tool_call #59 tool|82 x_search_tool_call #60 tool|83 get_origin_pr_code_tour_tool_call #61 tool|84 update_origin_pr_code_tour_tool_call #62 tool|85 list_tracked_tasks_tool_call #63 tool|86 create_tracked_tasks_tool_call #64 tool|87 update_tracked_tasks_tool_call #65 tool|88 delete_tracked_tasks_tool_call #66 tool|89 update_tracked_task_statuses_tool_call #67 tool|90 create_project_tool_call #68 tool|91 update_tracked_task_tags_tool_call #69 tool|93 stop_project_updates_tool_call #70 tool|94 start_project_updates_tool_call #71 tool|95 manage_access_tool_call #72 tool|1000 execute_tool_call #73 tool|54 hook_additional_contexts #74*|57 tool_call_id 9?|59 started_at_ms 4?|60 completed_at_ms 4?",u,p,y,B,b,C.bk,C.AJ,L,j,V,ut,mt,gt.Ih,_t.pn,Jo,wt,yt,St.JU,qt.OU,Pt,bt.Cs,Rt.r9,kt,Et.t8,Ut,Nt,Gt.MU,ko,Ht,Zt,tr.fd,rr.U_,er.ex,nr.AU,sr.NX,fr,Jr,Ir,kr,Io,$r,Lr,Fr.us,Qr,ne,me,_e,Be,Ie.iO,Re,Ae,De,We,rn,an,fn,Dn,zs,Vs,ni,mi,Ji,bi,Zn,os,gs,Ss,Rs,_n,Ts,Rn,qn,Un,Ai,$i.C]}}class bo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bo,t,r)}static $(){return["TruncatedToolCallArgs"]}}class Ro extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ro,t,r)}static $(){return["TruncatedToolCallSuccess"]}}class vo extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vo,t,r)}static $(){return["TruncatedToolCallError|1 error 9"]}}class xo extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xo,t,r)}static $(){return["TruncatedToolCallResult|1 success #0 result|2 error #1 result",Ro,vo]}}class ko extends Fi{constructor(t){super(),this.originalStepBlobId=new Uint8Array(0),this.originalStepSizeBytes=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ko,t,r)}static $(){return["TruncatedToolCall|1 original_step_blob_id 12|2 args #0|3 result #1|4 original_step_size_bytes 13|5 preview #2",bo,xo,Po]}}class Eo extends Fi{constructor(t){super(),this.delta={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eo,t,r)}static $(){return["ToolCallDelta|1 shell_tool_call_delta #0 delta|2 task_tool_call_delta #1 delta|3 edit_tool_call_delta #2 delta|4 replace_env_tool_call_delta #3 delta",m,wo,F,Fr.km]}}class Co extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Co,t,r)}static $(){return["ConversationStep|1 assistant_message #0 message|2 tool_call #1 message|3 thinking_message #2 message",Oa,Po,Da]}}class To extends Fi{constructor(t){super(),this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(To,t,r)}static $(){return["ConversationAction|1 user_message_action #0 action|2 resume_action #1 action|3 cancel_action #2 action|4 summarize_action #3 action|5 shell_command_action #4 action|6 start_plan_action #5 action|7 execute_plan_action #6 action|8 async_ask_question_completion_action #7 action|10 cancel_subagent_action #8 action|12 background_task_completion_action #9 action|13 background_shell_action #10 action|14 background_subagent_action #11 action|16 subscription_notification_action #12 action|18 goal_continuation_action #13 action|19 inject_context_action #14 action|11 triggering_auth_id 9?|15 triggering_user_info #15?|17 request_context_parts #16?",sa,qa,Sa,Ia,Pa,ba,Ra,Ba,No,Ao,Go,Lo,ia,oa,aa,Uo,Mi.sG]}}class Uo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uo,t,r)}static $(){return["TriggeringUserInfo|1 auth_id 9?|2 user_id 5?|3 followup_id 9?"]}}class Ao extends Fi{constructor(t){super(),this.completions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ao,t,r)}static $(){return["BackgroundTaskCompletionAction|1 completions #0*|2 system_reminder 9?|3 request_context #1",$o,Mi.bb]}}class $o extends Fi{constructor(t){super(),this.taskId="",this.kind=zi.UNSPECIFIED,this.status=ji.UNSPECIFIED,this.title="",this.reason=s.U6.UNSPECIFIED,this.notificationContext=Hi.UNSPECIFIED,this.recordOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($o,t,r)}static $(){return["BackgroundTaskCompletion|1 task_id 9|2 kind #0|3 status #1|4 title 9|5 detail 9?|6 output_path 9?|7 thread_id 9?|8 reason #2|9 subagent_id 9?|10 tool_call_id 9?|11 notification_context #3|12 completed_at_ms 4?|13 record_only 8|14 subagent_state #4?",zi,ji,s.U6,Hi,Mo]}}class Mo extends Fi{constructor(t){super(),this.subagentId="",this.blobId=new Uint8Array(0),this.recordedByParentTurn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mo,t,r)}static $(){return["SubagentStatePointer|1 subagent_id 9|2 blob_id 12|3 recorded_by_parent_turn 8"]}}class Oo extends Fi{constructor(t){super(),this.parentToolCallId="",this.environment=s.dU.UNSPECIFIED,this.status=Wi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oo,t,r)}static $(){return["SubagentRunState|1 parent_tool_call_id 9|2 subagent_id 9?|3 environment #0|4 status #1|5 title 9?|6 detail 9?|7 transcript_path 9?|8 output_path 9?|9 completed_timestamp_ms 4?|10 completion_reason #2?",s.dU,Wi,s.U6]}}class Do extends Fi{constructor(t){super(),this.stepIndex=0,this.toolCallId="",this.tool=Qi.UNSPECIFIED,this.backgrounded=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Do,t,r)}static $(){return["SubagentDispatchStep|1 step_index 13|2 tool_call_id 9|3 tool #0|4 backgrounded 8",Qi]}}class No extends Fi{constructor(t){super(),this.subagentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(No,t,r)}static $(){return["CancelSubagentAction|1 subagent_id 9"]}}class Go extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Go,t,r)}static $(){return["BackgroundShellAction|1 tool_call_id 9"]}}class Lo extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lo,t,r)}static $(){return["BackgroundSubagentAction|1 tool_call_id 9"]}}class Fo extends Fi{constructor(t){super(),this.toolCallId="",this.resolution={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fo,t,r)}static $(){return["InterruptedPendingToolCallResolution|1 tool_call_id 9|2 shell_result #0 resolution|3 task_result #1 resolution",i.W4,_o]}}class Ko extends Fi{constructor(t){super(),this.resolutions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ko,t,r)}static $(){return["InterruptedPendingToolCallResolutions|1 resolutions #0*",Fo]}}class zo extends Fi{constructor(t){super(),this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zo,t,r)}static $(){return["ConversationHistory|1 messages #0*|2 replace_user_info 8?",jo]}}class jo extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jo,t,r)}static $(){return["ConversationHistoryMessage|1 user #0 message|2 assistant #1 message|3 tool #2 message",Ho,Xo,ea]}}class Ho extends Fi{constructor(t){super(),this.content=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ho,t,r)}static $(){return["ConversationHistoryUserMessage|1 content #0*",Wo]}}class Wo extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wo,t,r)}static $(){return["ConversationHistoryUserContent|1 text #0 content|2 image #1 content",Qo,Vo]}}class Qo extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qo,t,r)}static $(){return["ConversationHistoryTextContent|1 text 9"]}}class Vo extends Fi{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vo,t,r)}static $(){return["ConversationHistoryImageContent|1 data 9|2 mime_type 9?"]}}class Xo extends Fi{constructor(t){super(),this.content=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xo,t,r)}static $(){return["ConversationHistoryAssistantMessage|1 content #0*",Yo]}}class Yo extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yo,t,r)}static $(){return["ConversationHistoryAssistantContent|1 text #0 content|2 reasoning #1 content|3 redacted_reasoning #2 content|4 tool_call #3 content",Qo,Zo,ta,ra]}}class Zo extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zo,t,r)}static $(){return["ConversationHistoryReasoningContent|1 text 9|2 signature 9?"]}}class ta extends Fi{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ta,t,r)}static $(){return["ConversationHistoryRedactedReasoningContent|1 data 9"]}}class ra extends Fi{constructor(t){super(),this.toolCallId="",this.toolName="",this.argsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ra,t,r)}static $(){return["ConversationHistoryToolCall|1 tool_call_id 9|2 tool_name 9|3 args_json 9"]}}class ea extends Fi{constructor(t){super(),this.toolCallId="",this.toolName="",this.content=[],this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ea,t,r)}static $(){return["ConversationHistoryToolMessage|1 tool_call_id 9|2 tool_name 9|3 content #0*|4 is_error 8?|5 hook_additional_contexts #1*",na,$i.C]}}class na extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(na,t,r)}static $(){return["ConversationHistoryToolResultContent|1 text #0 content|2 image #1 content",Qo,Vo]}}class sa extends Fi{constructor(t){super(),this.prependUserMessages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sa,t,r)}static $(){return["UserMessageAction|1 user_message #0|2 request_context #1|3 send_to_interaction_listener 8?|4 prepend_user_messages #0*|6 interrupted_pending_tool_call_resolutions #2?|7 conversation_history #3?|8 trailing_conversation_history #3?",Ua,Mi.bb,Ko,zo]}}class ia extends Fi{constructor(t){super(),this.notifications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ia,t,r)}static $(){return["SubscriptionNotificationAction|1 notifications #0*|2 request_context #1|3 send_to_interaction_listener 8?",Ua,Mi.bb]}}class oa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oa,t,r)}static $(){return["GoalContinuationAction"]}}class aa extends Fi{constructor(t){super(),this.injectionId="",this.expectedRunId="",this.payload={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aa,t,r)}static $(){return["InjectContextAction|1 injection_id 9|2 expected_run_id 9|3 user_context #0 payload|4 system_context #1 payload",ua,ca]}}class ua extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ua,t,r)}static $(){return["UserContextInjection|1 user_message #0|2 request_context #1",Ua,Mi.bb]}}class ca extends Fi{constructor(t){super(),this.producer="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ca,t,r)}static $(){return["SystemContextInjection|1 producer 9|2 content 9"]}}class la extends Fi{constructor(t){super(),this.state={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(la,t,r)}static $(){return["ContextInjectionState|1 queued #0 state|2 delivered #1 state|3 queued_for_next_turn #2 state|4 cancelled #3 state|5 rejected #4 state",ma,fa,da,pa,ha]}}class ma extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ma,t,r)}static $(){return["ContextInjectionQueued"]}}class fa extends Fi{constructor(t){super(),this.step=0,this.deliveryBatchId="",this.deliveredAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fa).fromBinary(t,r)}static fromJson(t,r){return(new fa).fromJson(t,r)}static fromJsonString(t,r){return(new fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fa,t,r)}static $(){return["ContextInjectionDelivered|1 step 5|2 delivery_batch_id 9|3 delivered_at_ms 3"]}}class da extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new da).fromBinary(t,r)}static fromJson(t,r){return(new da).fromJson(t,r)}static fromJsonString(t,r){return(new da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(da,t,r)}static $(){return["ContextInjectionQueuedForNextTurn"]}}class pa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pa).fromBinary(t,r)}static fromJson(t,r){return(new pa).fromJson(t,r)}static fromJsonString(t,r){return(new pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pa,t,r)}static $(){return["ContextInjectionCancelled"]}}class ha extends Fi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ha).fromBinary(t,r)}static fromJson(t,r){return(new ha).fromJson(t,r)}static fromJsonString(t,r){return(new ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ha,t,r)}static $(){return["ContextInjectionRejected|1 reason 9"]}}class ga extends Fi{constructor(t){super(),this.id="",this.label="",this.source=Vi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ga,t,r)}static $(){return["SubmittedCustomMode|1 id 9|2 label 9|5 source #0|6 source_path 9?|7 source_hash 9?|10 managed_skill_id 9?|11 plugin_id 9?|12 plugin_snapshot_token 9?",Vi]}}class _a extends Fi{constructor(t){super(),this.id="",this.label="",this.source=Vi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_a,t,r)}static $(){return["CustomModeDescriptor|1 id 9|2 label 9|3 description 9?|4 icon 9?|5 color 9?|6 source #0|7 source_path 9?|8 source_hash 9?|9 managed_skill_id 9?|10 plugin_id 9?|11 plugin_snapshot_token 9?",Vi]}}class Ja extends Fi{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ja,t,r)}static $(){return["SubmittedExitedCustomMode|1 id 9|2 label 9"]}}class wa extends Fi{constructor(t){super(),this.nextMode=Ki.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wa,t,r)}static $(){return["CustomModeExitIntent|1 next_mode #0|2 exited_mode #1",Ki,Ja]}}class ya extends Fi{constructor(t){super(),this.intent={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ya,t,r)}static $(){return["CustomModeIntent|1 enter #0 intent|2 exit #1 intent",ga,wa]}}class Sa extends Fi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sa).fromBinary(t,r)}static fromJson(t,r){return(new Sa).fromJson(t,r)}static fromJsonString(t,r){return(new Sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sa,t,r)}static $(){return["CancelAction|1 reason 9|3 interrupted_pending_tool_call_resolutions #0?",Ko]}}class qa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qa).fromBinary(t,r)}static fromJson(t,r){return(new qa).fromJson(t,r)}static fromJsonString(t,r){return(new qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qa,t,r)}static $(){return["ResumeAction|2 request_context #0",Mi.bb]}}class Ba extends Fi{constructor(t){super(),this.originalToolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ba).fromBinary(t,r)}static fromJson(t,r){return(new Ba).fromJson(t,r)}static fromJsonString(t,r){return(new Ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ba,t,r)}static $(){return["AsyncAskQuestionCompletionAction|1 original_tool_call_id 9|2 original_args #0|3 result #1|4 request_context #2|5 during_voice_call 8?|6 voice_calls_read_utterances 8?",qt.ju,qt.tz,Mi.bb]}}class Ia extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ia).fromBinary(t,r)}static fromJson(t,r){return(new Ia).fromJson(t,r)}static fromJsonString(t,r){return(new Ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ia,t,r)}static $(){return["SummarizeAction"]}}class Pa extends Fi{constructor(t){super(),this.execId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pa).fromBinary(t,r)}static fromJson(t,r){return(new Pa).fromJson(t,r)}static fromJsonString(t,r){return(new Pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pa,t,r)}static $(){return["ShellCommandAction|1 shell_command #0|2 exec_id 9",Na]}}class ba extends Fi{constructor(t){super(),this.isSpec=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ba).fromBinary(t,r)}static fromJson(t,r){return(new ba).fromJson(t,r)}static fromJsonString(t,r){return(new ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ba,t,r)}static $(){return["StartPlanAction|1 user_message #0|2 request_context #1|3 is_spec 8",Ua,Mi.bb]}}class Ra extends Fi{constructor(t){super(),this.executionMode=Ki.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ra).fromBinary(t,r)}static fromJson(t,r){return(new Ra).fromJson(t,r)}static fromJsonString(t,r){return(new Ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ra,t,r)}static $(){return["ExecutePlanAction|1 request_context #0|2 plan #1?|3 plan_file_uri 9?|4 plan_file_content 9?|5 execution_mode #2|6 kickoff_message_id 9?|7 plan_id 9?|8 plan_file_path 9?|9 during_voice_call 8?|10 voice_calls_read_utterances 8?",Mi.bb,Fa,Ki]}}class va extends Fi{constructor(t){super(),this.interactionId="",this.skippedQuestionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new va).fromBinary(t,r)}static fromJson(t,r){return(new va).fromJson(t,r)}static fromJsonString(t,r){return(new va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(va,t,r)}static $(){return["InteractionResponseMetadata|1 interaction_id 9|2 response #0?|3 skipped_question_ids 9*",fc]}}class xa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xa).fromBinary(t,r)}static fromJson(t,r){return(new xa).fromJson(t,r)}static fromJsonString(t,r){return(new xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xa,t,r)}static $(){return["SubscriptionEventDisplay|1 display_label 9?|2 resource_url 9?|3 subscription_id 9?|5 headline_action 9?|6 headline_subject 9?"]}}class ka extends Fi{constructor(t){super(),this.planId="",this.planTitle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ka,t,r)}static $(){return["ExecutePlanInfo|1 plan_id 9|2 plan_title 9"]}}class Ea extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ea,t,r)}static $(){return["ProjectDetails|1 name 9?|2 subagent #0?|3 side_chat #1?|4 init_description 9?",Ca,Ta]}}class Ca extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ca,t,r)}static $(){return["ProjectSubagentDetails|2 store_dir 9?"]}}class Ta extends Fi{constructor(t){super(),this.storeDir="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ta,t,r)}static $(){return["ProjectSideChatDetails|1 store_dir 9"]}}class Ua extends Fi{constructor(t){super(),this.text="",this.messageId="",this.mode=Ki.UNSPECIFIED,this.conversationStateBlobId=new Uint8Array(0),this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ua,t,r)}static $(){return["UserMessage|1 text 9|2 message_id 9|3 selected_context #0?|4 mode #1|5 is_simulated_msg 8?|6 best_of_n_group_id 9?|7 try_use_best_of_n_promotion 8?|8 rich_text 9?|9 simulated_msg_reason #2?|10 conversation_state_blob_id 12|11 subagent_system_reminder 9?|13 triggering_user_info #3?|14 execute_plan_info #4?|15 simulated_message_metadata #5?|16 prompt_reference_id 9?|17 thread_id 9?|18 text_blob_id 12?|19 rich_text_blob_id 12?|21 hook_additional_contexts #6*|22 custom_mode_intent #7?|23 project_details #8?|24 turn_steer 8?|25 started_at_ms 4?|26 completed_at_ms 4?|27 sent_by_agent_id 9?|28 sent_by_voice_call 8?|29 sender #9?|30 forked_context 9?|31 reply_to 9?|32 reply_audience #10?|33 reply_to_tool_call_id 9?|34 during_voice_call 8?|35 inherits_voice_call 8?|36 voice_calls_read_utterances 8?|37 summarized_tool_call_id 9?|38 sender_time_zone 9?|39 reply_quote 9?",Oi.xv,Ki,Xi,Uo,ka,Aa,$i.C,ya,Ea,$a,Zi]}}class Aa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aa,t,r)}static $(){return["UserMessage.SimulatedMessageMetadata|1 title 9?|2 task_id 9?|3 fsd_finding_action 9?|4 url 9?|5 subscription_source #0?|6 subscription_event_display #1?|7 interaction_response #2?|8 tool_call_id 9?",Yi,xa,va]}}class $a extends Fi{constructor(t){super(),this.kind=Ma.UNSPECIFIED,this.id="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($a,t,r)}static $(){return["MessageSender|1 kind #0|2 id 9|3 display_name 9",Ma]}}var Ma=(0,o.QT)(n.proto3,Li,"MessageSender.Kind",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"VOICE_CALL"],[3,"MAIN_BOT"],[4,"PROJECT"],[5,"PROJECT_SLACK"],[6,"PROJECT_TEAMMATE"]],1);class Oa extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oa,t,r)}static $(){return["AssistantMessage|1 text 9|2 started_at_ms 4?|3 completed_at_ms 4?"]}}class Da extends Fi{constructor(t){super(),this.text="",this.durationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Da,t,r)}static $(){return["ThinkingMessage|1 text 9|2 duration_ms 13|3 started_at_ms 4?|4 completed_at_ms 4?|5 narration 8?"]}}class Na extends Fi{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Na,t,r)}static $(){return["ShellCommand|1 command 9"]}}class Ga extends Fi{constructor(t){super(),this.stdout="",this.stderr="",this.exitCode=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ga,t,r)}static $(){return["ShellOutput|1 stdout 9|2 stderr 9|3 exit_code 5"]}}class La extends Fi{constructor(t){super(),this.turn={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(La,t,r)}static $(){return["ConversationTurn|1 agent_conversation_turn #0 turn|2 shell_conversation_turn #1 turn",Ha,Va]}}class Fa extends Fi{constructor(t){super(),this.plan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fa,t,r)}static $(){return["ConversationPlan|1 plan 9"]}}class Ka extends Fi{constructor(t){super(),this.id="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ka,t,r)}static $(){return["PlanRegistryEntry|1 id 9|2 path 9"]}}class za extends Fi{constructor(t){super(),this.conversationId="",this.goalId="",this.objective="",this.status=ke.UNSPECIFIED,this.idleContinuationsWithoutToolCalls=0,this.continuationCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(za,t,r)}static $(){return["GoalState|1 conversation_id 9|2 goal_id 9|3 objective 9|4 status #0|5 idle_continuations_without_tool_calls 13|6 active_duration_ms 4?|7 last_accrued_at_ms 4?|8 continuation_count 13|9 agent_session_id 9?|11 context_tokens_added 3?",ke]}}class ja extends Fi{constructor(t){super(),this.turn={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ja,t,r)}static $(){return["ConversationTurnStructure|1 agent_conversation_turn #0 turn|2 shell_conversation_turn #1 turn",Wa,Xa]}}class Ha extends Fi{constructor(t){super(),this.steps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ha,t,r)}static $(){return["AgentConversationTurn|1 user_message #0|2 steps #1*|3 request_id 9?",Ua,Co]}}class Wa extends Fi{constructor(t){super(),this.userMessage=new Uint8Array(0),this.steps=[],this.sendMessageStepIndices=[],this.subagentDispatchSteps=[],this.dynamicToolNames=[],this.longReasoningReminderExposureLogged=!1,this.assistantTextStepIndices=[],this.appSecretsRequestStepIndices=[],this.preferenceChangeStepIndices=[],this.unfoldedStepIndices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wa).fromBinary(t,r)}static fromJson(t,r){return(new Wa).fromJson(t,r)}static fromJsonString(t,r){return(new Wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wa,t,r)}static $(){return["AgentConversationTurnStructure|1 user_message 12|2 steps 12*|3 request_id 9?|4 encrypted_model 9?|5 dynamic_tool_count 13?|6 send_message_step_indices 13*|7 routed_model_display_name 9?|8 subagent_dispatch_steps #0*|9 dynamic_tool_names 9*|10 user_message_id 9?|11 long_reasoning_reminder #1?|12 long_reasoning_reminder_exposure_logged 8|13 assistant_text_step_indices 13*|14 assistant_text_steps_recorded 8?|15 app_secrets_request_step_indices 13*|16 preference_change_step_indices 13*|17 run #2?|18 thread_id 9?|19 unfolded_step_indices 13*",Do,Qa,lu]}}class Qa extends Fi{constructor(t){super(),this.remainingDelayCalls=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qa).fromBinary(t,r)}static fromJson(t,r){return(new Qa).fromJson(t,r)}static fromJsonString(t,r){return(new Qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qa,t,r)}static $(){return["LongReasoningReminderState|1 remaining_delay_calls 13"]}}class Va extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Va).fromBinary(t,r)}static fromJson(t,r){return(new Va).fromJson(t,r)}static fromJsonString(t,r){return(new Va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Va,t,r)}static $(){return["ShellConversationTurn|1 shell_command #0|2 shell_output #1",Na,Ga]}}class Xa extends Fi{constructor(t){super(),this.shellCommand=new Uint8Array(0),this.shellOutput=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xa).fromBinary(t,r)}static fromJson(t,r){return(new Xa).fromJson(t,r)}static fromJsonString(t,r){return(new Xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xa,t,r)}static $(){return["ShellConversationTurnStructure|1 shell_command 12|2 shell_output 12"]}}class Ya extends Fi{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ya).fromBinary(t,r)}static fromJson(t,r){return(new Ya).fromJson(t,r)}static fromJsonString(t,r){return(new Ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ya,t,r)}static $(){return["ConversationSummary|1 summary 9"]}}class Za extends Fi{constructor(t){super(),this.summarizedMessages=[],this.summary="",this.windowTail=0,this.summaryMessage=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Za).fromBinary(t,r)}static fromJson(t,r){return(new Za).fromJson(t,r)}static fromJsonString(t,r){return(new Za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Za,t,r)}static $(){return["ConversationSummaryArchive|1 summarized_messages 12*|2 summary 9|3 window_tail 13|4 summary_message 12"]}}class tu extends Fi{constructor(t){super(),this.id="",this.label="",this.estimatedTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tu).fromBinary(t,r)}static fromJson(t,r){return(new tu).fromJson(t,r)}static fromJsonString(t,r){return(new tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tu,t,r)}static $(){return["PromptTokenBreakdownCategory|1 id 9|2 label 9|3 estimated_tokens 13|4 character_count 13?"]}}class ru extends Fi{constructor(t){super(),this.totalUsedTokens=0,this.maxTokens=0,this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ru).fromBinary(t,r)}static fromJson(t,r){return(new ru).fromJson(t,r)}static fromJsonString(t,r){return(new ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ru,t,r)}static $(){return["PromptTokenBreakdownSnapshot|1 total_used_tokens 13|2 max_tokens 13|3 categories #0*",tu]}}class eu extends Fi{constructor(t){super(),this.sourceType="",this.messageIndex=0,this.contentPath="",this.startOffset=0,this.endOffset=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eu).fromBinary(t,r)}static fromJson(t,r){return(new eu).fromJson(t,r)}static fromJsonString(t,r){return(new eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eu,t,r)}static $(){return["PromptContextSourceRef|1 source_type 9|3 message_index 13|4 content_path 9|5 start_offset 13|6 end_offset 13"]}}class nu extends Fi{constructor(t){super(),this.id="",this.kind="",this.label="",this.categoryId="",this.estimatedTokens=0,this.characterCount=0,this.contentAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nu).fromBinary(t,r)}static fromJson(t,r){return(new nu).fromJson(t,r)}static fromJsonString(t,r){return(new nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nu,t,r)}static $(){return["PromptContextNode|1 id 9|2 parent_id 9?|3 kind 9|4 label 9|5 category_id 9|6 estimated_tokens 13|7 character_count 13|9 content_available 8|11 source #0?|12 inline_content 9?",eu]}}class su extends Fi{constructor(t){super(),this.schemaVersion=0,this.nodes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new su).fromBinary(t,r)}static fromJson(t,r){return(new su).fromJson(t,r)}static fromJsonString(t,r){return(new su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(su,t,r)}static $(){return["PromptContextUsageTree|1 schema_version 13|2 nodes #0*",nu]}}class iu extends Fi{constructor(t){super(),this.usedTokens=0,this.maxTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iu).fromBinary(t,r)}static fromJson(t,r){return(new iu).fromJson(t,r)}static fromJsonString(t,r){return(new iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iu,t,r)}static $(){return["ConversationTokenDetails|1 used_tokens 13|2 max_tokens 13|3 breakdown #0?|4 prompt_context_usage_tree #1?",ru,su]}}class ou extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ou).fromBinary(t,r)}static fromJson(t,r){return(new ou).fromJson(t,r)}static fromJsonString(t,r){return(new ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ou,t,r)}static $(){return["FileState|1 content 9?|2 initial_content 9?"]}}class au extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new au).fromBinary(t,r)}static fromJson(t,r){return(new au).fromJson(t,r)}static fromJsonString(t,r){return(new au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(au,t,r)}static $(){return["FileStateStructure|1 content 12?|2 initial_content 12?"]}}class uu extends Fi{constructor(t){super(),this.durationMs=n.protoInt64.zero,this.timestampMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uu).fromBinary(t,r)}static fromJson(t,r){return(new uu).fromJson(t,r)}static fromJsonString(t,r){return(new uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uu,t,r)}static $(){return["StepTiming|1 duration_ms 4|2 timestamp_ms 4"]}}class cu extends Fi{constructor(t){super(),this.completedTurnCountCapped=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cu).fromBinary(t,r)}static fromJson(t,r){return(new cu).fromJson(t,r)}static fromJsonString(t,r){return(new cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cu,t,r)}static $(){return["TurnTelemetryState|1 completed_turn_count_capped 13|2 last_completed_turn_timestamp_ms 4?"]}}class lu extends Fi{constructor(t){super(),this.runId="",this.status=to.UNSPECIFIED,this.startedAtMs=n.protoInt64.zero,this.attemptCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lu).fromBinary(t,r)}static fromJson(t,r){return(new lu).fromJson(t,r)}static fromJsonString(t,r){return(new lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lu,t,r)}static $(){return["TurnRunRecord|1 run_id 9|2 status #0|3 started_at_ms 4|4 finished_at_ms 4?|5 attempt_count 13|6 interrupt_reason #1?",to,ro]}}class mu extends Fi{constructor(t){super(),this.rootPromptMessagesJson=[],this.turns=[],this.todos=[],this.pendingToolCalls=[],this.fileStates={},this.summaryArchives=[],this.plans={},this.communicateUpdateHistory=[],this.communicateUpdateStatesByParentToolCallId={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mu).fromBinary(t,r)}static fromJson(t,r){return(new mu).fromJson(t,r)}static fromJsonString(t,r){return(new mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mu,t,r)}static $(){return["ConversationState|1 root_prompt_messages_json 9*|8 turns #0*|3 todos #1*|4 pending_tool_calls 9*|5 token_details #2|6 summary #3?|7 plan #4?|9 summary_archive #5?|10 file_states 9,#6|11 summary_archives #5*|12 plans 9,#7|13 communicate_update_history #8*|14 communicate_update_final_summary 9?|15 communicate_update_completed_subtitle 9?|16 communicate_update_states_by_parent_tool_call_id 9,#9",La,C.kW,iu,Ya,Fa,Za,ou,Ka,fu,du]}}class fu extends Fi{constructor(t){super(),this.step="",this.messageIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fu).fromBinary(t,r)}static fromJson(t,r){return(new fu).fromJson(t,r)}static fromJsonString(t,r){return(new fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fu,t,r)}static $(){return["CommunicateUpdateHistoryEntry|1 step 9|3 message_index 13"]}}class du extends Fi{constructor(t){super(),this.history=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new du).fromBinary(t,r)}static fromJson(t,r){return(new du).fromJson(t,r)}static fromJsonString(t,r){return(new du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(du,t,r)}static $(){return["CommunicateUpdateTurnState|1 history #0*|2 final_summary 9?|3 completed_subtitle 9?",fu]}}class pu extends Fi{constructor(t){super(),this.createdTimestampMs=n.protoInt64.zero,this.lastUsedTimestampMs=n.protoInt64.zero,this.environment=s.dU.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pu).fromBinary(t,r)}static fromJson(t,r){return(new pu).fromJson(t,r)}static fromJsonString(t,r){return(new pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pu,t,r)}static $(){return["SubagentPersistedState|1 conversation_state #0|2 created_timestamp_ms 4|3 last_used_timestamp_ms 4|4 subagent_type #1|5 model_id 9?|6 environment #2|7 cloud_subagent #3?|8 first_class_bc_id 9?|9 cloud_requested_environment_build_id 9?|10 machine #4?|11 attached_video_unavailable #5?",Ju,s._L,s.dU,gu,uo,hu]}}class hu extends Fi{constructor(t){super(),this.videoPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hu).fromBinary(t,r)}static fromJson(t,r){return(new hu).fromJson(t,r)}static fromJsonString(t,r){return(new hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hu,t,r)}static $(){return["AttachedVideoUnavailable|1 video_paths 9*"]}}class gu extends Fi{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gu,t,r)}static $(){return["CloudSubagentReference|1 bc_id 9|2 transcript_path 9?"]}}class _u extends Fi{constructor(t){super(),this.repoPath="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_u,t,r)}static $(){return["TrackedGitRepo|1 repo_path 9|2 branch_name 9"]}}class Ju extends Fi{constructor(t){super(),this.rootPromptMessagesJson=[],this.turns=[],this.todos=[],this.pendingToolCalls=[],this.previousWorkspaceUris=[],this.fileStates={},this.fileStatesV2={},this.summaryArchives=[],this.turnTimings=[],this.subagentStates={},this.selfSummaryCount=0,this.readPaths=[],this.plans={},this.trackedGitRepoBranches=[],this.communicateUpdateHistory=[],this.subagentThreads={},this.communicateUpdateStatesByParentToolCallId={},this.subagentRunsByParentToolCallId={},this.subagentStateRefs={},this.completedAskQuestionToolCallIds=[],this.durableSkillBlocks=[],this.recentUserMessageIds=[],this.mentionedAgentIds=[],this.voiceCallUtterances=[],this.voiceCallTimeTaskIds=[],this.writesVoiceCallUtterances=!1,this.threadSummaries={},this.recentThreadReplies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ju,t,r)}static $(){return["ConversationStateStructure|1 root_prompt_messages_json 12*|8 turns 12*|3 todos 12*|4 pending_tool_calls 9*|5 token_details #0|6 summary 12?|7 plan 12?|9 previous_workspace_uris 9*|10 mode #1?|11 summary_archive 12?|12 file_states 9,12|15 file_states_v2 9,#2|13 summary_archives 12*|14 turn_timings #3*|16 subagent_states 9,#4|17 self_summary_count 13|18 read_paths 9*|19 active_branch_name 9?|20 plans 9,#5|21 tracked_git_repo_branches #6*|22 agent_type 9?|23 communicate_update_history #7*|24 subagent_threads 9,9|25 communicate_update_final_summary 9?|28 communicate_update_completed_subtitle 9?|29 communicate_update_states_by_parent_tool_call_id 9,#8|30 subagent_runs_by_parent_tool_call_id 9,#9|26 conversation_started_timestamp_ms 4?|27 conversation_started_time_zone 9?|31 subagent_state_refs 9,12|32 goal_state #10?|33 is_root_project_conversation 8?|34 completed_ask_question_tool_call_ids 9*|35 durable_skill_blocks 9*|36 durable_custom_mode_id 9?|37 message_count_at_last_compaction 13?|38 recent_user_message_ids 9*|39 recent_user_message_ids_older_turn_count 13?|40 turn_telemetry #11?|42 mentioned_agent_ids 9*|43 voice_call_utterances #12*|44 voice_call_pending_answer #13?|45 voice_call_time_task_ids 9*|46 writes_voice_call_utterances 8|47 voice_calls_read_utterances 8?|49 user_time_zone 9?|50 project_coordinator_system_section 9?|51 project_coordinator_system_section_communication_rules 8?|52 last_run #14?|53 thread_summaries 9,#15|54 recent_thread_replies #16*|55 turns_cleared 8?|56 project_prompt_turn_count 13?",iu,Ki,au,uu,pu,Ka,_u,fu,du,Oo,za,cu,Su,Bu,lu,yu,wu]}}class wu extends Fi{constructor(t){super(),this.messageId="",this.rootId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wu,t,r)}static $(){return["ThreadReply|1 message_id 9|2 root_id 9"]}}class yu extends Fi{constructor(t){super(),this.replyCount=0,this.lastReplyAtMs=n.protoInt64.zero,this.preview="",this.participantIds=[],this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yu,t,r)}static $(){return["ThreadSummary|1 reply_count 13|2 last_reply_at_ms 4|3 preview 9|4 participant_ids 9*|5 created_at_ms 4"]}}class Su extends Fi{constructor(t){super(),this.id="",this.kind=qu.UNSPECIFIED,this.text="",this.answersMessageIds=[],this.failed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Su,t,r)}static $(){return["VoiceCallUtterance|1 id 9|2 kind #0|3 text 9|4 answers_message_ids 9*|5 failed 8",qu]}}var qu=(0,o.QT)(n.proto3,Li,"VoiceCallUtterance.Kind",[[0,"UNSPECIFIED"],[1,"SEND"],[2,"TERMINAL"]],1);class Bu extends Fi{constructor(t){super(),this.messageIds=[],this.readsUtterances=!1,this.endedOnSend=!1,this.reopenedTerminalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bu,t,r)}static $(){return["VoiceCallPendingAnswer|1 message_ids 9*|2 reads_utterances 8|3 ended_on_send 8|4 reopened_terminal_id 9"]}}class Iu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iu,t,r)}static $(){return["ThinkingDetails"]}}class Pu extends Fi{constructor(t){super(),this.bearerToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pu,t,r)}static $(){return["ClientLlmGatewayCredential|1 bearer_token 9"]}}class bu extends Fi{constructor(t){super(),this.modelId="",this.displayModelId="",this.displayName="",this.displayNameShort="",this.aliases=[],this.credentials={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bu,t,r)}static $(){return["ModelDetails|1 model_id 9|3 display_model_id 9|4 display_name 9|5 display_name_short 9|6 aliases 9*|2 thinking_details #0?|7 max_mode 8?|8 api_key_credentials #1 credentials|9 azure_credentials #2 credentials|10 bedrock_credentials #3 credentials",Iu,Di.G0,Di.ih,Di.R4]}}class Ru extends Fi{constructor(t){super(),this.subagentType="",this.selection={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ru,t,r)}static $(){return["SubagentModelOverride|1 subagent_type 9|2 model #0 selection|3 inherit 8 selection|4 disabled 8 selection",Di.G4]}}class vu extends Fi{constructor(t){super(),this.id=new Uint8Array(0),this.value=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vu).fromBinary(t,r)}static fromJson(t,r){return(new vu).fromJson(t,r)}static fromJsonString(t,r){return(new vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vu,t,r)}static $(){return["PreFetchedBlob|1 id 12|2 value 12"]}}class xu extends Fi{constructor(t){super(),this.selectedSubagentModels=[],this.selectedSubagentModelDetails=[],this.preFetchedBlobs=[],this.subagentModelOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xu).fromBinary(t,r)}static fromJson(t,r){return(new xu).fromJson(t,r)}static fromJsonString(t,r){return(new xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xu,t,r)}static $(){return["AgentRunRequest|1 conversation_state #0|2 action #1|3 model_details #2|9 requested_model #3?|4 mcp_tools #4|5 conversation_id 9?|6 mcp_file_system_options #5?|7 skill_options #6?|8 custom_system_prompt 9?|11 subagent_type_name 9?|12 exclude_workspace_context 8?|13 harness 9?|14 selected_subagent_models #3*|15 selected_subagent_model_details #2*|16 conversation_group_id 9?|17 pre_fetched_blobs #7*|18 dev_raw_model_slug 9?|19 client_supports_inline_images 8?|20 subagent_model_overrides #8*|21 can_create_cloud_subagents 8?|22 suppress_subagent_progress_update_tool 8?|23 client_supports_send_to_user 8?|24 computer_use_coordinate_mode 9?|25 run_id 9?|26 agent_session_id 9?|28 client_supports_routed_model_update 8?|29 system_prompt_spec #9?|30 client_llm_gateway_credential #10?|31 client_supports_preview_card 8?|32 started_as_new_project 8?|33 first_project_onboarding 8?|34 next_interaction_query_id 13?|35 voice_call_notes #11?|36 transcript_parent_conversation_id 9?|37 emit_model_call_usage 8?",Ju,To,bu,Di.G4,Ni.Or,Ni.Is,Mi.uw,vu,Ru,Gi.$,Pu,s.OT]}}class ku extends Fi{constructor(t){super(),this.text="",this.isServerNotice=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ku).fromBinary(t,r)}static fromJson(t,r){return(new ku).fromJson(t,r)}static fromJsonString(t,r){return(new ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ku,t,r)}static $(){return["TextDeltaUpdate|1 text 9|2 is_server_notice 8"]}}class Eu extends Fi{constructor(t){super(),this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eu,t,r)}static $(){return["RoutedModelUpdate|1 display_name 9"]}}class Cu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cu,t,r)}static $(){return["ToolCallStartedUpdate|1 call_id 9|2 tool_call #0|3 model_call_id 9",Po]}}class Tu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tu,t,r)}static $(){return["ToolCallCompletedUpdate|1 call_id 9|2 tool_call #0|3 model_call_id 9",Po]}}class Uu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uu,t,r)}static $(){return["ToolCallDeltaUpdate|1 call_id 9|2 tool_call_delta #0|3 model_call_id 9",Eo]}}class Au extends Fi{constructor(t){super(),this.callId="",this.argsTextDelta="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Au,t,r)}static $(){return["PartialToolCallUpdate|1 call_id 9|2 tool_call #0|3 args_text_delta 9|4 model_call_id 9",Po]}}class $u extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($u,t,r)}static $(){return["ThinkingDeltaUpdate|1 text 9|2 thinking_style #0?",eo]}}class Mu extends Fi{constructor(t){super(),this.thinkingDurationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mu,t,r)}static $(){return["ThinkingCompletedUpdate|1 thinking_duration_ms 5|2 narration 8?"]}}class Ou extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ou,t,r)}static $(){return["ThinkingNoteUpdate|1 text 9"]}}class Du extends Fi{constructor(t){super(),this.tokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Du,t,r)}static $(){return["TokenDeltaUpdate|1 tokens 5"]}}class Nu extends Fi{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nu,t,r)}static $(){return["SummaryUpdate|1 summary 9"]}}class Gu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gu,t,r)}static $(){return["SummaryStartedUpdate"]}}class Lu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lu,t,r)}static $(){return["HeartbeatUpdate"]}}class Fu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fu,t,r)}static $(){return["SummaryCompletedUpdate|1 hook_message 9?|2 failed 8?|3 fallback 8?"]}}class Ku extends Fi{constructor(t){super(),this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ku,t,r)}static $(){return["ShellOutputDeltaUpdate|1 stdout #0 event|2 stderr #1 event|3 exit #2 event|4 start #3 event",i.o0,i.Db,i.vb,i.tD]}}class zu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zu,t,r)}static $(){return["TurnEndedUpdate|1 input_tokens 3?|2 output_tokens 3?|3 cache_read_tokens 3?|4 cache_write_tokens 3?|5 reasoning_tokens 3?|6 ended_at_ms 4?|7 estimated_cost #0?",ju]}}class ju extends Fi{constructor(t){super(),this.rawCostCents=0,this.chargedCents=0,this.source=no.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ju,t,r)}static $(){return["EstimatedCost|1 raw_cost_cents 1|2 charged_cents 1|3 source #0",no]}}class Hu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hu,t,r)}static $(){return["UserMessageAppendedUpdate|1 user_message #0",Ua]}}class Wu extends Fi{constructor(t){super(),this.stepId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wu,t,r)}static $(){return["StepStartedUpdate|1 step_id 4"]}}class Qu extends Fi{constructor(t){super(),this.callCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qu,t,r)}static $(){return["ToolRequestsListedUpdate|1 call_count 13"]}}class Vu extends Fi{constructor(t){super(),this.stepId=n.protoInt64.zero,this.stepDurationMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vu,t,r)}static $(){return["StepCompletedUpdate|1 step_id 4|2 step_duration_ms 3"]}}class Xu extends Fi{constructor(t){super(),this.modelCallId="",this.inputTokens=n.protoInt64.zero,this.outputTokens=n.protoInt64.zero,this.cacheReadTokens=n.protoInt64.zero,this.cacheWriteTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xu,t,r)}static $(){return["ModelCallCompletedUpdate|1 model_call_id 9|2 input_tokens 3|3 output_tokens 3|4 cache_read_tokens 3|5 cache_write_tokens 3|6 reasoning_tokens 3?"]}}class Yu extends Fi{constructor(t){super(),this.path="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yu,t,r)}static $(){return["ActiveBranchChange|1 path 9|2 branch_name 9"]}}class Zu extends Fi{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zu,t,r)}static $(){return["FeedbackRequestCategory|1 id 9|2 label 9"]}}class tc extends Fi{constructor(t){super(),this.id="",this.prompt="",this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tc,t,r)}static $(){return["FeedbackRequestCategoryGroup|1 id 9|2 prompt 9|3 categories #0*",Zu]}}class rc extends Fi{constructor(t){super(),this.requestId="",this.categories=[],this.categoryGroups=[],this.showFormImmediately=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rc,t,r)}static $(){return["FeedbackRequestUpdate|1 request_id 9|2 canonical_model_name 9?|3 categories #0*|4 category_groups #1*|5 show_form_immediately 8|6 title 9?|7 negative_title 9?|8 comment_placeholder 9?",Zu,tc]}}class ec extends Fi{constructor(t){super(),this.displayOrder=so.UNSPECIFIED,this.parentInvocationId="",this.alternateInvocationId="",this.parentResponse="",this.comparisonConfigId="",this.alternateModelId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ec,t,r)}static $(){return["ResponseComparisonStarted|1 display_order #0|2 parent_invocation_id 9|3 alternate_invocation_id 9|4 parent_response 9|5 comparison_config_id 9|6 alternate_model_id 9",so]}}class nc extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nc,t,r)}static $(){return["ResponseComparisonTextDelta|1 text 9"]}}class sc extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sc,t,r)}static $(){return["ResponseComparisonCompleted"]}}class ic extends Fi{constructor(t){super(),this.reason=io.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ic,t,r)}static $(){return["ResponseComparisonSkipped|1 reason #0",io]}}class oc extends Fi{constructor(t){super(),this.comparisonId="",this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oc,t,r)}static $(){return["ResponseComparisonUpdate|1 comparison_id 9|2 started #0 event|3 text_delta #1 event|4 completed #2 event|5 skipped #3 event",ec,nc,sc,ic]}}class ac extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ac).fromBinary(t,r)}static fromJson(t,r){return(new ac).fromJson(t,r)}static fromJsonString(t,r){return(new ac).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ac,t,r)}static $(){return["InteractionUpdate|1 text_delta #0 message|7 partial_tool_call #1 message|15 tool_call_delta #2 message|2 tool_call_started #3 message|3 tool_call_completed #4 message|4 thinking_delta #5 message|5 thinking_completed #6 message|6 user_message_appended #7 message|8 token_delta #8 message|9 summary #9 message|10 summary_started #10 message|11 summary_completed #11 message|12 shell_output_delta #12 message|13 heartbeat #13 message|14 turn_ended #14 message|16 step_started #15 message|17 step_completed #16 message|27 tool_requests_listed #17 message|19 post_request_prompt #18 message|20 active_branch_change #19 message|21 feedback_request #20 message|22 response_comparison #21 message|23 context_injection_state #22 message|24 routed_model #23 message|26 grok_bot_nudge #24 message|28 thinking_note #25 message|30 voice_call_utterance #26 message|31 model_call_completed #27 message|25 message_started_at_ms 4?",ku,Au,Uu,Cu,Tu,$u,Mu,Hu,Du,Nu,Gu,Fu,Ku,Lu,zu,Wu,Vu,Qu,cc,Yu,rc,oc,uc,Eu,lc,Ou,Su,Xu]}}class uc extends Fi{constructor(t){super(),this.injectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uc).fromBinary(t,r)}static fromJson(t,r){return(new uc).fromJson(t,r)}static fromJsonString(t,r){return(new uc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uc,t,r)}static $(){return["ContextInjectionStateUpdate|1 injection_id 9|2 state #0",la]}}class cc extends Fi{constructor(t){super(),this.title="",this.message="",this.buttonLabel="",this.buttonUrl="",this.buttonAction=oo.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cc,t,r)}static $(){return["PostRequestPromptUpdate|1 title 9|2 message 9|3 button_label 9|4 button_url 9|5 button_action #0",oo]}}class lc extends Fi{constructor(t){super(),this.job="",this.description="",this.showNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lc,t,r)}static $(){return["GrokBotNudgeUpdate|1 job 9|2 description 9|3 show_number 13"]}}class mc extends Fi{constructor(t){super(),this.id=0,this.query={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mc,t,r)}static $(){return["InteractionQuery|1 id 13|2 web_search_request_query #0 query|3 ask_question_interaction_query #1 query|4 switch_mode_request_query #2 query|7 create_plan_request_query #3 query|8 setup_vm_environment_args #4 query|9 web_fetch_request_query #5 query|10 pr_management_request_query #6 query|11 mcp_auth_request_query #7 query|12 generate_image_request_query #8 query|13 replace_env_args #9 query|14 connect_scm_request_query #10 query",_t.KL,dc,bt.Nc,gt.vR,Gt.BI,tr.Un,nr.DY,sr.uL,Rt.Uj,Fr.TO,Ie.$1]}}class fc extends Fi{constructor(t){super(),this.id=0,this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fc,t,r)}static $(){return["InteractionResponse|1 id 13|2 web_search_request_response #0 result|3 ask_question_interaction_response #1 result|4 switch_mode_request_response #2 result|7 create_plan_request_response #3 result|8 setup_vm_environment_result #4 result|9 web_fetch_request_response #5 result|10 pr_management_result #6 result|11 mcp_auth_request_response #7 result|12 generate_image_request_response #8 result|13 replace_env_result #9 result|14 connect_scm_request_response #10 result",_t.lI,pc,bt.w$,gt.gz,Gt.r$,tr.fS,nr.HL,sr.h,Rt.vW,Fr.dV,Ie.qG]}}class dc extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dc,t,r)}static $(){return["AskQuestionInteractionQuery|1 args #0|2 tool_call_id 9",qt.ju]}}class pc extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pc,t,r)}static $(){return["AskQuestionInteractionResponse|1 result #0",qt.tz]}}},"../proto/dist/generated/agent/v1/agent_service_connect.js"(t,r,e){e.d(r,{N:()=>o});var n=e("../proto/dist/generated/agent/v1/agent_service_pb.js"),s=e("@bufbuild/protobuf"),i=e("../proto/dist/generated/aiserver/v1/bidi_pb.js");const o={typeName:"agent.v1.AgentService",methods:{run:{name:"Run",I:n.KS,O:n.Oy,kind:s.MethodKind.BiDiStreaming},runSSE:{name:"RunSSE",I:i.$r,O:n.Oy,kind:s.MethodKind.ServerStreaming},runPoll:{name:"RunPoll",I:i.hD,O:i.xy,kind:s.MethodKind.ServerStreaming},nameAgent:{name:"NameAgent",I:n.Il,O:n.mw,kind:s.MethodKind.Unary},updateConversationMetadata:{name:"UpdateConversationMetadata",I:n.vw,O:n.HJ,kind:s.MethodKind.Unary},createTranscriptOverview:{name:"CreateTranscriptOverview",I:n.BU,O:n.Hi,kind:s.MethodKind.Unary},getUsableModels:{name:"GetUsableModels",I:n.KD,O:n.sY,kind:s.MethodKind.Unary},getDefaultModelForCli:{name:"GetDefaultModelForCli",I:n.Tu,O:n.pe,kind:s.MethodKind.Unary},getAllowedModelIntents:{name:"GetAllowedModelIntents",I:n.Ov,O:n.k4,kind:s.MethodKind.Unary},uploadConversationBlobs:{name:"UploadConversationBlobs",I:n.yD,O:n.W$,kind:s.MethodKind.Unary},uploadLocalAgentRunToPromptQuality:{name:"UploadLocalAgentRunToPromptQuality",I:n.uK,O:n.eE,kind:s.MethodKind.Unary},getSignedUrlForAttachedMedia:{name:"GetSignedUrlForAttachedMedia",I:n.W3,O:n.wq,kind:s.MethodKind.Unary},notifyConversationClone:{name:"NotifyConversationClone",I:n.xk,O:n.JF,kind:s.MethodKind.Unary},warmUp:{name:"WarmUp",I:n.EC,O:n.M2,kind:s.MethodKind.Unary},getNewChatNudgeLegacyModelPicker:{name:"GetNewChatNudgeLegacyModelPicker",I:n.Pg,O:n.zP,kind:s.MethodKind.Unary},getNewChatNudgeParameterizedModelPicker:{name:"GetNewChatNudgeParameterizedModelPicker",I:n.hs,O:n.TW,kind:s.MethodKind.Unary},getPromptContextUsage:{name:"GetPromptContextUsage",I:n.Y3,O:n.KE,kind:s.MethodKind.Unary},listLocalSubscriptionTools:{name:"ListLocalSubscriptionTools",I:n.dw,O:n.JH,kind:s.MethodKind.Unary},callLocalSubscriptionTool:{name:"CallLocalSubscriptionTool",I:n.uw,O:n.uu,kind:s.MethodKind.Unary},streamLocalAgentMailbox:{name:"StreamLocalAgentMailbox",I:n.k5,O:n.ic,kind:s.MethodKind.ServerStreaming}}}},"../proto/dist/generated/agent/v1/agent_service_pb.js"(t,r,e){e.d(r,{BU:()=>v,EC:()=>j,HJ:()=>P,Hi:()=>x,Il:()=>q,JF:()=>z,JH:()=>et,KD:()=>k,KE:()=>R,KS:()=>J,M2:()=>H,Ov:()=>U,Oy:()=>S,Pg:()=>W,TW:()=>gt,Tu:()=>C,W$:()=>O,W3:()=>L,Y3:()=>b,dw:()=>tt,eE:()=>G,hs:()=>ht,ic:()=>pt,k4:()=>A,k5:()=>ut,kA:()=>g,mw:()=>B,pe:()=>T,sY:()=>E,uK:()=>N,uu:()=>st,uw:()=>nt,vw:()=>I,wq:()=>F,xk:()=>K,yD:()=>M,zP:()=>Q});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/agent_pb.js"),i=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),o=e("../proto/dist/generated/agent/v1/mcp_pb.js"),a=e("../proto/dist/generated/agent/v1/exec_pb.js"),u=e("../proto/dist/generated/agent/v1/kv_pb.js"),c=e("../proto/dist/runtime/compact.js");const l="agent.v1.";class m extends c.HL{static get runtime(){return(0,c.kU)(this,"runtime",n.proto3)}static $p(){return l}}var f=(0,c.QT)(n.proto3,l,"NameAgentKind",[[0,"UNSPECIFIED"],[1,"PROJECT"]],1),d=(0,c.QT)(n.proto3,l,"LocalPromptQualityInvocationStatus",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ERRORED"],[3,"ABORTED"]],1),p=(0,c.QT)(n.proto3,l,"LocalAgentMailboxGapReason",[[0,"UNSPECIFIED"],[1,"TRIMMED"],[2,"LOST"]],1),h=(0,c.QT)(n.proto3,l,"LocalAgentMailboxEndedReason",[[0,"UNSPECIFIED"],[1,"NO_ACTIVE_SUBSCRIPTIONS"],[2,"STORE_DELETED"],[3,"MIGRATED_TO_CLOUD"]],1);class g extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ClientHeartbeat"]}}class _ extends m{constructor(t){super(),this.selectedSubagentModels=[],this.selectedSubagentModelDetails=[],this.preFetchedBlobs=[],this.subagentModelOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["PrewarmRequest|1 model_details #0|9 requested_model #1?|2 conversation_id 9?|3 conversation_state #2|4 mcp_tools #3|5 mcp_file_system_options #4?|6 best_of_n_group_id 9?|7 try_use_best_of_n_promotion 8?|8 custom_system_prompt 9?|11 subagent_type_name 9?|12 exclude_workspace_context 8?|13 harness 9?|14 selected_subagent_models #1*|15 selected_subagent_model_details #0*|16 conversation_group_id 9?|17 pre_fetched_blobs #5*|18 client_supports_inline_images 8?|19 subagent_model_overrides #6*|20 can_create_cloud_subagents 8?|21 suppress_subagent_progress_update_tool 8?|22 client_supports_send_to_user 8?|23 computer_use_coordinate_mode 9?|24 agent_session_id 9?|26 client_supports_routed_model_update 8?|27 client_llm_gateway_credential #7?|28 client_supports_preview_card 8?|29 started_as_new_project 8?|30 first_project_onboarding 8?",s.Gmx,i.G4,s.Y9z,o.Or,o.Is,s.onr,s.Bjv,s.Ibo]}}class J extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["AgentClientMessage|1 run_request #0 message|2 exec_client_message #1 message|5 exec_client_control_message #2 message|3 kv_client_message #3 message|4 conversation_action #4 message|6 interaction_response #5 message|7 client_heartbeat #6 message|8 prewarm_request #7 message",s.Mpn,a.yT,a.$Y,u.gm,s.QFf,s.Y5,g,_]}}class w extends m{constructor(t){super(),this.serverFirstTokenMs=0,this.preStreamSetupMs=0,this.waitForFirstEventMs=0,this.slowPoolWaitMs=0,this.clientClock=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["TtftBreakdown|1 server_first_token_ms 1|2 pre_stream_setup_ms 1|3 wait_for_first_event_ms 1|4 provider_ttft_ms 1?|5 slow_pool_wait_ms 1|6 client_prep_ms 1?|7 client_clock 8|8 pre_handler_ms 1?|9 client_prep_legs #0?",y]}}class y extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["TtftClientPrepLegs|1 state_restore_ms 1?|2 root_prompt_restore_ms 1?|3 request_context_ms 1?|4 system_prompt_ms 1?|5 pre_turn_snapshot_ms 1?|6 pre_turn_snapshot_wait_ms 1?|7 pre_turn_snapshot_blob_writes_ms 1?|8 pre_turn_snapshot_serialize_ms 1?|9 first_step_to_first_invocation_ms 1?|10 prompt_message_count 13?|11 turn_count 13?"]}}class S extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["AgentServerMessage|1 interaction_update #0 message|2 exec_server_message #1 message|5 exec_server_control_message #2 message|3 conversation_checkpoint_update #3 message|4 kv_server_message #4 message|7 interaction_query #5 message|8 ttft_breakdown #6",s.Uq,a.Ye,a.Nv,s.Y9z,u.km,s.Pd7,w]}}class q extends m{constructor(t){super(),this.userMessage="",this.kind=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["NameAgentRequest|1 user_message 9|2 kind #0",f]}}class B extends m{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["NameAgentResponse|1 name 9"]}}class I extends m{constructor(t){super(),this.conversationId="",this.workspacePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["UpdateConversationMetadataRequest|1 conversation_id 9|2 name 9?|3 only_set_name_if_empty 8?|4 workspace_paths 9*"]}}class P extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["UpdateConversationMetadataResponse"]}}class b extends m{constructor(t){super(),this.conversationId="",this.rootPromptMessagesJson=[],this.selfContained=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["GetPromptContextUsageRequest|1 conversation_id 9|3 root_prompt_messages_json 12*|5 self_contained 8"]}}class R extends m{constructor(t){super(),this.unavailableBlobCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["GetPromptContextUsageResponse|2 unavailable_blob_count 13|3 tree #0",s.d2k]}}class v extends m{constructor(t){super(),this.formattedConversation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["CreateTranscriptOverviewRequest|1 formatted_conversation 9"]}}class x extends m{constructor(t){super(),this.overview="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["CreateTranscriptOverviewResponse|1 overview 9"]}}class k extends m{constructor(t){super(),this.customModelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["GetUsableModelsRequest|1 custom_model_ids 9*"]}}class E extends m{constructor(t){super(),this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["GetUsableModelsResponse|1 models #0*",s.Gmx]}}class C extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["GetDefaultModelForCliRequest"]}}class T extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["GetDefaultModelForCliResponse|1 model #0",s.Gmx]}}class U extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["GetAllowedModelIntentsRequest"]}}class A extends m{constructor(t){super(),this.modelIntents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["GetAllowedModelIntentsResponse|1 model_intents 9*"]}}class $ extends m{constructor(t){super(),this.id=new Uint8Array(0),this.value=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["BlobEntry|1 id 12|2 value 12"]}}class M extends m{constructor(t){super(),this.conversationId="",this.blobs=[],this.chunkIndex=0,this.totalChunks=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["UploadConversationBlobsRequest|1 conversation_id 9|2 blobs #0*|3 chunk_index 5|4 total_chunks 5",$]}}class O extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["UploadConversationBlobsResponse"]}}class D extends m{constructor(t){super(),this.invocationId="",this.attemptRequestId="",this.attempt=0,this.startedAt="",this.completedAt="",this.modelId="",this.providerName="",this.status=d.UNSPECIFIED,this.messages=[],this.responseMessages=[],this.toolsJson="",this.promptTokens=n.protoInt64.zero,this.completionTokens=n.protoInt64.zero,this.totalTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["LocalPromptQualityInvocation|1 invocation_id 9|2 attempt_request_id 9|3 attempt 5|4 started_at 9|5 completed_at 9|6 model_id 9|7 provider_name 9|8 status #0|9 messages 12*|10 response_messages 12*|11 tools_json 9|12 prompt_tokens 3|13 completion_tokens 3|14 total_tokens 3|15 token_limit 3?|16 error_message 9?|17 prompt_tag 9?|18 feature_type 9?",d]}}class N extends m{constructor(t){super(),this.schemaVersion=0,this.generationUuid="",this.conversationId="",this.payloadDigest="",this.invocations=[],this.terminalStatus=d.UNSPECIFIED,this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["UploadLocalAgentRunToPromptQualityRequest|1 schema_version 5|2 generation_uuid 9|3 conversation_id 9|4 payload_digest 9|5 invocations #0*|6 terminal_status #1|7 created_at 9",D,d]}}class G extends m{constructor(t){super(),this.requestId="",this.primaryInvocationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["UploadLocalAgentRunToPromptQualityResponse|1 request_id 9|2 primary_invocation_id 9"]}}class L extends m{constructor(t){super(),this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["GetSignedUrlForAttachedMediaRequest|3 conversation_id 9|1 key 9?|2 mime_type 9?|4 content_length_bytes 3?"]}}class F extends m{constructor(t){super(),this.key="",this.postUrl="",this.getUrl="",this.expiresAtUnixMs=n.protoInt64.zero,this.refreshAfterUnixMs=n.protoInt64.zero,this.postFields={},this.putUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["GetSignedUrlForAttachedMediaResponse|1 key 9|2 post_url 9|3 get_url 9|4 expires_at_unix_ms 3|5 refresh_after_unix_ms 3|6 post_fields 9,9|7 put_url 9"]}}class K extends m{constructor(t){super(),this.conversationId="",this.sourceConversationId="",this.sourceRequestId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["NotifyConversationCloneRequest|1 conversation_id 9|2 source_conversation_id 9|3 source_request_id 9"]}}class z extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["NotifyConversationCloneResponse"]}}class j extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["WarmUpRequest"]}}class H extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["WarmUpResponse"]}}class W extends m{constructor(t){super(),this.currentModel="",this.maxMode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["GetNewChatNudgeLegacyModelPickerRequest|1 current_model 9|2 max_mode 8"]}}class Q extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["GetNewChatNudgeLegacyModelPickerResponse|1 nudge #0?",Z]}}class V extends m{constructor(t){super(),this.bannerMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["NudgeBumpVariant|1 banner_message 9|2 banner_description 9?"]}}class X extends m{constructor(t){super(),this.popupMessage="",this.acceptLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["NudgeAskVariant|1 popup_message 9|2 accept_label 9"]}}class Y extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["NudgeSilentSwitchVariant"]}}class Z extends m{constructor(t){super(),this.nudgeId="",this.targetModel="",this.experimentName="",this.variant={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["NewChatNudge|1 nudge_id 9|2 target_model 9|3 experiment_name 9|4 bump #0 variant|5 ask #1 variant|6 silent_switch #2 variant",V,X,Y]}}class tt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["ListLocalSubscriptionToolsRequest"]}}class rt extends m{constructor(t){super(),this.toolName="",this.description="",this.inputSchemaJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["LocalSubscriptionToolDefinition|1 tool_name 9|2 description 9|3 input_schema_json 9"]}}class et extends m{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["ListLocalSubscriptionToolsResponse|1 tools #0*",rt]}}class nt extends m{constructor(t){super(),this.conversationId="",this.toolName="",this.toolArgsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["CallLocalSubscriptionToolRequest|1 conversation_id 9|2 tool_name 9|3 tool_args_json 9"]}}class st extends m{constructor(t){super(),this.resultJson="",this.isError=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["CallLocalSubscriptionToolResponse|1 result_json 9|2 is_error 8|3 watch_expires_at_unix_ms 3?"]}}class it extends m{constructor(t){super(),this.subscriptionId="",this.eventId="",this.inboxRelPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["SubscriptionDeliveryEntry|1 subscription_id 9|2 event_id 9|3 inbox_rel_path 9"]}}class ot extends m{constructor(t){super(),this.subscriptionId="",this.inboxRelPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["SubscriptionRemovedEntry|1 subscription_id 9|2 inbox_rel_path 9"]}}class at extends m{constructor(t){super(),this.localAgentMailboxEntryId="",this.payload={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["LocalAgentMailboxEntry|1 local_agent_mailbox_entry_id 9|2 subscription_delivery #0 payload|3 subscription_removed #1 payload",it,ot]}}class ut extends m{constructor(t){super(),this.conversations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["StreamLocalAgentMailboxRequest|1 conversations #0*",ct]}}class ct extends m{constructor(t){super(),this.conversationId="",this.afterOffset="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["StreamLocalAgentMailboxRequest.ConversationCursor|1 conversation_id 9|2 after_offset 9"]}}class lt extends m{constructor(t){super(),this.conversationId="",this.offset="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["LocalAgentMailboxDelivery|1 conversation_id 9|2 offset 9|3 entry #0",at]}}class mt extends m{constructor(t){super(),this.conversationId="",this.afterOffset="",this.resumeOffset="",this.reason=p.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["LocalAgentMailboxGap|1 conversation_id 9|2 after_offset 9|3 resume_offset 9|4 reason #0",p]}}class ft extends m{constructor(t){super(),this.conversationId="",this.reason=h.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["LocalAgentMailboxEnded|1 conversation_id 9|2 reason #0",h]}}class dt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["StreamLocalAgentMailboxHeartbeat"]}}class pt extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["StreamLocalAgentMailboxResponse|1 delivery #0 message|2 heartbeat #1 message|3 gap #2 message|4 ended #3 message",lt,dt,mt,ft]}}class ht extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["GetNewChatNudgeParameterizedModelPickerRequest|1 current_model #0|2 model_nudges_enabled 8?",i.G4]}}class gt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["GetNewChatNudgeParameterizedModelPickerResponse|1 nudge #0?",_t]}}class _t extends m{constructor(t){super(),this.nudgeId="",this.experimentName="",this.variant={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["NewChatNudgeV2|1 nudge_id 9|2 target_model #0|3 experiment_name 9|4 bump #1 variant|5 ask #2 variant|6 silent_switch #3 variant",i.G4,V,X,Y]}}},"../proto/dist/generated/agent/v1/agent_skills_pb.js"(t,r,e){e.d(r,{N:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.fullPath="",this.content="",this.description="",this.environments=[],this.disabledEnvironments=[],this.disableModelInvocation=!1,this.globs=[],this.scopedTo=[],this.argumentHint="",this.disableUserInvocation=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AgentSkill|1 full_path 9|2 content 9|3 description 9|4 parse_error 9?|5 environments 9*|6 disabled_environments 9*|7 git_remote_origin 9?|8 disable_model_invocation 8|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 globs 9*|14 scoped_to 9*|15 argument_hint 9|16 disable_user_invocation 8"]}}},"../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js"(t,r,e){e.d(r,{Ev:()=>c,LK:()=>o,RZ:()=>u,Uz:()=>a,h6:()=>m,iS:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.journalEpoch="",this.seq=n.protoInt64.zero,this.lastEventId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AgentStoreConflictCursor|1 journal_epoch 9|2 seq 4|3 last_event_id 9"]}}class a extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AgentStoreConflictArgs|1 cursor #0?|2 advance 8?|3 include_quota_notices 8?",o]}}class u extends i{constructor(t){super(),this.v=0,this.eventId="",this.journalEpoch="",this.seq=n.protoInt64.zero,this.tsMs=n.protoInt64.zero,this.kind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AgentStoreConflictEvent|1 v 13|2 event_id 9|3 journal_epoch 9|4 seq 4|5 ts_ms 4|6 kind 9|7 store_id 9?|8 original_rel_path 9?|9 conflict_rel_path 9?|10 original_abs_path 9?|11 conflict_abs_path 9?|12 preserved_bytes 4?|13 scope_kind 9?|14 limit_bytes 4?|15 usage_bytes 4?"]}}class c extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AgentStoreConflictResult|1 success #0 result|2 error #1 result",l,m]}}class l extends i{constructor(t){super(),this.events=[],this.gap=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AgentStoreConflictSuccess|1 events #0*|2 next_cursor #1|3 gap 8",u,o]}}class m extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AgentStoreConflictError|1 error 9"]}}},"../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"(t,r,e){e.d(r,{Zc:()=>u,ex:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.filePaths=[],this.commitHashes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AiAttributionArgs|5 file_paths 9*|2 start_line 5?|3 end_line 5?|6 commit_hashes 9*|7 output_mode 9?|9 max_commits 5?|10 include_line_ranges 8?"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AiAttributionResult|1 success #0 result|2 error #1 result",c,l]}}class c extends o{constructor(t){super(),this.attributionText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AiAttributionSuccess|1 attribution_text 9|2 output_location #0?",s.pV]}}class l extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AiAttributionError|1 error 9"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AiAttributionToolCall|1 args #0|2 result #1",a,u]}}},"../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"(t,r,e){e.d(r,{JU:()=>a,y$:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ApplyAgentDiffToolCall|1 args #0|2 result #1",u,c]}}class u extends o{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ApplyAgentDiffArgs|1 agent_id 9"]}}class c extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ApplyAgentDiffResult|1 success #0 result|2 error #1 result",l,d]}}class l extends o{constructor(t){super(),this.appliedChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ApplyAgentDiffSuccess|1 applied_changes #0*",m]}}class m extends o{constructor(t){super(),this.path="",this.changeType=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AppliedAgentChange|1 path 9|2 change_type #0|3 before_content 9?|4 after_content 9?|5 error 9?|6 message_for_model 9?",f]}}var f=(0,s.QT)(n.proto3,i,"AppliedAgentChange.ChangeType",[[0,"UNSPECIFIED"],[1,"CREATED"],[2,"MODIFIED"],[3,"DELETED"]],1);class d extends o{constructor(t){super(),this.error="",this.appliedChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ApplyAgentDiffError|1 error 9|2 applied_changes #0*",m]}}},"../proto/dist/generated/agent/v1/ask_question_tool_pb.js"(t,r,e){e.d(r,{OU:()=>o,ju:()=>a,ox:()=>h,tz:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AskQuestionToolCall|1 args #0|2 result #1",a,m]}}class a extends i{constructor(t){super(),this.title="",this.questions=[],this.runAsync=!1,this.asyncOriginalToolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AskQuestionArgs|1 title 9|2 questions #0*|5 run_async 8|6 async_original_tool_call_id 9",u]}}class u extends i{constructor(t){super(),this.id="",this.prompt="",this.options=[],this.allowMultiple=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AskQuestionArgs.Question|1 id 9|2 prompt 9|3 options #0*|4 allow_multiple 8|5 prompt_markdown 9?",c]}}class c extends i{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AskQuestionArgs.Option|1 id 9|2 label 9"]}}class l extends i{constructor(t){super(),this.interactionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AskQuestionAsync|1 interaction_id 9"]}}class m extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AskQuestionResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 async #3 result",f,p,h,l]}}class f extends i{constructor(t){super(),this.answers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["AskQuestionSuccess|1 answers #0*",d]}}class d extends i{constructor(t){super(),this.questionId="",this.selectedOptionIds=[],this.freeformText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["AskQuestionSuccess.Answer|1 question_id 9|2 selected_option_ids 9*|3 freeform_text 9"]}}class p extends i{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["AskQuestionError|1 error_message 9"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["AskQuestionRejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/background_shell_exec_pb.js"(t,r,e){e.d(r,{$P:()=>c,Gv:()=>g,LL:()=>d,Lt:()=>l,Of:()=>f,Po:()=>m,nt:()=>p,tR:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),o=e("../proto/dist/generated/agent/v1/utils_pb.js"),a=e("../proto/dist/runtime/compact.js");class u extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class c extends u{constructor(t){super(),this.command="",this.workingDirectory="",this.toolCallId="",this.enableWriteShellStdinTool=!1,this.skipApproval=!1,this.adminCommandDenylist=[],this.suppressStdinLogging=!1,this.smartModeClassifierAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["BackgroundShellSpawnArgs|1 command 9|2 working_directory 9|3 tool_call_id 9|4 parsing_result #0|5 sandbox_policy #1?|6 enable_write_shell_stdin_tool 8|7 description 9?|8 classifier_result #2?|9 output_notification #3?|10 smart_mode_approval #4?|11 hook_approval_requirement #5?|12 skip_approval 8|13 conversation_id 9?|14 admin_command_denylist 9*|15 request_id 9?|16 suppress_stdin_logging 8|17 secret_scope_id 9?|18 smart_mode_classifier_allowed 8|19 desktop_lease_actor_id 9?",s.HO,i.Mw,s.E4,s.$F,o.UC,s.In]}}class l extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BackgroundShellSpawnResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result|5 sandbox_unsupported #4 result",m,f,s.pZ,s.jn,s.rI]}}class m extends u{constructor(t){super(),this.shellId=0,this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["BackgroundShellSpawnSuccess|1 shell_id 13|2 command 9|3 working_directory 9|4 pid 13?"]}}class f extends u{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["BackgroundShellSpawnError|1 command 9|2 working_directory 9|3 error 9"]}}class d extends u{constructor(t){super(),this.shellId=0,this.chars="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WriteShellStdinArgs|1 shell_id 13|2 chars 9"]}}class p extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WriteShellStdinResult|1 success #0 result|2 error #1 result",h,g]}}class h extends u{constructor(t){super(),this.shellId=0,this.terminalFileLengthBeforeInputWritten=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WriteShellStdinSuccess|1 shell_id 13|2 terminal_file_length_before_input_written 13"]}}class g extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WriteShellStdinError|1 error 9"]}}},"../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"(t,r,e){e.d(r,{GL:()=>u,HW:()=>l,uX:()=>c,yN:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["CanvasDiagnosticsArgs|1 path 9|2 tool_call_id 9"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["CanvasDiagnosticsResult|1 success #0 result|2 error #1 result|3 canvas_id 9?|4 title 9?|5 save_state 9?|6 save_detail 9?",c,l]}}class c extends o{constructor(t){super(),this.path="",this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CanvasDiagnosticsSuccess|1 path 9|2 diagnostics #0*",s.oQ]}}class l extends o{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CanvasDiagnosticsError|1 path 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/computer_use_tool_pb.js"(t,r,e){e.d(r,{Dh:()=>u,EB:()=>c,Gx:()=>p,Jb:()=>C,K5:()=>f,OT:()=>d,Wd:()=>x,Z8:()=>l,ho:()=>g,ks:()=>v,qA:()=>E,t8:()=>T,w3:()=>a,xp:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"MouseButton",[[0,"UNSPECIFIED"],[1,"LEFT"],[2,"RIGHT"],[3,"MIDDLE"],[4,"BACK"],[5,"FORWARD"]],1),u=(0,s.QT)(n.proto3,i,"ScrollDirection",[[0,"UNSPECIFIED"],[1,"UP"],[2,"DOWN"],[3,"LEFT"],[4,"RIGHT"]],1),c=(0,s.QT)(n.proto3,i,"KeyStroke",[[0,"UNSPECIFIED"],[1,"TAP"],[2,"DOWN"],[3,"UP"]],1),l=(0,s.QT)(n.proto3,i,"ComputerUseDriver",[[0,"UNSPECIFIED"],[1,"XDOTOOL"],[2,"NATIVE_X11"]],1);class m extends o{constructor(t){super(),this.x=0,this.y=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["Coordinate|1 x 5|2 y 5"]}}class f extends o{constructor(t){super(),this.toolCallId="",this.actions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ComputerUseArgs|1 tool_call_id 9|2 actions #0*|3 description 9?|4 bind_unmapped_characters 8?|5 desktop_lease_actor_id 9?|6 screenshot_settle_ms 5?|10 native_x11_driver #1?|11 mark_monitor_busy 8?|9 full_resolution_screenshot 8?|12 capture_name_prefix 9?|13 omit_inline_screenshot 8?",g,h]}}class d extends o{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ComputerUseEndTurnArgs|1 bc_id 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ComputerUseEndTurnResult"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["NativeX11Driver|1 typing_delay_ms 5?|2 allow_fallback 8?"]}}class g extends o{constructor(t){super(),this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ComputerUseAction|1 mouse_move #0 action|2 click #1 action|3 mouse_down #2 action|4 mouse_up #3 action|5 drag #4 action|6 scroll #5 action|7 type #6 action|8 key #7 action|9 wait #8 action|10 screenshot #9 action|11 cursor_position #10 action",_,J,w,y,S,q,B,I,P,b,R]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["MouseMoveAction|1 coordinate #0",m]}}class J extends o{constructor(t){super(),this.button=a.UNSPECIFIED,this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ClickAction|1 coordinate #0?|2 button #1|3 count 5|4 modifier_keys 9?",m,a]}}class w extends o{constructor(t){super(),this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["MouseDownAction|1 button #0",a]}}class y extends o{constructor(t){super(),this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["MouseUpAction|1 button #0",a]}}class S extends o{constructor(t){super(),this.path=[],this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["DragAction|1 path #0*|2 button #1|3 modifier_keys 9?",m,a]}}class q extends o{constructor(t){super(),this.direction=u.UNSPECIFIED,this.amount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ScrollAction|1 coordinate #0?|2 direction #1|3 amount 5|4 modifier_keys 9?",m,u]}}class B extends o{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["TypeAction|1 text 9"]}}class I extends o{constructor(t){super(),this.key="",this.stroke=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["KeyAction|1 key 9|2 hold_duration_ms 5?|3 stroke #0",c]}}class P extends o{constructor(t){super(),this.durationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["WaitAction|1 duration_ms 5"]}}class b extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ScreenshotAction"]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["CursorPositionAction"]}}class v extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ComputerUseResult|1 success #0 result|2 error #1 result",x,C]}}class x extends o{constructor(t){super(),this.actionCount=0,this.durationMs=0,this.typing=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ComputerUseSuccess|1 action_count 5|2 duration_ms 5|3 screenshot 9?|4 log 9?|5 screenshot_path 9?|6 cursor_position #0?|7 settle_ms 5?|9 driver #1?|10 monitor_busy_marked 8?|11 full_resolution_screenshot #2?|12 typing #3*",m,l,k,E]}}class k extends o{constructor(t){super(),this.path="",this.sha256="",this.sizeBytes=0,this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ComputerUseFullResolutionScreenshot|1 path 9|2 sha256 9|3 size_bytes 13|4 width 5|5 height 5"]}}class E extends o{constructor(t){super(),this.method="",this.chars=0,this.atoms=0,this.typedAtoms=0,this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ComputerUseTyping|1 method 9|2 chars 5|3 atoms 5|4 typed_atoms 5|5 aborted 8|6 check 9?|7 verified 5?|8 unchecked 9?|9 landing 9?"]}}class C extends o{constructor(t){super(),this.error="",this.actionCount=0,this.durationMs=0,this.typing=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ComputerUseError|1 error 9|2 action_count 5|3 duration_ms 5|4 log 9?|5 screenshot 9?|6 screenshot_path 9?|7 driver #0?|8 monitor_busy_marked 8?|9 typing #1*",l,E]}}class T extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ComputerUseToolCall|1 args #0|2 result #1",f,v]}}},"../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"(t,r,e){e.d(r,{$1:()=>_,O9:()=>w,iO:()=>g,ik:()=>S,lB:()=>y,qG:()=>J});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.toolCallId="",this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ConnectScmArgs|1 tool_call_id 9|2 github #0 target|3 gitlab #1 target|4 bitbucket #2 target|5 azure_devops #3 target|6 reconnect 8?|7 repo_url 9?|8 instance_host 9?",l,a,u,c]}}class a extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ConnectScmGitlab|1 instance_id 9?"]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ConnectScmBitbucket|1 instance_id 9?"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ConnectScmAzureDevops"]}}class l extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ConnectScmGithub|1 repository #0|2 ghe_application 9?",m]}}class m extends i{constructor(t){super(),this.owner="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ConnectScmGithubRepository|1 owner 9|2 repo 9"]}}class f extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ConnectScmResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 scm_target 9?",d,p,h]}}class d extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ConnectScmSuccess"]}}class p extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ConnectScmError|1 error 9"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ConnectScmRejected|1 reason 9"]}}class g extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ConnectScmToolCall|1 args #0|2 result #1",o,f]}}class _ extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ConnectScmRequestQuery|1 args #0",o]}}class J extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ConnectScmRequestResponse|1 approved #0 result|2 rejected #1 result|3 failed #2 result",w,y,S]}}class w extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ConnectScmRequestResponse.Approved|1 scm_target 9?"]}}class y extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["ConnectScmRequestResponse.Rejected|1 reason 9|2 recorded_args #0?",o]}}class S extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ConnectScmRequestResponse.Failed|1 error 9"]}}},"../proto/dist/generated/agent/v1/conversation_search_exec_pb.js"(t,r,e){e.d(r,{$m:()=>u,pT:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ConversationSearchSource",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD_CACHE"]],1);class u extends o{constructor(t){super(),this.query="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ConversationSearchArgs|1 query 9|2 tool_call_id 9|3 limit 5?"]}}class c extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ConversationSearchResult|1 success #0 result|2 error #1 result",l,f]}}class l extends o{constructor(t){super(),this.hits=[],this.truncated=!1,this.partial=!1,this.rebuilding=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ConversationSearchSuccess|1 hits #0*|2 truncated 8|3 partial 8|4 rebuilding 8",m]}}class m extends o{constructor(t){super(),this.conversationId="",this.title="",this.source=a.UNSPECIFIED,this.updatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ConversationSearchHit|1 conversation_id 9|2 title 9|3 source #0|4 updated_at_ms 3|5 snippet 9?",a]}}class f extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ConversationSearchError|1 error 9"]}}},"../proto/dist/generated/agent/v1/create_plan_tool_pb.js"(t,r,e){e.d(r,{Ih:()=>a,Jo:()=>m,bK:()=>l,gz:()=>p,iY:()=>f,vR:()=>d});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/todo_tool_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["CreatePlanToolCall|1 args #0|2 result #1",c,l]}}class u extends o{constructor(t){super(),this.name="",this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["Phase|1 name 9|2 todos #0*",s.kW]}}class c extends o{constructor(t){super(),this.plan="",this.todos=[],this.overview="",this.name="",this.isProject=!1,this.phases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CreatePlanArgs|1 plan 9|2 todos #0*|3 overview 9|4 name 9|5 is_project 8|6 phases #1*",s.kW,u]}}class l extends o{constructor(t){super(),this.result={case:void 0},this.planUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CreatePlanResult|1 success #0 result|2 error #1 result|3 plan_uri 9",m,f]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CreatePlanSuccess"]}}class f extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["CreatePlanError|1 error 9"]}}class d extends o{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["CreatePlanRequestQuery|1 args #0|2 tool_call_id 9",c]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["CreatePlanRequestResponse|1 result #0",l]}}},"../proto/dist/generated/agent/v1/cursor_rules_pb.js"(t,r,e){e.d(r,{DX:()=>d,Xo:()=>l,_u:()=>m,f5:()=>f,gv:()=>a,i9:()=>u,uT:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"CursorRuleSource",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1);class u extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["CursorRuleTypeGlobal"]}}class c extends o{constructor(t){super(),this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CursorRuleTypeFileGlobs|1 globs 9*"]}}class l extends o{constructor(t){super(),this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CursorRuleTypeAgentFetched|1 description 9"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CursorRuleTypeManuallyAttached"]}}class f extends o{constructor(t){super(),this.type={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["CursorRuleType|1 global #0 type|2 file_globbed #1 type|3 agent_fetched #2 type|4 manually_attached #3 type",u,c,l,m]}}class d extends o{constructor(t){super(),this.fullPath="",this.content="",this.source=a.UNSPECIFIED,this.environments=[],this.disabledEnvironments=[],this.scopedTo=[],this.frontmatter="",this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["CursorRule|1 full_path 9|2 content 9|3 type #0|4 source #1|5 git_remote_origin 9?|6 parse_error 9?|7 environments 9*|8 disabled_environments 9*|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 scoped_to 9*|14 frontmatter 9|15 is_required 8?|16 warnings 9*|17 body_omitted 8?",f,a]}}},"../proto/dist/generated/agent/v1/delete_exec_pb.js"(t,r,e){e.d(r,{GU:()=>p,LX:()=>l,Pi:()=>a,QG:()=>m,dn:()=>o,fl:()=>u,iq:()=>d,n0:()=>c,vX:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["DeleteArgs|1 path 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["DeleteResult|1 success #0 result|2 file_not_found #1 result|3 not_file #2 result|4 permission_denied #3 result|5 file_busy #4 result|6 rejected #5 result|7 error #6 result",u,c,l,m,f,d,p]}}class u extends i{constructor(t){super(),this.path="",this.deletedFile="",this.fileSize=n.protoInt64.zero,this.prevContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["DeleteSuccess|1 path 9|2 deleted_file 9|3 file_size 3|4 prev_content 9"]}}class c extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["DeleteFileNotFound|1 path 9"]}}class l extends i{constructor(t){super(),this.path="",this.actualType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["DeleteNotFile|1 path 9|2 actual_type 9"]}}class m extends i{constructor(t){super(),this.path="",this.clientVisibleError="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["DeletePermissionDenied|1 path 9|2 client_visible_error 9|3 is_readonly 8"]}}class f extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["DeleteFileBusy|1 path 9"]}}class d extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["DeleteRejected|1 path 9|2 reason 9"]}}class p extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DeleteError|1 path 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"(t,r,e){e.d(r,{Ek:()=>l,Ho:()=>d,J6:()=>p,Mu:()=>h,RP:()=>g,_B:()=>c,a1:()=>m,h_:()=>u,oQ:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");const o="agent.v1.";class a extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return o}}var u=(0,i.QT)(n.proto3,o,"DiagnosticSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFORMATION"],[4,"HINT"]],1);class c extends a{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["DiagnosticsArgs|1 path 9|2 tool_call_id 9"]}}class l extends a{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["DiagnosticsResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 file_not_found #3 result|5 permission_denied #4 result",m,d,p,h,g]}}class m extends a{constructor(t){super(),this.path="",this.diagnostics=[],this.totalDiagnostics=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["DiagnosticsSuccess|1 path 9|2 diagnostics #0*|3 total_diagnostics 5",f]}}class f extends a{constructor(t){super(),this.severity=u.UNSPECIFIED,this.message="",this.source="",this.code="",this.isStale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["Diagnostic|1 severity #0|2 range #1|3 message 9|4 source 9|5 code 9|6 is_stale 8",u,s.Q6]}}class d extends a{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["DiagnosticsError|1 path 9|2 error 9"]}}class p extends a{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DiagnosticsRejected|1 path 9|2 reason 9"]}}class h extends a{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["DiagnosticsFileNotFound|1 path 9"]}}class g extends a{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["DiagnosticsPermissionDenied|1 path 9"]}}},"../proto/dist/generated/agent/v1/exec_pb.js"(t,r,e){e.d(r,{$Y:()=>T,D9:()=>k,Fu:()=>E,Kg:()=>$,Nv:()=>A,S1:()=>N,VA:()=>C,Ye:()=>M,w5:()=>L,yT:()=>O});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/generated/agent/v1/write_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/delete_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/grep_exec_pb.js"),u=e("../proto/dist/generated/agent/v1/read_exec_pb.js"),c=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),l=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),m=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),f=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),d=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),p=e("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),h=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),g=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),_=e("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),J=e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),w=e("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),y=e("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js"),S=e("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js"),q=e("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js"),B=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),I=e("../proto/dist/generated/agent/v1/conversation_search_exec_pb.js"),P=e("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js"),b=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),R=e("../proto/dist/generated/agent/v1/hooks_pb.js"),v=e("../proto/dist/runtime/compact.js");class x extends v.HL{static get runtime(){return(0,v.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class k extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ExecClientStreamClose|1 id 13"]}}class E extends x{constructor(t){super(),this.id=0,this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ExecClientThrow|1 id 13|2 error 9|3 stack_trace 9?|4 error_code 9?"]}}class C extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ExecClientHeartbeat|1 id 13"]}}class T extends x{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ExecClientControlMessage|1 stream_close #0 message|2 throw #1 message|3 heartbeat #2 message",k,E,C]}}class U extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ExecServerAbort|1 id 13"]}}class A extends x{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ExecServerControlMessage|1 abort #0 message",U]}}class $ extends x{constructor(t){super(),this.traceId="",this.spanId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["SpanContext|1 trace_id 9|2 span_id 9|3 trace_flags 13?|4 trace_state 9?"]}}class M extends x{constructor(t){super(),this.id=0,this.execId="",this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ExecServerMessage|1 id 13|15 exec_id 9|57 machine_id 9?|2 shell_args #0 message|3 write_args #1 message|4 delete_args #2 message|5 grep_args #3 message|7 read_args #4 message|29 redacted_read_args #4 message|8 ls_args #5 message|9 diagnostics_args #6 message|10 request_context_args #7 message|11 mcp_args #8 message|14 shell_stream_args #0 message|16 background_shell_spawn_args #9 message|17 list_mcp_resources_exec_args #10 message|18 read_mcp_resource_exec_args #11 message|36 mcp_state_exec_args #12 message|20 fetch_args #13 message|21 record_screen_args #14 message|22 computer_use_args #15 message|23 write_shell_stdin_args #16 message|27 execute_hook_args #17 message|28 subagent_args #18 message|30 force_background_shell_args #19 message|31 force_background_subagent_args #20 message|37 subagent_await_args #21 message|38 smart_mode_classifier_args #22 message|40 canvas_diagnostics_args #23 message|41 shell_allowlist_precheck_args #24 message|42 mcp_allowlist_precheck_args #25 message|43 web_fetch_allowlist_precheck_args #26 message|44 git_diff_request #27 message|52 mini_swe_agent_bash_args #0 message|53 conversation_search_args #28 message|54 agent_store_conflict_args #29 message|60 computer_use_end_turn_args #30 message|19 span_context #31?|55 accept_hook_additional_contexts 8?|58 record_agent_view 8?|59 refuse_unread_changes 8?",s.a,i.hY,o.dn,a.Qj,u.a2,c.xe,l._B,m._K,f.E_,d.$P,f.kj,f.DI,f.Km,p.UM,h.zH,g.K5,d.LL,D,_.Pw,s.Hu,_.S3,_.TN,J.Th,w.yN,y.C,S.c,q.K,B.Vq,I.$m,P.Uz,g.OT,$]}}class O extends x{constructor(t){super(),this.id=0,this.execId="",this.hookAdditionalContexts=[],this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ExecClientMessage|1 id 13|15 exec_id 9|39 local_execution_time_ms 5?|45 hook_additional_contexts #0*|2 shell_result #1 message|3 write_result #2 message|4 delete_result #3 message|5 grep_result #4 message|7 read_result #5 message|29 redacted_read_result #5 message|8 ls_result #6 message|9 diagnostics_result #7 message|10 request_context_result #8 message|11 mcp_result #9 message|14 shell_stream #10 message|16 background_shell_spawn_result #11 message|17 list_mcp_resources_exec_result #12 message|18 read_mcp_resource_exec_result #13 message|36 mcp_state_exec_result #14 message|20 fetch_result #15 message|21 record_screen_result #16 message|22 computer_use_result #17 message|23 write_shell_stdin_result #18 message|27 execute_hook_result #19 message|28 subagent_result #20 message|30 force_background_shell_result #21 message|31 force_background_subagent_result #22 message|37 subagent_await_result #23 message|38 smart_mode_classifier_result #24 message|40 canvas_diagnostics_result #25 message|41 shell_allowlist_precheck_result #26 message|42 mcp_allowlist_precheck_result #27 message|43 web_fetch_allowlist_precheck_result #28 message|44 git_diff_response #29 message|53 conversation_search_result #30 message|54 agent_store_conflict_result #31 message|55 mini_swe_agent_bash_result #1 message|57 computer_use_end_turn_result #32 message",b.C,s.W4,i.v3,o.Pi,a.Ud,u.sV,c.fv,l.Ek,m._G,f.iz,s.FI,d.Lt,f.kP,f.ZD,f._W,p.uN,h.Tj,g.ks,d.nt,N,_.vS,s.jK,_.a3,_.zJ,J.bN,w.GL,y.e,S.M,q.M,B.df,I.pT,P.Ev,g.Gx]}}class D extends x{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ExecuteHookArgs|1 request #0",G]}}class N extends x{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ExecuteHookResult|1 response #0",L]}}class G extends x{constructor(t){super(),this.request={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ExecuteHookRequest|1 pre_compact #0 request|2 subagent_start #1 request|3 subagent_stop #2 request|4 pre_tool_use #3 request|5 post_tool_use #4 request|6 post_tool_use_failure #5 request|7 before_submit_prompt #6 request|8 after_agent_response #7 request|9 after_agent_thought #8 request|11 stop #9 request",R.Ks,R.b3,R.ty,R.CI,R.rY,R.hy,R.D2,R.mL,R.AL,R.Od]}}class L extends x{constructor(t){super(),this.response={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ExecuteHookResponse|1 pre_compact #0 response|2 subagent_start #1 response|3 subagent_stop #2 response|4 pre_tool_use #3 response|5 post_tool_use #4 response|6 post_tool_use_failure #5 response|7 before_submit_prompt #6 response|8 after_agent_response #7 response|9 after_agent_thought #8 response|11 stop #9 response",R.$_,R.W0,R.AH,R.Wn,R.uB,R.U1,R.u1,R.FW,R.H,R.rT]}}},"../proto/dist/generated/agent/v1/fetch_exec_pb.js"(t,r,e){e.d(r,{UM:()=>o,Uk:()=>u,fk:()=>c,uN:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.url="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["FetchArgs|1 url 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["FetchResult|1 success #0 result|2 error #1 result",u,c]}}class u extends i{constructor(t){super(),this.url="",this.content="",this.statusCode=0,this.contentType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["FetchSuccess|1 url 9|2 content 9|3 status_code 5|4 content_type 9"]}}class c extends i{constructor(t){super(),this.url="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["FetchError|1 url 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/generate_image_tool_pb.js"(t,r,e){e.d(r,{Uj:()=>m,Uq:()=>p,k4:()=>a,l3:()=>d,r9:()=>l,vW:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.description="",this.referenceImagePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["GenerateImageArgs|1 description 9|2 file_path 9?|5 reference_image_paths 9*|6 aspect_ratio 9?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["GenerateImageResult|1 success #0 result|2 error #1 result",u,c]}}class u extends i{constructor(t){super(),this.filePath="",this.imageData="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GenerateImageSuccess|1 file_path 9|2 image_data 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GenerateImageError|1 error 9"]}}class l extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["GenerateImageToolCall|1 args #0|2 result #1",o,a]}}class m extends i{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["GenerateImageRequestQuery|1 args #0|2 tool_call_id 9",o]}}class f extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["GenerateImageRequestResponse|1 approved #0 result|2 rejected #1 result",d,p]}}class d extends i{constructor(t){super(),this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GenerateImageRequestResponse.Approved|1 description 9"]}}class p extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GenerateImageRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/grep_exec_pb.js"(t,r,e){e.d(r,{Qj:()=>a,T7:()=>p,Ud:()=>u,Zp:()=>h,_0:()=>l,dx:()=>_,sS:()=>d,ts:()=>c,uI:()=>g,vD:()=>m,xA:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.pattern="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["GrepArgs|1 pattern 9|2 path 9?|3 glob 9?|4 output_mode 9?|5 context_before 5?|6 context_after 5?|7 context 5?|8 case_insensitive 8?|9 type 9?|10 head_limit 5?|11 multiline 8?|12 sort 9?|13 sort_ascending 8?|14 tool_call_id 9|15 sandbox_policy #0?|16 offset 5?",s.Mw]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GrepResult|1 success #0 result|2 error #1 result",l,c]}}class c extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GrepError|1 error 9"]}}class l extends o{constructor(t){super(),this.pattern="",this.path="",this.outputMode="",this.workspaceResults={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["GrepSuccess|1 pattern 9|2 path 9|3 output_mode 9|4 workspace_results 9,#0|5 active_editor_result #0?",m]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["GrepUnionResult|1 count #0 result|2 files #1 result|3 content #2 result",f,p,h]}}class f extends o{constructor(t){super(),this.counts=[],this.totalFiles=0,this.totalMatches=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["GrepCountResult|1 counts #0*|2 total_files 5|3 total_matches 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",d]}}class d extends o{constructor(t){super(),this.file="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GrepFileCount|1 file 9|2 count 5"]}}class p extends o{constructor(t){super(),this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GrepFilesResult|1 files 9*|2 total_files 5|3 client_truncated 8|4 ripgrep_truncated 8|5 head_limit_applied 5?|6 offset_applied 5?"]}}class h extends o{constructor(t){super(),this.matches=[],this.totalLines=0,this.totalMatchedLines=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["GrepContentResult|1 matches #0*|2 total_lines 5|3 total_matched_lines 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",g]}}class g extends o{constructor(t){super(),this.file="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GrepFileMatch|1 file 9|2 matches #0*",_]}}class _ extends o{constructor(t){super(),this.lineNumber=0,this.content="",this.contentTruncated=!1,this.isContextLine=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["GrepContentMatch|1 line_number 5|2 content 9|3 content_truncated 8|4 is_context_line 8"]}}},"../proto/dist/generated/agent/v1/hook_additional_context_pb.js"(t,r,e){e.d(r,{C:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.hookEventName="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["HookAdditionalContext|1 hook_event_name 9|2 content 9"]}}},"../proto/dist/generated/agent/v1/hooks_pb.js"(t,r,e){e.d(r,{$_:()=>u,AH:()=>f,AL:()=>J,CI:()=>q,D2:()=>p,FW:()=>_,H:()=>w,Ks:()=>a,Od:()=>y,U1:()=>R,W0:()=>l,Wn:()=>B,b3:()=>c,hy:()=>b,mL:()=>g,rT:()=>S,rY:()=>I,ty:()=>m,u1:()=>h,uB:()=>P});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.trigger="",this.contextUsagePercent=0,this.contextTokens=n.protoInt64.zero,this.contextWindowSize=n.protoInt64.zero,this.messageCount=0,this.messagesToCompact=0,this.isFirstCompaction=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["PreCompactRequestQuery|1 trigger 9|2 context_usage_percent 1|3 context_tokens 3|4 context_window_size 3|5 message_count 5|6 messages_to_compact 5|7 is_first_compaction 8|8 conversation_id 9?|9 generation_id 9?|10 model 9?|11 model_id 9?|12 model_params #0*",s.SR]}}class u extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["PreCompactRequestResponse|1 user_message 9?"]}}class c extends o{constructor(t){super(),this.subagentId="",this.subagentType="",this.task="",this.parentConversationId="",this.isParallelWorker=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SubagentStartRequestQuery|1 subagent_id 9|2 subagent_type 9|3 task 9|4 parent_conversation_id 9|5 tool_call_id 9?|6 subagent_model 9?|7 is_parallel_worker 8|8 git_branch 9?|9 conversation_id 9?|10 generation_id 9?|11 model 9?|12 model_id 9?|13 model_params #0*",s.SR]}}class l extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SubagentStartRequestResponse|1 permission 9?|2 user_message 9?|3 additional_context 9?"]}}class m extends o{constructor(t){super(),this.subagentId="",this.subagentType="",this.status="",this.durationMs=n.protoInt64.zero,this.parentConversationId="",this.messageCount=0,this.toolCallCount=0,this.modifiedFiles=[],this.loopCount=0,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SubagentStopRequestQuery|1 subagent_id 9|2 subagent_type 9|3 status 9|4 duration_ms 3|5 summary 9?|6 parent_conversation_id 9|7 message_count 5|8 tool_call_count 5|9 error_message 9?|10 modified_files 9*|11 git_branch 9?|12 conversation_id 9?|13 generation_id 9?|14 model 9?|15 loop_count 5|16 task 9?|17 description 9?|18 model_id 9?|19 model_params #0*|20 child_conversation_id 9?",s.SR]}}class f extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SubagentStopRequestResponse|1 followup_message 9?|2 additional_context 9?"]}}class d extends o{constructor(t){super(),this.type="",this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["BeforeSubmitPromptAttachment|1 type 9|2 file_path 9"]}}class p extends o{constructor(t){super(),this.prompt="",this.attachments=[],this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["BeforeSubmitPromptRequestQuery|1 prompt 9|2 attachments #0*|3 composer_mode 9?|4 conversation_id 9?|5 generation_id 9?|6 model 9?|7 model_id 9?|8 model_params #1*",d,s.SR]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["BeforeSubmitPromptRequestResponse|1 continue 8?|2 user_message 9?|3 additional_context 9?"]}}class g extends o{constructor(t){super(),this.text="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["AfterAgentResponseRequestQuery|1 text 9|2 conversation_id 9?|3 generation_id 9?|4 model 9?|5 model_id 9?|6 model_params #0*|7 input_tokens 3?|8 output_tokens 3?|9 cache_read_tokens 3?|10 cache_write_tokens 3?",s.SR]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["AfterAgentResponseRequestResponse"]}}class J extends o{constructor(t){super(),this.text="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["AfterAgentThoughtRequestQuery|1 text 9|2 duration_ms 3?|3 conversation_id 9?|4 generation_id 9?|5 model 9?|6 model_id 9?|7 model_params #0*",s.SR]}}class w extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["AfterAgentThoughtRequestResponse"]}}class y extends o{constructor(t){super(),this.status="",this.loopCount=0,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["StopRequestQuery|1 status 9|2 loop_count 5|3 conversation_id 9?|4 generation_id 9?|5 model 9?|6 model_id 9?|7 model_params #0*|8 input_tokens 3?|9 output_tokens 3?|10 cache_read_tokens 3?|11 cache_write_tokens 3?",s.SR]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["StopRequestResponse|1 followup_message 9?"]}}class q extends o{constructor(t){super(),this.toolName="",this.toolUseId="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["PreToolUseRequestQuery|1 tool_name 9|2 tool_input #0|3 tool_use_id 9|4 cwd 9?|5 conversation_id 9?|6 generation_id 9?|7 model 9?|8 model_id 9?|9 model_params #1*|10 parent_tool_call_id 9?",n.Struct,s.SR]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["PreToolUseRequestResponse|1 permission 9?|2 user_message 9?|3 agent_message 9?|4 updated_input 9?|5 additional_context 9?"]}}class I extends o{constructor(t){super(),this.toolName="",this.toolOutput="",this.durationMs=n.protoInt64.zero,this.toolUseId="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["PostToolUseRequestQuery|1 tool_name 9|2 tool_input #0|3 tool_output 9|4 duration_ms 3|5 tool_use_id 9|6 cwd 9?|7 conversation_id 9?|8 generation_id 9?|9 model 9?|10 model_id 9?|11 model_params #1*|12 parent_tool_call_id 9?",n.Struct,s.SR]}}class P extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["PostToolUseRequestResponse|1 additional_context 9?|2 updated_mcp_tool_output 9?"]}}class b extends o{constructor(t){super(),this.toolName="",this.errorMessage="",this.failureType="",this.durationMs=n.protoInt64.zero,this.toolUseId="",this.isInterrupt=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PostToolUseFailureRequestQuery|1 tool_name 9|2 tool_input #0|3 error_message 9|4 failure_type 9|5 duration_ms 3|6 tool_use_id 9|7 is_interrupt 8|8 conversation_id 9?|9 generation_id 9?|10 model 9?|11 model_id 9?|12 model_params #1*|13 parent_tool_call_id 9?",n.Struct,s.SR]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["PostToolUseFailureRequestResponse|1 additional_context 9?"]}}},"../proto/dist/generated/agent/v1/kv_pb.js"(t,r,e){e.d(r,{gm:()=>d,km:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["Error|1 message 9"]}}class u extends o{constructor(t){super(),this.blobId=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GetBlobArgs|1 blob_id 12"]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GetBlobResult|1 blob_data 12?|2 error #0?",a]}}class l extends o{constructor(t){super(),this.blobId=new Uint8Array(0),this.blobData=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SetBlobArgs|1 blob_id 12|2 blob_data 12"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SetBlobResult|1 error #0?",a]}}class f extends o{constructor(t){super(),this.id=0,this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["KvServerMessage|1 id 13|2 get_blob_args #0 message|3 set_blob_args #1 message|4 span_context #2?",u,l,s.Kg]}}class d extends o{constructor(t){super(),this.id=0,this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["KvClientMessage|1 id 13|2 get_blob_result #0 message|3 set_blob_result #1 message",c,m]}}},"../proto/dist/generated/agent/v1/ls_exec_pb.js"(t,r,e){e.d(r,{PC:()=>c,Y$:()=>h,fv:()=>u,k2:()=>d,uj:()=>f,ur:()=>m,vq:()=>l,xe:()=>a,ze:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.path="",this.ignore=[],this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["LsArgs|1 path 9|2 ignore 9*|3 tool_call_id 9|4 sandbox_policy #0?|5 timeout_ms 13?",s.Mw]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["LsResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 timeout #3 result",c,f,d,p]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["LsSuccess|1 directory_tree_root #0",l]}}class l extends o{constructor(t){super(),this.absPath="",this.childrenDirs=[],this.childrenFiles=[],this.childrenWereProcessed=!1,this.fullSubtreeExtensionCounts={},this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["LsDirectoryTreeNode|1 abs_path 9|2 children_dirs #0*|3 children_files #1*|4 children_were_processed 8|5 full_subtree_extension_counts 9,5|6 num_files 5",l,m]}}class m extends o{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["LsDirectoryTreeNode.File|1 name 9|2 terminal_metadata #0?",h]}}class f extends o{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["LsError|1 path 9|2 error 9"]}}class d extends o{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["LsRejected|1 path 9|2 reason 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["LsTimeout|1 directory_tree_root #0",l]}}class h extends o{constructor(t){super(),this.lastCommands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["TerminalMetadata|1 cwd 9?|2 last_commands #0*|3 last_modified_ms 3?|4 current_command #0?",g]}}class g extends o{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["TerminalMetadata.Command|1 command 9|2 exit_code 5?|3 timestamp_ms 3?|4 duration_ms 3?"]}}},"../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{M:()=>a,c:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.providerIdentifier="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpAllowlistPrecheckArgs|1 provider_identifier 9|2 tool_name 9|3 tool_call_id 9?|4 annotations_json 9?"]}}class a extends i{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"(t,r,e){e.d(r,{D5:()=>p,NX:()=>m,OI:()=>h,h:()=>d,uL:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.serverIdentifier="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpAuthArgs|1 server_identifier 9|2 tool_call_id 9|3 plugin_id 9?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpAuthResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["McpAuthSuccess|1 server_identifier 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["McpAuthError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["McpAuthRejected|1 reason 9"]}}class m extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["McpAuthToolCall|1 args #0|2 result #1",o,a]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpAuthRequestQuery|1 args #0",o]}}class d extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["McpAuthRequestResponse|1 approved #0 result|2 rejected #1 result",p,h]}}class p extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["McpAuthRequestResponse.Approved"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["McpAuthRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/mcp_exec_pb.js"(t,r,e){e.d(r,{D0:()=>E,DI:()=>F,Dh:()=>H,E_:()=>f,HQ:()=>v,JL:()=>_,Jx:()=>j,KZ:()=>z,Ke:()=>h,Km:()=>x,Kp:()=>S,Nh:()=>I,QW:()=>q,T2:()=>N,WV:()=>g,X2:()=>D,XE:()=>T,ZD:()=>K,Zl:()=>c,_W:()=>C,_Z:()=>y,do:()=>w,ew:()=>l,iz:()=>p,kP:()=>O,kj:()=>M,ov:()=>W,pv:()=>U,w2:()=>G,xo:()=>R,zN:()=>J,zj:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/mcp_pb.js"),o=e("../proto/dist/runtime/compact.js");const a="agent.v1.";class u extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return a}}var c=(0,o.QT)(n.proto3,a,"McpPolicyBlockedReason",[[0,"UNSPECIFIED"],[1,"MCP_SERVERS_OFF"],[2,"MCP_ALLOWLIST"],[3,"CLOUD_AGENT_ALLOWLIST"],[4,"DENYLIST"],[5,"APPLIES_TO"],[6,"TOOL_ACCESS"]],1),l=(0,o.QT)(n.proto3,a,"McpRefreshPolicy",[[0,"UNSPECIFIED"],[1,"FORCE_IF_MISSING"],[2,"FORCE"]],1),m=(0,o.QT)(n.proto3,a,"McpServerTransport",[[0,"UNSPECIFIED"],[1,"STDIO"],[2,"HTTP"]],1);class f extends u{constructor(t){super(),this.name="",this.args={},this.toolCallId="",this.providerIdentifier="",this.toolName="",this.smartModeApprovalOnly=!1,this.skipApproval=!1,this.serverIdentifier="",this.symbolicPathArguments=[],this.argumentsRepaired=!1,this.refuseSavedSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpArgs|1 name 9|2 args 9,#0|3 tool_call_id 9|4 provider_identifier 9|5 tool_name 9|6 smart_mode_approval #1?|7 smart_mode_approval_only 8|8 skip_approval 8|9 server_identifier 9|10 symbolic_path_arguments #2*|11 arguments_repaired 8|12 refuse_saved_secrets 8",n.Value,s.UC,d]}}class d extends u{constructor(t){super(),this.path="",this.sha256="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["McpSymbolicPathArgument|1 path 9|2 sha256 9|3 size_bytes 3"]}}class p extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["McpResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result|5 tool_not_found #4 result|6 server_not_found #5 result|7 approved #6 result",q,I,R,v,g,_,h]}}class h extends u{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["McpApproved"]}}class g extends u{constructor(t){super(),this.name="",this.availableTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["McpToolNotFound|1 name 9|2 available_tools 9*|3 recovery #0?",P]}}class _ extends u{constructor(t){super(),this.name="",this.availableServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["McpServerNotFound|1 name 9|2 available_servers 9*"]}}class J extends u{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["McpTextContent|1 text 9|2 output_location #0?",s.pV]}}class w extends u{constructor(t){super(),this.data=new Uint8Array(0),this.mimeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["McpImageContent|1 data 12|2 mime_type 9"]}}class y extends u{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["McpToolResultContentItem|1 text #0 content|2 image #1 content",J,w]}}class S extends u{constructor(t){super(),this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SystemReminder|1 body 9"]}}class q extends u{constructor(t){super(),this.content=[],this.isError=!1,this.systemReminders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["McpSuccess|1 content #0*|2 is_error 8|3 structured_content #1|4 system_reminders #2*|5 result_meta #1|6 mcp_app_document #3",y,n.Struct,S,B]}}class B extends u{constructor(t){super(),this.uri="",this.mimeType="",this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["McpAppDocument|1 uri 9|2 mime_type 9|3 text 9|4 meta_json 9?"]}}class I extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["McpError|1 error 9|2 needs_auth 8?|3 recovery #0?|4 http_status 5?|5 retry_after_ms 13?|6 not_dialed 8?|7 bearer_error 9?|8 policy_blocked_reason #1?",P,c]}}class P extends u{constructor(t){super(),this.outcome=b.UNSPECIFIED,this.availableTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["McpRecovery|1 outcome #0|2 fresh_input_schema_json 9?|3 available_tools 9*",b]}}var b=(0,o.QT)(n.proto3,a,"McpRecovery.Outcome",[[0,"UNSPECIFIED"],[1,"CHANGED"],[2,"REMOVED"],[3,"UNCHANGED"],[4,"REFRESH_FAILED"]],1);class R extends u{constructor(t){super(),this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["McpRejected|1 reason 9|2 is_readonly 8"]}}class v extends u{constructor(t){super(),this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["McpPermissionDenied|1 error 9|2 is_readonly 8"]}}class x extends u{constructor(t){super(),this.serverIdentifiers=[],this.kickOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["McpStateExecArgs|1 server_identifiers 9*|2 kick_only 8|3 refresh_policy #0?|4 rule_subjects #1?",l,k]}}class k extends u{constructor(t){super(),this.commandPatterns=[],this.serverUrlPatterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["McpRuleSubjectsRequest|1 command_patterns 9*|2 server_url_patterns 9*"]}}class E extends u{constructor(t){super(),this.transport=m.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["McpRuleSubject|1 transport #0|2 value 9?",m]}}class C extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["McpStateExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result",U,A,$]}}class T extends u{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.tools=[],this.instructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["McpStateServer|1 server_name 9|2 server_identifier 9|3 plugin 9?|4 marketplace 9?|5 tools #0*|6 instructions #1*|7 status 9?|8 error_message 9?|9 pending_sign_in 8?|10 transport #2?|11 account_label 9?|12 rule_subject #3?",i.gd,i.I0,m,E]}}class U extends u{constructor(t){super(),this.servers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["McpStateSuccess|1 servers #0*",T]}}class A extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["McpStateError|1 error 9"]}}class $ extends u{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["McpStateRejected|1 reason 9"]}}class M extends u{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ListMcpResourcesExecArgs|1 server 9?"]}}class O extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ListMcpResourcesExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result",N,G,L]}}class D extends u{constructor(t){super(),this.uri="",this.server="",this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ListMcpResourcesExecResult.McpResource|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 server 9|6 annotations 9,9"]}}class N extends u{constructor(t){super(),this.resources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ListMcpResourcesSuccess|1 resources #0*",D]}}class G extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ListMcpResourcesError|1 error 9"]}}class L extends u{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ListMcpResourcesRejected|1 reason 9"]}}class F extends u{constructor(t){super(),this.server="",this.uri="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["ReadMcpResourceExecArgs|1 server 9|2 uri 9|3 download_path 9?|4 tool_call_id 9|5 smart_mode_approval #0?",s.UC]}}class K extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["ReadMcpResourceExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 not_found #3 result",z,j,H,W]}}class z extends u{constructor(t){super(),this.uri="",this.content={case:void 0},this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["ReadMcpResourceSuccess|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 text 9 content|6 blob 12 content|7 annotations 9,9|8 download_path 9?|9 output_location #0?|10 meta_json 9?",s.pV]}}class j extends u{constructor(t){super(),this.uri="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["ReadMcpResourceError|1 uri 9|2 error 9"]}}class H extends u{constructor(t){super(),this.uri="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["ReadMcpResourceRejected|1 uri 9|2 reason 9"]}}class W extends u{constructor(t){super(),this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ReadMcpResourceNotFound|1 uri 9"]}}},"../proto/dist/generated/agent/v1/mcp_pb.js"(t,r,e){e.d(r,{E$:()=>l,I0:()=>u,Is:()=>m,Or:()=>a,UC:()=>c,U_:()=>f,gd:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.name="",this.providerIdentifier="",this.toolName="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpToolDefinition|1 name 9|4 provider_identifier 9|5 tool_name 9|2 description 9|3 input_schema #0|6 input_schema_json 9?|7 output_schema_json 9?|8 annotations_json 9?|9 meta_json 9?",n.Value]}}class a extends i{constructor(t){super(),this.mcpTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpTools|1 mcp_tools #0*",o]}}class u extends i{constructor(t){super(),this.serverName="",this.instructions="",this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["McpInstructions|1 server_name 9|2 instructions 9|3 server_identifier 9"]}}class c extends i{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["McpDescriptor|1 server_name 9|2 server_identifier 9|3 folder_path 9?|4 server_use_instructions 9?|5 tools #0*|7 plugin 9?|8 marketplace 9?|9 plugin_db_id 9?|10 marketplace_id 9?|11 account_label 9?",l]}}class l extends i{constructor(t){super(),this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["McpToolDescriptor|1 tool_name 9|2 definition_path 9?|3 description 9?|4 input_schema #0?|5 input_schema_json 9?|6 annotations_json 9?",n.Value]}}class m extends i{constructor(t){super(),this.enabled=!1,this.workspaceProjectDir="",this.mcpDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["McpFileSystemOptions|1 enabled 8|2 workspace_project_dir 9|3 mcp_descriptors #0*",c]}}class f extends i{constructor(t){super(),this.enabled=!1,this.mcpDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpMetaToolOptions|1 enabled 8|2 mcp_descriptors #0*",c]}}},"../proto/dist/generated/agent/v1/pr_management_tool_pb.js"(t,r,e){e.d(r,{AU:()=>R,DY:()=>v,HL:()=>y,K$:()=>B});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"MergePrMode",[[0,"UNSPECIFIED"],[1,"MERGE"],[2,"AUTO"],[3,"DISABLE_AUTO"]],1),u=(0,s.QT)(n.proto3,i,"MergePrMethod",[[0,"UNSPECIFIED"],[1,"MERGE"],[2,"SQUASH"]],1),c=(0,s.QT)(n.proto3,i,"PullRequestStatus",[[0,"UNSPECIFIED"],[1,"OPEN"],[2,"CLOSED"]],1);class l extends o{constructor(t){super(),this.toolCallId="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["PrManagementArgs|1 tool_call_id 9|2 create_pr #0 action|3 update_pr #1 action|4 post_comment #2 action|5 resolve_comment #3 action|6 get_ci_status #4 action|7 set_pr_status #5 action|8 merge_pr #6 action|9 list_prs #7 action|10 get_pr #8 action",m,f,d,p,h,g,_,J,w]}}class m extends o{constructor(t){super(),this.title="",this.body="",this.branchName="",this.addLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CreatePrAction|1 title 9|2 body 9|3 base_branch 9?|4 draft 8?|5 branch_name 9|6 add_labels 9*|7 repo_url 9?|8 skip_branch_prefix_check 8?|9 stack_on_pr_number 3?"]}}class f extends o{constructor(t){super(),this.addLabels=[],this.removeLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UpdatePrAction|1 pr_url 9?|2 title 9?|3 body 9?|4 base_branch 9?|5 branch_name 9?|6 add_labels 9*|7 remove_labels 9*|8 repo_url 9?|9 stack_on_pr_number 3?|10 clear_stack 8?|11 draft 8?"]}}class d extends o{constructor(t){super(),this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["PostCommentAction|1 pr_url 9?|2 branch_name 9?|3 body 9|4 repo_url 9?|5 in_reply_to 3?|6 path 9?|7 line 5?|8 start_line 5?|9 side 9?|10 reply_to_reference 9?"]}}class p extends o{constructor(t){super(),this.commentId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ResolveCommentAction|1 pr_url 9?|2 branch_name 9?|3 comment_id 3|4 repo_url 9?|5 comment_reference 9?"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["GetCiStatusAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?"]}}class g extends o{constructor(t){super(),this.status=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SetPrStatusAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?|4 status #0",c]}}class _ extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.method=u.UNSPECIFIED,this.expectedMemberHeadShas={},this.downstack=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["MergePrAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?|4 mode #0|5 method #1|6 expected_head_sha 9?|7 expected_member_head_shas 9,9|8 downstack 8",a,u]}}class J extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ListPrsArgs|1 limit 5?"]}}class w extends o{constructor(t){super(),this.prUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GetPrArgs|1 pr_url 9"]}}class y extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["PrManagementResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 registered #3 result|5 needs_confirmation #4 result|6 read #5 result",q,B,I,P,b,S]}}class S extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["PrManagementRead|1 message 9"]}}class q extends o{constructor(t){super(),this.prUrl="",this.prNumber=0,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["PrManagementSuccess|1 pr_url 9|2 pr_number 5|3 message 9"]}}class B extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["PrManagementError|1 error 9"]}}class I extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["PrManagementRejected|1 reason 9"]}}class P extends o{constructor(t){super(),this.message="",this.title="",this.body="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["PrManagementRegistered|1 message 9|2 title 9|3 body 9|4 base_branch 9?|5 draft 8?|6 branch_name 9"]}}class b extends o{constructor(t){super(),this.message="",this.discoveredPrUrl="",this.discoveredPrNumber=0,this.discoveredPrTitle="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PrManagementNeedsConfirmation|1 message 9|2 discovered_pr_url 9|3 discovered_pr_number 5|4 discovered_pr_title 9|5 branch_name 9"]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["PrManagementToolCall|1 args #0|2 result #1",l,y]}}class v extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["PrManagementRequestQuery|1 args #0",l]}}},"../proto/dist/generated/agent/v1/read_exec_pb.js"(t,r,e){e.d(r,{F_:()=>c,Ko:()=>m,a2:()=>o,cW:()=>d,f4:()=>l,lW:()=>f,mE:()=>u,sV:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ReadArgs|1 path 9|2 tool_call_id 9|4 offset 5?|5 limit 13?|6 encoding_hint 9?|7 digest_only 8?|8 max_chars 13?|9 max_video_bytes 13?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ReadResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 file_not_found #3 result|5 permission_denied #4 result|6 invalid_file #5 result",u,c,l,m,f,d]}}class u extends i{constructor(t){super(),this.path="",this.output={case:void 0},this.totalLines=0,this.fileSize=n.protoInt64.zero,this.truncated=!1,this.rangeApplied=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ReadSuccess|1 path 9|2 content 9 output|5 data 12 output|3 total_lines 5|4 file_size 3|6 truncated 8|7 output_blob_id 12?|8 range_applied 8|9 sha256 9?|10 size_bytes 3?|11 redacted 8?"]}}class c extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReadError|1 path 9|2 error 9"]}}class l extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReadRejected|1 path 9|2 reason 9"]}}class m extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReadFileNotFound|1 path 9"]}}class f extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReadPermissionDenied|1 path 9"]}}class d extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReadInvalidFile|1 path 9|2 reason 9"]}}},"../proto/dist/generated/agent/v1/record_screen_exec_pb.js"(t,r,e){e.d(r,{$u:()=>a,N8:()=>p,T4:()=>f,Tj:()=>m,Wg:()=>c,ol:()=>d,y:()=>u,yH:()=>h,zH:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"RecordingMode",[[0,"UNSPECIFIED"],[1,"START_RECORDING"],[2,"SAVE_RECORDING"],[3,"DISCARD_RECORDING"]],1),u=(0,s.QT)(n.proto3,i,"RequestedFilePathRejectedReason",[[0,"UNSPECIFIED"],[1,"SLASHES_NOT_ALLOWED"]],1),c=(0,s.QT)(n.proto3,i,"RecordScreenFailureKind",[[0,"UNSPECIFIED"],[1,"INVALID_MODE"],[2,"STAGING_IO"],[3,"DISPLAY_UNAVAILABLE"],[4,"FFMPEG_START_FAILED"],[5,"NO_ACTIVE_RECORDING"],[6,"SAVE_IN_PROGRESS"],[7,"FFMPEG_STOP_FAILED"],[8,"PROXY_MISSING"],[9,"PROXY_INVALID"],[10,"RENDERER_UNAVAILABLE"],[11,"RENDER_FAILED"],[12,"ARTIFACT_WRITE_FAILED"],[13,"INTERNAL"],[14,"DESKTOP_HELD"],[15,"HOOK_REJECTED"],[16,"EXEC_FAILED"]],1);class l extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["RecordScreenArgs|1 mode #0|2 tool_call_id 9|3 save_as_filename 9?|4 desktop_lease_actor_id 9?",a]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["RecordScreenResult|1 start_success #0 result|2 save_success #1 result|3 discard_success #2 result|4 failure #3 result",f,d,p,h]}}class f extends o{constructor(t){super(),this.wasPriorRecordingCancelled=!1,this.wasSaveAsFilenameIgnored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["RecordScreenStartSuccess|1 was_prior_recording_cancelled 8|2 was_save_as_filename_ignored 8"]}}class d extends o{constructor(t){super(),this.path="",this.recordingDurationMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["RecordScreenSaveSuccess|1 path 9|2 recording_duration_ms 3|3 requested_file_path_rejected_reason #0?",u]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["RecordScreenDiscardSuccess"]}}class h extends o{constructor(t){super(),this.error="",this.kind=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["RecordScreenFailure|1 error 9|2 kind #0",c]}}},"../proto/dist/generated/agent/v1/replace_env_tool_pb.js"(t,r,e){e.d(r,{TO:()=>l,dV:()=>d,km:()=>h,uq:()=>f,us:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ReplaceEnvMode",[[0,"UNSPECIFIED"],[1,"CUSTOM"],[2,"CLEAN_SLATE"],[3,"DEFAULT"]],1);class u extends o{constructor(t){super(),this.repoUrl="",this.ref="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["RepoCheckoutRefOverride|1 repo_url 9|2 ref 9"]}}class c extends o{constructor(t){super(),this.installScript="",this.dockerfileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReplaceEnvConfig|1 install_script 9|2 dockerfile_contents 9"]}}class l extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.checkoutRefOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReplaceEnvArgs|1 config #0|2 mode #1|3 checkout_ref_overrides #2*",c,a,u]}}class m extends o{constructor(t){super(),this.setupLogs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReplaceEnvSuccess|1 setup_logs 9"]}}class f extends o{constructor(t){super(),this.errorMessage="",this.setupLogs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReplaceEnvFailure|1 error_message 9|2 setup_logs 9"]}}class d extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReplaceEnvResult|1 success #0 result|2 failure #1 result",m,f]}}class p extends o{constructor(t){super(),this.associatedPodKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ReplaceEnvToolCall|1 args #0|2 result #1|3 associated_pod_key 9",l,d]}}class h extends o{constructor(t){super(),this.associatedPodKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ReplaceEnvToolCallDelta|1 associated_pod_key 9"]}}},"../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"(t,r,e){e.d(r,{RH:()=>l,U_:()=>d,Y6:()=>u,q3:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"BugfixVerdict",[[0,"UNSPECIFIED"],[1,"FIXED"],[2,"FALSE_POSITIVE"],[3,"COULD_NOT_FIX"],[4,"RESOLVED_BY_OTHER_FIX"]],1);class u extends o{constructor(t){super(),this.bugId="",this.bugTitle="",this.verdict=a.UNSPECIFIED,this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BugfixResultItem|1 bug_id 9|2 bug_title 9|3 verdict #0|4 explanation 9|5 severity 9?",a]}}class c extends o{constructor(t){super(),this.summary="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReportBugfixResultsArgs|1 summary 9|2 results #0*",u]}}class l extends o{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReportBugfixResultsSuccess|1 results #0*",u]}}class m extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReportBugfixResultsError|1 error 9"]}}class f extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReportBugfixResultsResult|1 success #0 result|2 error #1 result",l,m]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReportBugfixResultsToolCall|1 args #0|2 result #1",c,f]}}},"../proto/dist/generated/agent/v1/request_context_exec_pb.js"(t,r,e){e.d(r,{TT:()=>v,DS:()=>B,Jy:()=>E,bb:()=>A,_K:()=>J,GE:()=>I,nf:()=>S,vB:()=>D,sG:()=>N,_G:()=>w,T3:()=>$,CB:()=>M,yb:()=>O,yW:()=>y,uw:()=>k});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");s.HL;var i=(0,s.QT)(n.proto3,"agent.v1.","PackageType",[[0,"UNSPECIFIED"],[1,"CURSOR_PROJECT"],[2,"CURSOR_PERSONAL"],[3,"CLAUDE_SKILL"],[4,"CLAUDE_PLUGIN"]],1),o=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js");class a extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class u extends a{constructor(t){super(),this.relativeWorkspacePath="",this.remoteUrls=[],this.remoteNames=[],this.repoName="",this.repoOwner="",this.isTracked=!1,this.isLocal=!1,this.workspaceUri="",this.pathEncryptionKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["RepositoryIndexingInfo|1 relative_workspace_path 9|2 remote_urls 9*|3 remote_names 9*|4 repo_name 9|5 repo_owner 9|6 is_tracked 8|7 is_local 8|8 orthogonal_transform_seed 1?|9 workspace_uri 9|10 path_encryption_key 9"]}}var c=e("../proto/dist/generated/agent/v1/mcp_pb.js"),l=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),m=e("../proto/dist/generated/agent/v1/subagents_pb.js"),f=e("../proto/dist/generated/agent/v1/agent_skills_pb.js"),d=e("../proto/dist/generated/agent/v1/system_prompt_pb.js");const p="agent.v1.";class h extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return p}}var g=(0,s.QT)(n.proto3,p,"ComputerUseDesktopPlatform",[[0,"UNSPECIFIED"],[1,"LINUX"],[2,"MACOS"],[3,"WINDOWS"]],1),_=(0,s.QT)(n.proto3,p,"MountedAgentStoreKind",[[0,"UNSPECIFIED"],[1,"SELF"],[2,"PEER"],[3,"SHARE"],[4,"PRINCIPAL"]],1);class J extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["RequestContextArgs|2 notes_session_id 9?|3 workspace_id 9?|4 read_only_pinned_tree_sha 9?|5 read_only_plugin_cache_root 9?|7 use_cached 8?|8 wait_for_workspace_cache 8?"]}}class w extends h{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["RequestContextResult|1 success #0 result|2 error #1 result|3 rejected #2 result",y,S,q]}}class y extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["RequestContextSuccess|1 request_context #0|2 served_from_disk_cache 8?",A]}}class S extends h{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["RequestContextError|1 error 9"]}}class q extends h{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["RequestContextRejected|1 reason 9"]}}class B extends h{constructor(t){super(),this.path="",this.status="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["GitRepoInfo|1 path 9|2 status 9|3 branch_name 9|4 remote_url 9?|5 previous_branch_is_ancestor 8?|6 is_origin_backed 8?"]}}class I extends h{constructor(t){super(),this.osVersion="",this.workspacePaths=[],this.shell="",this.sandboxEnabled=!1,this.terminalsFolder="",this.agentSharedNotesFolder="",this.agentConversationNotesFolder="",this.timeZone="",this.projectFolder="",this.agentTranscriptsFolder="",this.sandboxNetworkExplicitAllowlist=[],this.mountedAgentStores=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["RequestContextEnv|1 os_version 9|2 workspace_paths 9*|3 shell 9|5 sandbox_enabled 8|7 terminals_folder 9|8 agent_shared_notes_folder 9|9 agent_conversation_notes_folder 9|10 time_zone 9|11 project_folder 9|12 agent_transcripts_folder 9|13 artifacts_folder 9?|14 sandbox_supported 8?|16 sandbox_network_has_defaults 8?|17 sandbox_network_explicit_allowlist 9*|18 secret_redaction_enabled 8?|19 computer_use_supported 8?|20 is_working_dir_home_dir 8?|21 process_working_directory 9?|22 smart_mode_classifier_auto_mode_enabled 8?|23 dev_force_next_smart_mode_classifier_block_token 9?|24 dev_delay_next_smart_mode_classifier_token 9?|25 mounted_agent_stores #0*|26 user_agent_store_web_context #1?|27 dev_mock_prompt_time #2?|28 agent_store_dynamic_mount_enabled 8?|29 computer_use_desktop #3?",b,R,n.Timestamp,P]}}class P extends h{constructor(t){super(),this.platform=g.UNSPECIFIED,this.canvasWidth=0,this.canvasHeight=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ComputerUseDesktop|1 platform #0|2 canvas_width 5|3 canvas_height 5",g]}}class b extends h{constructor(t){super(),this.path="",this.kind=_.UNSPECIFIED,this.readOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["MountedAgentStore|1 path 9|2 kind #0|3 alias 9?|4 read_only 8|5 inherited_from_path 9?",_]}}class R extends h{constructor(t){super(),this.storeId="",this.portalBaseUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["UserAgentStoreWebContext|1 store_id 9|2 portal_base_url 9"]}}class v extends h{constructor(t){super(),this.logPath="",this.serverEndpoint="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["DebugModeConfig|1 log_path 9|2 server_endpoint 9|3 session_id 9"]}}class x extends h{constructor(t){super(),this.name="",this.description="",this.folderPath="",this.enabled=!1,this.readmeFilePath="",this.packageType=i.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SkillDescriptor|1 name 9|2 description 9|3 folder_path 9|4 enabled 8|5 parse_error 9?|6 readme_file_path 9|7 package_type #0",i]}}class k extends h{constructor(t){super(),this.skillDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["SkillOptions|1 skill_descriptors #0*",x]}}class E extends h{constructor(t){super(),this.configuredSteps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["HooksConfigInfo|1 configured_steps 9*"]}}class C extends h{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["PermissionsAutoRunInstructions|1 allow_instructions 9*|2 block_instructions 9*"]}}class T extends h{constructor(t){super(),this.startLineNumber=0,this.endLineNumberExclusive=0,this.beforeContextLines=[],this.removedLines=[],this.addedLines=[],this.afterContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["PrecomputedHumanChangeRenderedDiff|1 start_line_number 5|2 end_line_number_exclusive 5|3 before_context_lines 9*|4 removed_lines 9*|5 added_lines 9*|6 after_context_lines 9*"]}}class U extends h{constructor(t){super(),this.path="",this.renderedDiffs=[],this.isNewFile=!1,this.isDeletedFile=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["PrecomputedHumanChange|1 path 9|2 rendered_diffs #0*|3 is_new_file 8|4 is_deleted_file 8",T]}}class A extends h{constructor(t){super(),this.rules=[],this.repositoryInfo=[],this.tools=[],this.gitRepos=[],this.projectLayouts=[],this.mcpInstructions=[],this.fileContents={},this.customSubagents=[],this.agentSkills=[],this.precomputedHumanChanges=[],this.nonFileRules=[],this.disabledTeamRules=[],this.adminCommandDenylist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["RequestContext|2 rules #0*|4 env #1|6 repository_info #2*|7 tools #3*|8 conversation_notes_listing 9?|9 shared_notes_listing 9?|11 git_repos #4*|13 project_layouts #5*|14 mcp_instructions #6*|15 debug_mode_config #7?|16 cloud_rule 9?|17 web_search_enabled 8?|18 skill_options #8?|19 repository_info_should_query_prod 8?|20 file_contents 9,9|21 user_intent_summary 9?|22 custom_subagents #9*|23 mcp_file_system_options #10?|24 web_fetch_enabled 8?|25 hooks_additional_context 9?|26 commit_attribution_message 9?|27 pr_attribution_message 9?|28 hooks_config #11?|29 agent_skills #12*|30 precomputed_human_changes #13*|31 recently_added_plugin #14?|32 supports_mcp_auth 8?|33 git_repo_info_complete 8?|34 mcp_meta_tool_options #15?|35 read_lints_enabled 8?|36 mcp_info_complete 8?|37 non_file_rules #0*|38 matched_installed_plugin #16?|39 rules_info_complete 8?|40 env_info_complete 8?|41 repository_info_complete 8?|42 custom_subagents_info_complete 8?|43 agent_skills_info_complete 8?|44 mcp_file_system_info_complete 8?|45 git_status_info_complete 8?|46 user_permissions_auto_run #17?|47 project_permissions_auto_run #17?|48 admin_permissions_auto_run #17?|49 disabled_team_rules 9*|50 search_conversations_enabled 8?|51 send_message_enabled 8?|52 admin_command_denylist 9*|53 system_prompt_override #18?",o.DX,I,u,c.gd,B,l.vq,c.I0,v,k,m.zz,c.Is,E,f.N,U,G,c.U_,F,C,d.$]}}class $ extends h{constructor(t){super(),this.rules=[],this.nonFileRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["RequestContextRulesPart|1 rules #0*|2 non_file_rules #0*|3 cloud_rule 9?",o.DX]}}class M extends h{constructor(t){super(),this.agentSkills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["RequestContextSkillsPart|1 agent_skills #0*|2 skill_options #1?",f.N,k]}}class O extends h{constructor(t){super(),this.customSubagents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["RequestContextSubagentsPart|1 custom_subagents #0*",m.zz]}}class D extends h{constructor(t){super(),this.tools=[],this.mcpInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["RequestContextMcpsPart|1 tools #0*|2 mcp_instructions #1*|3 mcp_file_system_options #2?|4 mcp_meta_tool_options #3?",c.gd,c.I0,c.Is,c.U_]}}class N extends h{constructor(t){super(),this.rulesBlobId=new Uint8Array(0),this.rulesByteLength=0,this.skillsBlobId=new Uint8Array(0),this.skillsByteLength=0,this.subagentsBlobId=new Uint8Array(0),this.subagentsByteLength=0,this.mcpsBlobId=new Uint8Array(0),this.mcpsByteLength=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["RequestContextPartReferences|1 rules_blob_id 12|2 rules_byte_length 13|3 skills_blob_id 12|4 skills_byte_length 13|5 subagents_blob_id 12|6 subagents_byte_length 13|7 mcps_blob_id 12|8 mcps_byte_length 13|9 dynamic_context #0",A]}}class G extends h{constructor(t){super(),this.displayName="",this.description="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.commands=[],this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["RecentlyAddedPlugin|1 display_name 9|2 description 9|3 skills #0*|4 subagents #0*|5 hooks #0*|6 rules #0*|7 commands #0*|8 mcp_servers 9*",L]}}class L extends h{constructor(t){super(),this.name="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["RecentlyAddedPlugin.CapabilityDescriptor|1 name 9|2 description 9"]}}class F extends h{constructor(t){super(),this.displayName="",this.description="",this.matchedKeyword="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.commands=[],this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["MatchedInstalledPlugin|1 display_name 9|2 description 9|3 matched_keyword 9|4 skills #0*|5 subagents #0*|6 hooks #0*|7 rules #0*|8 commands #0*|9 mcp_servers 9*",L]}}},"../proto/dist/generated/agent/v1/requested_model_pb.js"(t,r,e){e.d(r,{G0:()=>o,G4:()=>c,R4:()=>u,SR:()=>l,ih:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ApiKeyCredentials|1 api_key 9|2 base_url 9?"]}}class a extends i{constructor(t){super(),this.apiKey="",this.baseUrl="",this.deployment="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AzureCredentials|1 api_key 9|2 base_url 9|3 deployment 9"]}}class u extends i{constructor(t){super(),this.accessKey="",this.secretKey="",this.region="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BedrockCredentials|1 access_key 9|2 secret_key 9|3 region 9|4 session_token 9?"]}}class c extends i{constructor(t){super(),this.modelId="",this.maxMode=!1,this.parameters=[],this.credentials={case:void 0},this.builtInModel=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["RequestedModel|1 model_id 9|2 max_mode 8|3 parameters #0*|4 api_key_credentials #1 credentials|5 azure_credentials #2 credentials|6 bedrock_credentials #3 credentials|7 built_in_model 8",l,o,a,u]}}class l extends i{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["RequestedModel.ModelParameterValue|1 id 9|2 value 9"]}}},"../proto/dist/generated/agent/v1/sandbox_pb.js"(t,r,e){e.d(r,{Mw:()=>l,Qq:()=>a,RB:()=>u,Sz:()=>f,h1:()=>c,vc:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["NetworkPolicyLoggingConfig|1 decision_log_path 9?|2 log_format 9?"]}}class u extends o{constructor(t){super(),this.deny=[],this.allow=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["NetworkPolicy|1 version 13?|2 default_action #0?|3 deny 9*|4 allow 9*|5 logging #1?",c,a]}}var c=(0,s.QT)(n.proto3,i,"NetworkPolicy.DefaultAction",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"DENY"]],1);class l extends o{constructor(t){super(),this.type=m.UNSPECIFIED,this.additionalReadwritePaths=[],this.additionalReadonlyPaths=[],this.readBoundary=f.UNSPECIFIED,this.additionalReadPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SandboxPolicy|1 type #0|2 network_access 8?|3 additional_readwrite_paths 9*|4 additional_readonly_paths 9*|5 debug_output_dir 9?|7 disable_tmp_write 8?|8 allowlist_escalated 8?|9 enable_shared_build_cache 8?|10 network_policy #1?|11 network_policy_strict 8?|12 capture_denies 8?|13 skip_statsig_defaults 8?|14 read_boundary #2|15 additional_read_paths 9*|16 allow_user_override_read_paths 8?|17 private_tmp 8?",m,u,f]}}var m=(0,s.QT)(n.proto3,i,"SandboxPolicy.Type",[[0,"UNSPECIFIED"],[1,"INSECURE_NONE"],[2,"WORKSPACE_READWRITE"],[3,"WORKSPACE_READONLY"]],1),f=(0,s.QT)(n.proto3,i,"SandboxPolicy.ReadBoundaryMode",[[0,"UNSPECIFIED"],[1,"SYSTEM"],[2,"WORKSPACE"]],1)},"../proto/dist/generated/agent/v1/selected_context_pb.js"(t,r,e){e.d(r,{AW:()=>M,Ps:()=>A,bf:()=>H,d:()=>f,uM:()=>j,xv:()=>st});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),a=e("../proto/dist/generated/agent/v1/agent_skills_pb.js"),u=e("../proto/dist/runtime/compact.js");const c="agent.v1.";class l extends u.HL{static get runtime(){return(0,u.kU)(this,"runtime",n.proto3)}static $p(){return c}}var m=(0,u.QT)(n.proto3,c,"SelectedPluginCapabilityType",[[0,"UNSPECIFIED"],[1,"COMMAND"],[2,"SKILL"],[3,"SUBAGENT"]],1);class f extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.path="",this.mimeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SelectedImage|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|10 prompt_upload_ref #1 data_or_blob_id|2 uuid 9|3 path 9|4 dimension #2|7 mime_type 9",d,h,p]}}class d extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SelectedImage.BlobIdWithData|1 blob_id 12|2 data 12"]}}class p extends l{constructor(t){super(),this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SelectedImage.Dimension|1 width 5|2 height 5"]}}class h extends l{constructor(t){super(),this.uploadId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["PromptUploadRef|1 upload_id 9"]}}class g extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.filename="",this.mimeType="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SelectedDocument|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|10 prompt_upload_ref #1 data_or_blob_id|2 uuid 9|3 filename 9|4 mime_type 9|7 path 9",_,h]}}class _ extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SelectedDocument.BlobIdWithData|1 blob_id 12|2 data 12"]}}class J extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.path="",this.mimeType="",this.filename="",this.materializeToFilesystem=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SelectedVideo|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|11 signed_url #1 data_or_blob_id|13 prompt_upload_ref #2 data_or_blob_id|2 uuid 9|3 path 9|4 fps 2?|7 mime_type 9|10 filename 9|12 materialize_to_filesystem 8",w,y,h]}}class w extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SelectedVideo.BlobIdWithData|1 blob_id 12|2 data 12"]}}class y extends l{constructor(t){super(),this.url="",this.key="",this.expiresAtUnixMs=n.protoInt64.zero,this.refreshAfterUnixMs=n.protoInt64.zero,this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SelectedVideo.SignedUrl|1 url 9|2 key 9|3 expires_at_unix_ms 3|4 refresh_after_unix_ms 3|5 conversation_id 9"]}}class S extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ExtraContextEntry|1 data 9 data_or_blob_id|2 blob_id 12 data_or_blob_id"]}}class q extends l{constructor(t){super(),this.content="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["SelectedFile|1 content 9|2 path 9|3 relative_path 9?"]}}class B extends l{constructor(t){super(),this.content="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["SelectedCodeSelection|1 content 9|2 path 9|3 relative_path 9?|4 range #0",s.Q6]}}class I extends l{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["SelectedTerminal|1 content 9|2 title 9?|3 path 9?"]}}class P extends l{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SelectedTerminalSelection|1 content 9|2 title 9?|3 path 9?|4 range #0",s.Q6]}}class b extends l{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["SelectedFolder|1 path 9|2 relative_path 9?|3 directory_tree #0",i.vq]}}class R extends l{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["SelectedExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?|6 blob_id 12?"]}}class v extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["SelectedCursorRule|1 rule #0",o.DX]}}class x extends l{constructor(t){super(),this.content="",this.fullContentLengthCharCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SelectedGitDiff|1 content 9|2 full_content_length_char_count 5"]}}class k extends l{constructor(t){super(),this.content="",this.fullContentLengthCharCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["SelectedGitDiffFromBranchToMain|1 content 9|2 full_content_length_char_count 5"]}}class E extends l{constructor(t){super(),this.sha="",this.message="",this.diff="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["SelectedGitCommit|1 sha 9|2 message 9|3 description 9?|4 diff 9"]}}class C extends l{constructor(t){super(),this.number=0,this.url="",this.folderPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["SelectedPullRequest|1 number 5|2 url 9|3 title 9?|4 folder_path 9|5 summary_json 9?|6 description 9?|7 blob_id 12?"]}}class T extends l{constructor(t){super(),this.prUrl="",this.filePath="",this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["SelectedGitPRDiffSelection|1 pr_url 9|2 file_path 9|3 start_line 5|4 end_line 5|5 diff_content 9?|6 blob_id 12?"]}}class U extends l{constructor(t){super(),this.pluginId="",this.capabilityType=m.UNSPECIFIED,this.sourcePath="",this.snapshotToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["SelectedPluginCapabilityRef|1 plugin_id 9|2 capability_type #0|3 source_path 9|4 snapshot_token 9|5 resolved_commit_sha 9?",m]}}class A extends l{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["SelectedCursorCommand|1 name 9|2 content 9|3 plugin_capability #0?|4 full_path 9?|5 display_name 9?",U]}}class $ extends l{constructor(t){super(),this.docId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["SelectedDocumentation|1 doc_id 9|2 name 9"]}}class M extends l{constructor(t){super(),this.agentId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["SelectedPastChat|1 agent_id 9|2 name 9"]}}class O extends l{constructor(t){super(),this.name="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["RecentAgent|1 name 9|2 path 9|3 overview 9?"]}}class D extends l{constructor(t){super(),this.recentAgents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["RecentAgentsContext|1 recent_agents #0*",O]}}class N extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["CallFrame|1 function_name 9?|2 url 9?|3 line_number 5?|4 column_number 5?"]}}class G extends l{constructor(t){super(),this.callFrames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["StackTrace|1 call_frames #0*|2 raw_stack_trace 9?",N]}}class L extends l{constructor(t){super(),this.message="",this.timestamp=0,this.level="",this.clientName="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["SelectedConsoleLog|1 message 9|2 timestamp 1|3 level 9|4 client_name 9|5 session_id 9|6 stack_trace #0?|7 object_data_json 9?",G]}}class F extends l{constructor(t){super(),this.element="",this.xpath="",this.textContent="",this.extra="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["SelectedUIElement|1 element 9|2 xpath 9|3 text_content 9|4 extra 9|5 component 9?|6 component_props_json 9?"]}}class K extends l{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["SelectedSubagent|1 name 9"]}}class z extends l{constructor(t){super(),this.browserId="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["SelectedBrowser|1 browser_id 9|2 url 9|3 page_title 9?"]}}class j extends l{constructor(t){super(),this.repoUrl="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["SelectedRepository|1 repo_url 9|2 label 9"]}}class H extends l{constructor(t){super(),this.environmentPublicId="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["SelectedEnvironment|1 environment_public_id 9|2 label 9"]}}class W extends l{constructor(t){super(),this.filesToCommit=[],this.filesToExcludeFromCommit=[],this.shouldStageAllChanges=!1,this.filesToCommitWithStatus=[],this.filesToExcludeFromCommitWithStatus=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["SelectedAgenticGitActionCommitParams|1 files_to_commit 9*|2 files_to_exclude_from_commit 9*|3 should_stage_all_changes 8|4 create_pr_draft 8?|5 files_to_commit_with_status #0*|6 files_to_exclude_from_commit_with_status #0*",V]}}class Q extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["SelectedAgenticGitActionCreateBranchParams"]}}class V extends l{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["SelectedAgenticGitFileWithStatus|1 path 9|2 status 9?"]}}class X extends l{constructor(t){super(),this.filesToPush=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["SelectedAgenticGitActionPushParams|1 files_to_push 9*|2 create_pr_draft 8?"]}}class Y extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["SelectedAgenticGitActionFixMergeConflictsParams|1 base_branch 9?|2 pr_url 9?"]}}class Z extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["SelectedAgenticGitActionBabysitPrInCloudParams|1 base_branch 9?"]}}class tt extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["SelectedAgenticGitActionUpdateBranchParams|1 base_branch 9?"]}}class rt extends l{constructor(t){super(),this.remoteBranch="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["SelectedAgenticGitActionPullLocallyParams|1 remote_branch 9"]}}class et extends l{constructor(t){super(),this.params={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["SelectedAgenticGitAction|2 commit_params #0 params|6 commit_and_push_params #0 params|3 push_params #1 params|7 create_pr_params #1 params|8 create_pr_with_changes_params #0 params|4 fix_merge_conflicts_params #2 params|11 babysit_pr_in_cloud_params #3 params|14 apply_locally_params #4 params|15 checkout_branch_params #4 params|12 create_branch_and_commit_params #0 params|13 create_branch_commit_and_push_params #0 params|16 update_branch_params #5 params|17 create_branch_params #6 params|5 branch_context #7?|9 path_to_template_file 9?|10 path_to_template_dir 9?",W,X,Y,Z,rt,tt,Q,nt]}}class nt extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["SelectedGitBranchContext|1 current_branch 9?|2 base_branch 9?|3 agent_branch_prefix 9?"]}}class st extends l{constructor(t){super(),this.selectedImages=[],this.extraContext=[],this.extraContextEntries=[],this.files=[],this.codeSelections=[],this.terminals=[],this.terminalSelections=[],this.folders=[],this.externalLinks=[],this.cursorRules=[],this.cursorCommands=[],this.documentations=[],this.uiElements=[],this.consoleLogs=[],this.gitCommits=[],this.pastChats=[],this.gitPrDiffSelections=[],this.selectedPullRequests=[],this.selectedSubagents=[],this.selectedVideos=[],this.selectedBrowsers=[],this.selectedDocuments=[],this.selectedSkills=[],this.selectedRepositories=[],this.selectedEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["SelectedContext|1 selected_images #0*|2 invocation_context #1?|3 extra_context 9*|16 extra_context_entries #2*|4 files #3*|5 code_selections #4*|6 terminals #5*|7 terminal_selections #6*|8 folders #7*|9 external_links #8*|10 cursor_rules #9*|18 git_diff #10?|11 git_diff_from_branch_to_main #11?|12 cursor_commands #12*|13 documentations #13*|14 ui_elements #14*|15 console_logs #15*|17 git_commits #16*|19 past_chats #17*|20 git_pr_diff_selections #18*|21 selected_pull_requests #19*|22 selected_subagents #20*|23 selected_videos #21*|24 selected_browsers #22*|25 selected_documents #23*|26 selected_skills #24*|27 recent_agents_context #25?|34 selected_agentic_git_action #26?|35 selected_repositories #27*|36 selected_environments #28*",f,it,S,q,B,I,P,b,R,v,x,k,A,$,F,L,E,M,T,C,K,J,z,g,a.N,D,et,j,H]}}class it extends l{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["InvocationContext|1 slack_thread #0 data|2 github_pr #1 data|3 ide_state #2 data|4 microsoft_teams_thread #3 data|10 blob_id 12 data",ot,ut,lt,at]}}class ot extends l{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["InvocationContext.SlackThread|1 thread 9|2 channel_name 9?|3 channel_purpose 9?|4 channel_topic 9?|5 sender_name 9?|6 sender_id 9?|7 sender_type 9?|8 is_directly_addressed 8?|9 message_permalink 9?"]}}class at extends l{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["InvocationContext.MicrosoftTeamsThread|1 thread 9|2 channel_name 9?|3 team_name 9?|4 channel_description 9?|5 team_description 9?"]}}class ut extends l{constructor(t){super(),this.title="",this.description="",this.comments="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["InvocationContext.GithubPR|1 title 9|2 description 9|3 comments 9|4 ci_failures 9?|5 code_tour_view #0?",ct]}}class ct extends l{constructor(t){super(),this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["InvocationContext.GithubPR.CodeTourView|1 head_sha 9|2 current_revision_id 9?|3 visible_section_id 9?|4 visible_step_id 9?|5 path_scope_prefix 9?"]}}class lt extends l{constructor(t){super(),this.visibleFiles=[],this.recentlyViewedFiles=[],this.currentlyViewedPrs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["InvocationContext.IdeState|1 visible_files #0*|2 recently_viewed_files #0*|3 currently_viewed_prs #1*",mt,dt]}}class mt extends l{constructor(t){super(),this.path="",this.totalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["InvocationContext.IdeState.File|1 path 9|2 relative_path 9?|3 cursor_position #0?|4 total_lines 5|5 active_command 9?",ft]}}class ft extends l{constructor(t){super(),this.line=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["InvocationContext.IdeState.File.CursorPosition|1 line 5|2 text 9"]}}class dt extends l{constructor(t){super(),this.number=0,this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["InvocationContext.IdeState.ViewedPullRequest|1 number 5|2 url 9|3 title 9?|4 folder_path 9?|5 summary_json 9?|6 description 9?"]}}},"../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"(t,r,e){e.d(r,{BI:()=>o,JH:()=>u,MU:()=>c,r$:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.installCommand="",this.startCommand="",this.dockerfileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SetupVmEnvironmentArgs|2 install_command 9|3 start_command 9|4 dockerfile_contents 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["SetupVmEnvironmentResult|1 success #0 result",u]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["SetupVmEnvironmentSuccess"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SetupVmEnvironmentToolCall|1 args #0|2 result #1",o,a]}}},"../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{C:()=>a,e:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ShellAllowlistPrecheckArgs|1 command 9|2 working_directory 9|3 parsing_result #0|4 classifier_result #1?|5 tool_call_id 9?",s.HO,s.E4]}}class u extends o{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ShellAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/shell_exec_pb.js"(t,r,e){e.d(r,{$F:()=>S,Db:()=>E,E4:()=>J,FI:()=>M,HO:()=>p,Hu:()=>q,In:()=>I,Jg:()=>m,Lv:()=>d,Ng:()=>A,Pv:()=>g,QR:()=>O,W4:()=>R,Y9:()=>U,_d:()=>l,a:()=>b,b:()=>P,eG:()=>N,iA:()=>f,jK:()=>B,jn:()=>L,mJ:()=>F,o0:()=>k,pZ:()=>G,r6:()=>h,rI:()=>$,tD:()=>T,vb:()=>C,xC:()=>D});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/generated/agent/v1/utils_pb.js"),o=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="agent.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}var l=(0,a.QT)(n.proto3,u,"TimeoutBehavior",[[0,"UNSPECIFIED"],[1,"CANCEL"],[2,"BACKGROUND"]],1),m=(0,a.QT)(n.proto3,u,"ShellBackgroundReason",[[0,"UNSPECIFIED"],[1,"TIMEOUT"],[2,"USER_REQUEST"]],1),f=(0,a.QT)(n.proto3,u,"ForceBackgroundShellStatus",[[0,"UNSPECIFIED"],[1,"ACCEPTED"],[2,"NOT_FOUND"]],1),d=(0,a.QT)(n.proto3,u,"ShellAbortReason",[[0,"UNSPECIFIED"],[1,"USER_ABORT"],[2,"TIMEOUT"]],1);class p extends c{constructor(t){super(),this.parsingFailed=!1,this.executableCommands=[],this.hasRedirects=!1,this.hasCommandSubstitution=!1,this.redirects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ShellCommandParsingResult|1 parsing_failed 8|2 executable_commands #0*|3 has_redirects 8|4 has_command_substitution 8|5 all_redirects_are_dev_null 8?|6 redirects #1*",g,_]}}class h extends c{constructor(t){super(),this.type="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommandArg|1 type 9|2 value 9"]}}class g extends c{constructor(t){super(),this.name="",this.args=[],this.fullText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommand|1 name 9|2 args #0*|3 full_text 9",h]}}class _ extends c{constructor(t){super(),this.operator="",this.destinationFds=[],this.targetNodeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ShellCommandParsingResult.Redirect|1 operator 9|2 destination_fds 13*|3 target_node_type 9|4 target_text 9?"]}}class J extends c{constructor(t){super(),this.commands=[],this.suggestedSandboxMode=w.UNSPECIFIED,this.classificationFailed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["CommandClassifierResult|1 commands #0*|2 suggested_sandbox_mode #1|3 classification_failed 8",y,w]}}var w=(0,a.QT)(n.proto3,u,"CommandClassifierResult.SuggestedSandboxMode",[[0,"UNSPECIFIED"],[1,"SANDBOX"],[2,"NO_SANDBOX"],[3,"UNDETERMINED"]],1);class y extends c{constructor(t){super(),this.name="",this.arguments=[],this.subcommandTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["CommandClassifierResult.ClassifiedCommand|1 name 9|2 arguments 9*|3 suggested_allowlist_entry 9?|4 subcommand_tokens 9*"]}}class S extends c{constructor(t){super(),this.pattern="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ShellOutputNotificationConfig|1 pattern 9|2 reason 9|3 debounce 1?|4 notification_limit 5?"]}}class q extends c{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ForceBackgroundShellArgs|1 tool_call_id 9"]}}class B extends c{constructor(t){super(),this.status=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ForceBackgroundShellResult|1 status #0|2 shell_result #1?",f,R]}}class I extends c{constructor(t){super(),this.kind=P.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ShellHookApprovalRequirement|1 kind #0|2 reason 9?",P]}}var P=(0,a.QT)(n.proto3,u,"ShellHookApprovalRequirement.Kind",[[0,"UNSPECIFIED"],[1,"FORCE_PROMPT"]],1);class b extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.timeout=0,this.toolCallId="",this.simpleCommands=[],this.hasInputRedirect=!1,this.hasOutputRedirect=!1,this.isBackground=!1,this.skipApproval=!1,this.timeoutBehavior=l.UNSPECIFIED,this.closeStdin=!1,this.adminCommandDenylist=[],this.smartModeClassifierAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ShellArgs|1 command 9|2 working_directory 9|3 timeout 5|4 tool_call_id 9|5 simple_commands 9*|6 has_input_redirect 8|7 has_output_redirect 8|8 parsing_result #0|9 requested_sandbox_policy #1?|10 file_output_threshold_bytes 4?|11 is_background 8|12 skip_approval 8|13 timeout_behavior #2|14 hard_timeout 5?|15 description 9?|16 classifier_result #3?|17 close_stdin 8|18 output_notification #4?|19 smart_mode_approval #5?|20 hook_approval_requirement #6?|21 conversation_id 9?|22 admin_command_denylist 9*|23 request_id 9?|24 secret_scope_id 9?|25 smart_mode_classifier_allowed 8|26 desktop_lease_actor_id 9?",p,s.Mw,l,J,S,i.UC,I]}}class R extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ShellResult|1 success #0 result|2 failure #1 result|3 timeout #2 result|4 rejected #3 result|5 spawn_error #4 result|7 permission_denied #5 result|101 sandbox_policy #6?|102 is_background 8?|103 terminals_folder 9?|104 pid 13?",O,D,N,G,F,L,s.Mw]}}class v extends c{constructor(t){super(),this.kind=x.UNSPECIFIED,this.memoryLimitBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ShellOomKill|1 kind #0|2 memory_limit_bytes 4",x]}}var x=(0,a.QT)(n.proto3,u,"ShellOomKill.Kind",[[0,"UNSPECIFIED"],[1,"COMMAND_KILLED"],[2,"COMMAND_FAILED"],[3,"UNCONFIRMED"]],1);class k extends c{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ShellStreamStdout|1 data 9"]}}class E extends c{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ShellStreamStderr|1 data 9"]}}class C extends c{constructor(t){super(),this.code=0,this.cwd="",this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ShellStreamExit|1 code 13|2 cwd 9|3 output_location #0?|4 aborted 8|5 abort_reason #1?|6 local_execution_time_ms 5?|7 oom_kill #2?",i.pV,d,v]}}class T extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ShellStreamStart|1 sandbox_policy #0?|2 command 9?",s.Mw]}}class U extends c{constructor(t){super(),this.shellId=0,this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ShellStreamBackgrounded|1 shell_id 13|2 command 9|3 working_directory 9|4 pid 13?|5 ms_to_wait 5?|6 reason #0?",m]}}class A extends c{constructor(t){super(),this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ShellStreamHookContext|1 hook_additional_contexts #0*",o.C]}}class $ extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.sandboxPolicyType="",this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["ShellSandboxUnsupported|1 command 9|2 working_directory 9|3 sandbox_policy_type 9|4 reason 9|5 is_readonly 8"]}}class M extends c{constructor(t){super(),this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ShellStream|1 stdout #0 event|2 stderr #1 event|3 exit #2 event|4 start #3 event|5 rejected #4 event|6 permission_denied #5 event|7 backgrounded #6 event|8 hook_context #7 event|9 sandbox_unsupported #8 event",k,E,C,T,G,L,U,A,$]}}class O extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.exitCode=0,this.signal="",this.stdout="",this.stderr="",this.executionTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ShellSuccess|1 command 9|2 working_directory 9|3 exit_code 5|4 signal 9|5 stdout 9|6 stderr 9|7 execution_time 5|8 output_location #0?|9 shell_id 13?|10 interleaved_output 9?|11 pid 13?|12 ms_to_wait 5?|13 local_execution_time_ms 5?|14 background_reason #1?|15 output_head 9?|16 output_tail 9?|17 elided_chars 13?",i.pV,m]}}class D extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.exitCode=0,this.signal="",this.stdout="",this.stderr="",this.executionTime=0,this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ShellFailure|1 command 9|2 working_directory 9|3 exit_code 5|4 signal 9|5 stdout 9|6 stderr 9|7 execution_time 5|8 output_location #0?|9 interleaved_output 9?|10 abort_reason #1?|11 aborted 8|12 local_execution_time_ms 5?|13 output_head 9?|14 output_tail 9?|15 elided_chars 13?|16 oom_kill #2?",i.pV,d,v]}}class N extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.timeoutMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ShellTimeout|1 command 9|2 working_directory 9|3 timeout_ms 5"]}}class G extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ShellRejected|1 command 9|2 working_directory 9|3 reason 9|4 is_readonly 8"]}}class L extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ShellPermissionDenied|1 command 9|2 working_directory 9|3 error 9|4 is_readonly 8"]}}class F extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["ShellSpawnError|1 command 9|2 working_directory 9|3 error 9"]}}},"../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"(t,r,e){e.d(r,{Th:()=>f,bN:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"SmartModeClassifierDecision",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"BLOCK"]],1),u=(0,s.QT)(n.proto3,i,"SmartModeClassifierRuleEffect",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"ASK_FIRST"]],1),c=(0,s.QT)(n.proto3,i,"SmartModeClassifierRuleSource",[[0,"UNSPECIFIED"],[1,"CUSTOM_RULE"],[2,"TEAM_RULE"]],1);class l extends o{constructor(t){super(),this.role="",this.content="",this.invokedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SmartModeClassifierConversationMessage|1 role 9|2 content 9|3 position 13?|4 invoked_files #0*",m]}}class m extends o{constructor(t){super(),this.path="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SmartModeClassifierInvokedFile|1 path 9|2 content 9"]}}class f extends o{constructor(t){super(),this.toolCallId="",this.conversationContext=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SmartModeClassifierArgs|1 tool_call_id 9|2 parent_conversation_id 9?|3 target #0|4 conversation_context #1*",d,l]}}class d extends o{constructor(t){super(),this.action="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SmartModeRiskTarget|1 action 9|2 arguments #0",n.Struct]}}class p extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SmartModeClassifierResult|1 success #0 result|2 error #1 result",h,_]}}class h extends o{constructor(t){super(),this.decision=a.UNSPECIFIED,this.appliedRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SmartModeClassifierSuccess|1 decision #0|2 block_reason 9?|3 proposed_allow_rule 9?|4 applied_rules #1*|5 proposed_allow_rule_replaces 9?|6 blocked_effect 9?|7 irreversible 8?|8 action_description 9?|9 block_reason_category 9?|10 jev_path 9?|11 high_stakes 8?",a,g]}}class g extends o{constructor(t){super(),this.effect=u.UNSPECIFIED,this.text="",this.source=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SmartModeClassifierAppliedRule|1 effect #0|2 text 9|3 source #1",u,c]}}class _ extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SmartModeClassifierError|1 error 9"]}}},"../proto/dist/generated/agent/v1/subagent_exec_pb.js"(t,r,e){e.d(r,{HJ:()=>y,Hq:()=>J,L5:()=>_,Pw:()=>m,S3:()=>q,TN:()=>p,Y:()=>w,a3:()=>B,bE:()=>g,jh:()=>l,od:()=>S,vS:()=>d,zJ:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),i=e("../proto/dist/generated/agent/v1/subagents_pb.js"),o=e("../proto/dist/generated/agent/v1/selected_context_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="agent.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}var l=(0,a.QT)(n.proto3,u,"ForceBackgroundSubagentStatus",[[0,"UNSPECIFIED"],[1,"ACCEPTED"],[2,"NOT_FOUND"]],1);class m extends c{constructor(t){super(),this.toolCallId="",this.subagentType="",this.modelId="",this.prompt="",this.readonly=!1,this.credentials={case:void 0},this.mode=i.FL.UNSPECIFIED,this.environment=i.dU.UNSPECIFIED,this.modelParameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SubagentArgs|1 tool_call_id 9|2 subagent_type 9|3 model_id 9|4 prompt 9|5 readonly 8|6 resume_agent_id 9?|7 run_in_background 8?|8 continuation_config #0|9 parent_conversation_id 9?|10 api_key_credentials #1 credentials|11 azure_credentials #2 credentials|12 bedrock_credentials #3 credentials|13 interrupt 8?|14 mode #4|15 fork_agent_id 9?|16 root_parent_conversation_id 9?|17 selected_context #5?|18 direct_meta_parent_child_subagent 8?|19 environment #6|20 cloud_base_branch 9?|21 model_parameters #7*|22 voice_call_notes #8?",f,s.G0,s.ih,s.R4,i.FL,o.xv,i.dU,s.SR,i.OT]}}class f extends c{constructor(t){super(),this.idleThreshold=0,this.maxLoops=0,this.nudgeMessage="",this.escapeMessageTemplate="",this.collectBackgroundChildren=!1,this.childrenCompletedMessageTemplate="",this.continuationRoundDelayMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ClientContinuationConfig|1 idle_threshold 5|2 max_loops 5|3 nudge_message 9|4 escape_message_template 9|5 collect_background_children 8|6 children_completed_message_template 9|7 continuation_round_delay_ms 5"]}}class d extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SubagentResult|1 success #0 result|2 error #1 result",y,S]}}class p extends c{constructor(t){super(),this.agentId="",this.timeoutMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SubagentAwaitArgs|1 agent_id 9|2 timeout_ms 13"]}}class h extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SubagentAwaitResult|1 complete #0 result|2 still_running #1 result|3 not_found #2 result|4 error #3 result",g,_,J,w]}}class g extends c{constructor(t){super(),this.agentId="",this.toolCallCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SubagentAwaitComplete|1 agent_id 9|2 transcript_path 9?|3 tool_call_count 5|4 final_message 9?"]}}class _ extends c{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SubagentAwaitStillRunning|1 agent_id 9|2 transcript_path 9?"]}}class J extends c{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SubagentAwaitNotFound|1 agent_id 9"]}}class w extends c{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SubagentAwaitError|1 agent_id 9?|2 error 9"]}}class y extends c{constructor(t){super(),this.agentId="",this.toolCallCount=0,this.backgroundReason=i.qL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SubagentSuccess|1 agent_id 9|2 final_message 9?|3 tool_call_count 5|4 background_reason #0|5 transcript_path 9?",i.qL]}}class S extends c{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SubagentError|1 agent_id 9?|2 error 9"]}}class q extends c{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ForceBackgroundSubagentArgs|1 tool_call_id 9"]}}class B extends c{constructor(t){super(),this.status=l.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ForceBackgroundSubagentResult|1 status #0",l]}}},"../proto/dist/generated/agent/v1/subagents_pb.js"(t,r,e){e.d(r,{FL:()=>m,OT:()=>R,U6:()=>l,_L:()=>f,b$:()=>a,dU:()=>u,qL:()=>c,zz:()=>b});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"CustomSubagentPermissionMode",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"READONLY"],[3,"AGENT_ONLY"]],1),u=(0,s.QT)(n.proto3,i,"SubagentExecutionEnvironment",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD"]],1),c=(0,s.QT)(n.proto3,i,"SubagentBackgroundReason",[[0,"UNSPECIFIED"],[1,"AGENT_REQUEST"],[2,"USER_REQUEST"],[3,"QUEUED_FOLLOW_UP"]],1),l=(0,s.QT)(n.proto3,i,"BackgroundTaskCompletionReason",[[0,"UNSPECIFIED"],[1,"TASK_FINISHED"],[2,"TASK_PROGRESS"],[3,"WORKER_REPARENTED"],[4,"WORKER_MESSAGE"],[5,"WORKER_NEEDS_ATTENTION"],[6,"PROJECT_SESSION_MESSAGE"]],1),m=(0,s.QT)(n.proto3,i,"TaskMode",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"PLAN"]],1);class f extends o{constructor(t){super(),this.type={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SubagentType|1 unspecified #0 type|2 computer_use #1 type|3 custom #2 type|4 explore #3 type|5 media_review #4 type|6 bash #5 type|7 browser_use #6 type|8 shell #7 type|9 vm_setup_helper #8 type|10 debug #9 type|11 cursor_guide #10 type|12 watch_video #11 type|13 computer_use_v2 #12 type",d,p,P,h,g,_,w,J,y,S,q,B,I]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SubagentTypeUnspecified"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SubagentTypeComputerUse"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SubagentTypeExplore"]}}class g extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SubagentTypeMediaReview"]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SubagentTypeBash"]}}class J extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SubagentTypeShell"]}}class w extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SubagentTypeBrowserUse"]}}class y extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SubagentTypeVmSetupHelper"]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SubagentTypeDebug"]}}class q extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["SubagentTypeCursorGuide"]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["SubagentTypeWatchVideo"]}}class I extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["SubagentTypeComputerUseV2"]}}class P extends o{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SubagentTypeCustom|1 name 9"]}}class b extends o{constructor(t){super(),this.fullPath="",this.name="",this.description="",this.tools=[],this.model="",this.prompt="",this.permissionMode=a.UNSPECIFIED,this.isBackground=!1,this.forceDefaultModel=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["CustomSubagent|1 full_path 9|2 name 9|3 description 9|4 tools 9*|5 model 9|6 prompt 9|7 permission_mode #0|8 is_background 8|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 force_default_model 8|14 source 9?",a]}}class R extends o{constructor(t){super(),this.request="",this.messageId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["VoiceCallNotes|1 request 9|2 message_id 9"]}}},"../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"(t,r,e){e.d(r,{Cs:()=>m,Nc:()=>f,q5:()=>p,rA:()=>h,w$:()=>d});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.targetModeId="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SwitchModeArgs|1 target_mode_id 9|2 explanation 9?|3 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["SwitchModeResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.fromModeId="",this.toModeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["SwitchModeSuccess|1 from_mode_id 9|2 to_mode_id 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SwitchModeError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SwitchModeRejected|1 reason 9"]}}class m extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SwitchModeToolCall|1 args #0|2 result #1",o,a]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SwitchModeRequestQuery|1 args #0",o]}}class d extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SwitchModeRequestResponse|1 approved #0 result|2 rejected #1 result",p,h]}}class p extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SwitchModeRequestResponse.Approved"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SwitchModeRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/system_prompt_pb.js"(t,r,e){e.d(r,{$:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.spec={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SystemPromptSpec|1 replace 9 spec|2 append 9 spec"]}}},"../proto/dist/generated/agent/v1/todo_tool_pb.js"(t,r,e){e.d(r,{AJ:()=>p,Vj:()=>a,bk:()=>c,kW:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"TodoStatus",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"IN_PROGRESS"],[3,"COMPLETED"],[4,"CANCELLED"]],1);class u extends o{constructor(t){super(),this.id="",this.content="",this.status=a.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.dependencies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["TodoItem|1 id 9|2 content 9|3 status #0|4 created_at 3|5 updated_at 3|6 dependencies 9*",a]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["UpdateTodosToolCall|1 args #0|2 result #1",l,m]}}class l extends o{constructor(t){super(),this.todos=[],this.merge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["UpdateTodosArgs|1 todos #0*|2 merge 8",u]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["UpdateTodosResult|1 success #0 result|2 error #1 result",f,d]}}class f extends o{constructor(t){super(),this.todos=[],this.totalCount=0,this.wasMerge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UpdateTodosSuccess|1 todos #0*|2 total_count 5|3 was_merge 8",u]}}class d extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["UpdateTodosError|1 error 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ReadTodosToolCall|1 args #0|2 result #1",h,g]}}class h extends o{constructor(t){super(),this.statusFilter=[],this.idFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ReadTodosArgs|1 status_filter #0*|2 id_filter 9*",a]}}class g extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ReadTodosResult|1 success #0 result|2 error #1 result",_,J]}}class _ extends o{constructor(t){super(),this.todos=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ReadTodosSuccess|1 todos #0*|2 total_count 5",u]}}class J extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ReadTodosError|1 error 9"]}}},"../proto/dist/generated/agent/v1/utils_pb.js"(t,r,e){e.d(r,{Q6:()=>o,UC:()=>c,pV:()=>u,yX:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["Range|1 start #0|2 end #0",a]}}class a extends i{constructor(t){super(),this.line=0,this.column=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["Position|1 line 13|2 column 13"]}}class u extends i{constructor(t){super(),this.filePath="",this.sizeBytes=n.protoInt64.zero,this.lineCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["OutputLocation|1 file_path 9|2 size_bytes 3|3 line_count 3"]}}class c extends i{constructor(t){super(),this.requestId="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SmartModeApproval|1 request_id 9|2 reason 9"]}}},"../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{K:()=>o,M:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WebFetchAllowlistPrecheckArgs|1 url 9|2 tool_call_id 9?"]}}class a extends i{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebFetchAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"(t,r,e){e.d(r,{Hs:()=>h,Un:()=>d,fS:()=>p,fd:()=>f,m$:()=>g});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.url="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebFetchArgs|1 url 9|2 tool_call_id 9"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WebFetchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",c,l,m]}}class c extends o{constructor(t){super(),this.url="",this.markdown="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WebFetchSuccess|1 url 9|2 markdown 9|3 output_location #0?",s.pV]}}class l extends o{constructor(t){super(),this.url="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WebFetchError|1 url 9|2 error 9"]}}class m extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WebFetchRejected|1 reason 9"]}}class f extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WebFetchToolCall|1 args #0|2 result #1",a,u]}}class d extends o{constructor(t){super(),this.skipApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WebFetchRequestQuery|1 args #0|2 skip_approval 8|3 smart_mode_approval #1",a,s.UC]}}class p extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WebFetchRequestResponse|1 approved #0 result|2 rejected #1 result",h,g]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WebFetchRequestResponse.Approved"]}}class g extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WebFetchRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/web_search_tool_pb.js"(t,r,e){e.d(r,{KL:()=>d,XJ:()=>h,lI:()=>p,pn:()=>f,yc:()=>g});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.searchTerm="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WebSearchArgs|1 search_term 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebSearchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WebSearchSuccess|1 references #0*",m]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WebSearchError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WebSearchRejected|1 reason 9"]}}class m extends i{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WebSearchReference|1 title 9|2 url 9|3 chunk 9"]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WebSearchToolCall|1 args #0|2 result #1",o,a]}}class d extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WebSearchRequestQuery|1 args #0",o]}}class p extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WebSearchRequestResponse|1 approved #0 result|2 rejected #1 result",h,g]}}class h extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WebSearchRequestResponse.Approved"]}}class g extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WebSearchRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/write_exec_pb.js"(t,r,e){e.d(r,{QM:()=>m,U7:()=>c,bM:()=>l,en:()=>f,hY:()=>o,j6:()=>u,v3:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.fileText="",this.toolCallId="",this.returnFileContentAfterWrite=!1,this.fileBytes=new Uint8Array(0),this.planMode=!1,this.confineToWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WriteArgs|1 path 9|2 file_text 9|3 tool_call_id 9|4 return_file_content_after_write 8|5 file_bytes 12|6 encoding_hint 9?|7 plan_mode 8|8 confine_to_workspace 8"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WriteResult|1 success #0 result|3 permission_denied #1 result|4 no_space #2 result|5 error #3 result|6 rejected #4 result",u,c,l,m,f]}}class u extends i{constructor(t){super(),this.path="",this.linesCreated=0,this.fileSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WriteSuccess|1 path 9|2 lines_created 5|3 file_size 5|4 file_content_after_write 9?"]}}class c extends i{constructor(t){super(),this.path="",this.directory="",this.operation="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WritePermissionDenied|1 path 9|2 directory 9|3 operation 9|4 error 9|5 is_readonly 8"]}}class l extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WriteNoSpace|1 path 9"]}}class m extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WriteError|1 path 9|2 error 9"]}}class f extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WriteRejected|1 path 9|2 reason 9"]}}},"../proto/dist/generated/aiserver/v1/bidi_pb.js"(t,r,e){e.d(r,{$r:()=>o,Qd:()=>a,hD:()=>c,xy:()=>l,yq:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class o extends i{constructor(t){super(),this.requestId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["BidiRequestId|1 request_id 9"]}}class a extends i{constructor(t){super(),this.data="",this.appendSeqno=n.protoInt64.zero,this.dataBinary=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["BidiAppendRequest|1 data 9|2 request_id #0|3 append_seqno 3|4 data_binary 12",o]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BidiAppendResponse"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["BidiPollRequest|1 request_id #0|2 start_request 8?",o]}}class l extends i{constructor(t){super(),this.seqno=n.protoInt64.zero,this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BidiPollResponse|1 seqno 3|2 data 9|3 eof 8?"]}}},"../proto/dist/generated/aiserver/v1/chat_pb.js"(t,r,e){e.d(r,{O9:()=>z,gn:()=>Xt,yf:()=>nt,An:()=>er,hS:()=>gt,jF:()=>Mt,KR:()=>H,TS:()=>Z,cf:()=>V,Bh:()=>ct,jp:()=>Q,D8:()=>at,XE:()=>et,Bo:()=>ut,O0:()=>X});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/tools_pb.js"),i=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),o=e("../proto/dist/generated/aiserver/v1/docs_pb.js"),a=(e("../proto/dist/generated/aiserver/v1/repository_pb.js"),e("../proto/dist/runtime/compact.js"));const u="aiserver.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}class l extends c{constructor(t){super(),this.type=m.UNSPECIFIED,this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ComposerCapabilityRequest|1 type #0|2 loop_on_lints #1 data|3 loop_on_tests #2 data|4 mega_planner #3 data|5 loop_on_command #4 data|6 tool_call #5 data|7 diff_review #6 data|8 context_picking #7 data|9 edit_trail #8 data|10 auto_context #9 data|11 context_planner #10 data|12 remember_this #11 data|13 decomposer #12 data|14 cursor_rules #13 data",m,h,g,_,J,w,y,I,P,b,R,v,B,x]}}var m=(0,a.QT)(n.proto3,u,"ComposerCapabilityRequest.ComposerCapabilityType",[[0,"UNSPECIFIED"],[1,"LOOP_ON_LINTS"],[2,"LOOP_ON_TESTS"],[3,"MEGA_PLANNER"],[4,"LOOP_ON_COMMAND"],[5,"TOOL_CALL"],[6,"DIFF_REVIEW"],[7,"CONTEXT_PICKING"],[8,"EDIT_TRAIL"],[9,"AUTO_CONTEXT"],[10,"CONTEXT_PLANNER"],[11,"DIFF_HISTORY"],[12,"REMEMBER_THIS"],[13,"DECOMPOSER"],[14,"USES_CODEBASE"],[15,"TOOL_FORMER"],[16,"CURSOR_RULES"],[17,"TOKEN_COUNTER"],[18,"USAGE_DATA"],[19,"CHIMES"],[20,"CODE_DECAY_TRACKER"],[21,"BACKGROUND_COMPOSER"],[22,"SUMMARIZATION"],[23,"AI_CODE_TRACKING"],[24,"QUEUING"],[25,"MEMORIES"],[26,"RCP_LOGS"],[27,"KNOWLEDGE_FETCH"],[28,"SLACK_INTEGRATION"],[29,"SUB_COMPOSER"],[30,"THINKING"],[31,"CONTEXT_WINDOW"],[32,"ONLINE_METRICS"],[33,"NOTIFICATIONS"],[34,"SPEC"],[35,"BROWSER_AGENT"]],1),f=(0,a.QT)(n.proto3,u,"ComposerCapabilityRequest.ToolType",[[0,"UNSPECIFIED"],[1,"ADD_FILE_TO_CONTEXT"],[3,"ITERATE"],[4,"REMOVE_FILE_FROM_CONTEXT"],[5,"SEMANTIC_SEARCH_CODEBASE"]],1);class d extends c{constructor(t){super(),this.type=f.UNSPECIFIED,this.name="",this.properties={},this.required=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ComposerCapabilityRequest.ToolSchema|1 type #0|2 name 9|3 properties 9,#1|4 required 9*",f,p]}}class p extends c{constructor(t){super(),this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ComposerCapabilityRequest.SchemaProperty|1 type 9|2 description 9?"]}}class h extends c{constructor(t){super(),this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnLintsCapability|1 linter_errors #0*|2 custom_instructions 9?",i.wZ]}}class g extends c{constructor(t){super(),this.testNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnTestsCapability|1 test_names 9*|2 custom_instructions 9?"]}}class _ extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ComposerCapabilityRequest.MegaPlannerCapability|1 custom_instructions 9?"]}}class J extends c{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnCommandCapability|1 command 9|2 custom_instructions 9?|3 output 9?|4 exit_code 5?"]}}class w extends c{constructor(t){super(),this.toolSchemas=[],this.relevantFiles=[],this.filesInContext=[],this.semanticSearchFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ComposerCapabilityRequest.ToolCallCapability|1 custom_instructions 9?|2 tool_schemas #0*|3 relevant_files 9*|4 files_in_context 9*|5 semantic_search_files 9*",d]}}class y extends c{constructor(t){super(),this.diffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability|1 custom_instructions 9?|2 diffs #0*",S]}}class S extends c{constructor(t){super(),this.relativeWorkspacePath="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability.SimpleFileDiff|1 relative_workspace_path 9|3 chunks #0*",q]}}class q extends c{constructor(t){super(),this.oldLines=[],this.newLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability.SimpleFileDiff.Chunk|1 old_lines 9*|2 new_lines 9*|3 old_range #0|4 new_range #0",i.MT]}}class B extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ComposerCapabilityRequest.DecomposerCapability|1 custom_instructions 9?"]}}class I extends c{constructor(t){super(),this.potentialContextFiles=[],this.potentialContextCodeChunks=[],this.filesInContext=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ComposerCapabilityRequest.ContextPickingCapability|1 custom_instructions 9?|2 potential_context_files 9*|3 potential_context_code_chunks #0*|4 files_in_context 9*",i.FY]}}class P extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ComposerCapabilityRequest.EditTrailCapability|1 custom_instructions 9?"]}}class b extends c{constructor(t){super(),this.additionalFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ComposerCapabilityRequest.AutoContextCapability|1 custom_instructions 9?|2 additional_files 9*"]}}class R extends c{constructor(t){super(),this.attachedCodeChunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ComposerCapabilityRequest.ContextPlannerCapability|1 custom_instructions 9?|2 attached_code_chunks #0*",i.FY]}}class v extends c{constructor(t){super(),this.memory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ComposerCapabilityRequest.RememberThisCapability|1 custom_instructions 9?|2 memory 9"]}}class x extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ComposerCapabilityRequest.CursorRulesCapability|1 custom_instructions 9?"]}}class k extends c{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ComposerCapabilityContext|27 slack_integration #0 data|28 github_pr #1 data|29 microsoft_teams_integration #2 data",E,T,C]}}class E extends c{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ComposerCapabilityContext.SlackIntegrationContext|1 thread 9|2 channel_name 9?|3 channel_purpose 9?|4 channel_topic 9?|5 sender_name 9?|6 sender_id 9?|7 sender_type 9?|8 is_directly_addressed 8?|9 message_permalink 9?"]}}class C extends c{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ComposerCapabilityContext.MicrosoftTeamsIntegrationContext|1 thread 9|2 channel_name 9?|3 team_name 9?|4 channel_description 9?|5 team_description 9?"]}}class T extends c{constructor(t){super(),this.title="",this.description="",this.comments="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ComposerCapabilityContext.GithubPRContext|1 title 9|2 description 9|3 comments 9|4 ci_failures 9?|5 code_tour_context #0",U]}}class U extends c{constructor(t){super(),this.changeId="",this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ComposerCapabilityContext.GithubPRContext.CodeTourContext|1 change_id 9|2 head_sha 9|3 current_revision_id 9?|4 visible_section_id 9?|5 visible_step_id 9?|6 path_scope_prefix 9?"]}}var A=e("../proto/dist/generated/agent/v1/agent_pb.js"),$=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),M=e("../proto/dist/generated/agent/v1/selected_context_pb.js");e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class O extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class D extends O{constructor(t){super(),this.lints=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["GetLintsForChangeResponse|1 lints #0*",N]}}class N extends O{constructor(t){super(),this.message="",this.severity="",this.relativeWorkspacePath="",this.startLineNumberOneIndexed=0,this.startColumnOneIndexed=0,this.endLineNumberInclusiveOneIndexed=0,this.endColumnOneIndexed=0,this.quickFixes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["GetLintsForChangeResponse.Lint|1 message 9|2 severity 9|3 relative_workspace_path 9|4 start_line_number_one_indexed 5|5 start_column_one_indexed 5|6 end_line_number_inclusive_one_indexed 5|7 end_column_one_indexed 5|9 quick_fixes #0*",G]}}class G extends O{constructor(t){super(),this.message="",this.kind="",this.isPreferred=!1,this.edits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["GetLintsForChangeResponse.Lint.QuickFix|1 message 9|2 kind 9|3 is_preferred 8|4 edits #0*",L]}}class L extends O{constructor(t){super(),this.relativeWorkspacePath="",this.text="",this.startLineNumberOneIndexed=0,this.startColumnOneIndexed=0,this.endLineNumberInclusiveOneIndexed=0,this.endColumnOneIndexed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["GetLintsForChangeResponse.Lint.QuickFix.Edit|1 relative_workspace_path 9|2 text 9|3 start_line_number_one_indexed 5|4 start_column_one_indexed 5|5 end_line_number_inclusive_one_indexed 5|6 end_column_one_indexed 5"]}}const F="aiserver.v1.";class K extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return F}}var z=(0,a.QT)(n.proto3,F,"ChunkType",[[0,"UNSPECIFIED"],[1,"CODEBASE"],[2,"LONG_FILE"],[3,"DOCS"]],1),j=(0,a.QT)(n.proto3,F,"SubagentType",[[0,"UNSPECIFIED"],[1,"DEEP_SEARCH"],[2,"FIX_LINTS"],[3,"TASK"],[4,"SPEC"]],1);class H extends K{constructor(t){super(),this.summary="",this.truncationLastBubbleIdInclusive="",this.clientShouldStartSendingFromInclusiveBubbleId="",this.previousConversationSummaryBubbleId="",this.includesToolResults=!1,this.strategy="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["ConversationSummary|1 summary 9|2 truncation_last_bubble_id_inclusive 9|3 client_should_start_sending_from_inclusive_bubble_id 9|4 previous_conversation_summary_bubble_id 9|5 includes_tool_results 8|6 strategy 9"]}}class W extends K{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ContextToRank|1 relative_workspace_path 9|2 contents 9|3 line_range #0?|4 code_block #1?",i.MT,i.NG]}}class Q extends K{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["RankedContext|1 context #0|2 score 2",W]}}class V extends K{constructor(t){super(),this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["DocumentationCitation|1 chunks #0*",o.ci]}}class X extends K{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["WebCitation|1 references #0*",Y]}}class Y extends K{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["WebReference|2 title 9|1 url 9|3 chunk 9"]}}class Z extends K{constructor(t){super(),this.title="",this.url="",this.chunk="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["DocsReference|1 title 9|2 url 9|3 chunk 9|4 name 9"]}}class tt extends K{constructor(t){super(),this.content="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["AiWebSearchResult|1 content 9|2 title 9"]}}class rt extends K{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["StatusUpdate|1 message 9|2 metadata 9?"]}}class et extends K{constructor(t){super(),this.updates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["StatusUpdates|1 updates #0*",rt]}}class nt extends K{constructor(t){super(),this.fileName="",this.diffHistory=[],this.diffHistoryTimestamps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ComposerFileDiffHistory|1 file_name 9|2 diff_history 9*|3 diff_history_timestamps 1*"]}}var st=(0,a.QT)(n.proto3,F,"StreamUnifiedChatRequest.UnifiedMode",[[0,"UNSPECIFIED"],[1,"CHAT"],[2,"AGENT"],[3,"EDIT"],[4,"CUSTOM"],[5,"PLAN"],[6,"DEBUG"]],1);n.proto3;class it extends K{constructor(t){super(),this.relativeWorkspacePath="",this.content="",this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["ContextPiece|1 relative_workspace_path 9|2 content 9|3 score 2"]}}class ot extends K{constructor(t){super(),this.percentageRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["ContextWindowStatus|1 percentage_remaining 5|2 tokens_used 5?|3 token_limit 5?|4 percentage_remaining_float 2?"]}}class at extends K{constructor(t){super(),this.message="",this.codicon="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["ServiceStatusUpdate|1 message 9|2 codicon 9|3 allow_command_links_potentially_unsafe_please_only_use_for_handwritten_trusted_markdown 8?|4 action_to_run_on_status_update 9?"]}}class ut extends K{constructor(t){super(),this.symbolName="",this.symbolSearchString="",this.relativeWorkspacePath="",this.roughLineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["SymbolLink|1 symbol_name 9|2 symbol_search_string 9|3 relative_workspace_path 9|4 rough_line_number 5"]}}class ct extends K{constructor(t){super(),this.displayName="",this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["FileLink|1 display_name 9|2 relative_workspace_path 9"]}}class lt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.redRanges=[],this.redRangesReversed=[],this.startHash="",this.endHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["RedDiff|1 relative_workspace_path 9|2 red_ranges #0*|3 red_ranges_reversed #0*|4 start_hash 9|5 end_hash 9",i.l2]}}class mt extends K{constructor(t){super(),this.fileDetails="",this.fileName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["DiffFile|1 file_details 9|2 file_name 9"]}}class ft extends K{constructor(t){super(),this.description="",this.message="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ViewableCommitProps|1 description 9|2 message 9|3 files #0*",mt]}}class dt extends K{constructor(t){super(),this.title="",this.body="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["ViewablePRProps|1 title 9|2 body 9|3 files #0*",mt]}}class pt extends K{constructor(t){super(),this.files=[],this.diffPreface="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["ViewableDiffProps|1 files #0*|2 diff_preface 9",mt]}}class ht extends K{constructor(t){super(),this.diffData=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["ViewableGitContext|1 commit_data #0?|2 pull_request_data #1?|3 diff_data #2*",ft,dt,pt]}}class gt extends K{constructor(t){super(),this.text="",this.type=_t.UNSPECIFIED,this.attachedCodeChunks=[],this.codebaseContextChunks=[],this.commits=[],this.pullRequests=[],this.gitDiffs=[],this.assistantSuggestedDiffs=[],this.interpreterResults=[],this.images=[],this.attachedFolders=[],this.approximateLintErrors=[],this.bubbleId="",this.attachedFoldersNew=[],this.lints=[],this.userResponsesToSuggestedCodeBlocks=[],this.relevantFiles=[],this.toolResults=[],this.notepads=[],this.capabilities=[],this.editTrailContexts=[],this.suggestedCodeBlocks=[],this.diffsForCompressingFiles=[],this.multiFileLinterErrors=[],this.diffHistories=[],this.recentlyViewedFiles=[],this.recentLocationsHistory=[],this.isAgentic=!1,this.fileDiffTrajectories=[],this.existedSubsequentTerminalCommand=!1,this.existedPreviousTerminalCommand=!1,this.docsReferences=[],this.webReferences=[],this.aiWebSearchResults=[],this.attachedFoldersListDirResults=[],this.humanChanges=[],this.attachedHumanChanges=!1,this.summarizedComposers=[],this.cursorRules=[],this.contextPieces=[],this.allThinkingBlocks=[],this.diffsSinceLastApply=[],this.deletedFiles=[],this.supportedTools=[],this.consoleLogs=[],this.knowledgeItems=[],this.uiElementPicked=[],this.documentationSelections=[],this.externalLinks=[],this.projectLayouts=[],this.capabilityContexts=[],this.todos=[],this.requestId="",this.createdAt="",this.mcpDescriptors=[],this.workspaceUris=[],this.cursorCommands=[],this.cursorCommandsExplicitlySet=!1,this.pastChats=[],this.pastChatsExplicitlySet=!1,this.selectedRepositories=[],this.selectedEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["ConversationMessage|1 text 9|2 type #0|3 attached_code_chunks #1*|4 codebase_context_chunks #2*|5 commits #3*|6 pull_requests #4*|7 git_diffs #5*|8 assistant_suggested_diffs #6*|9 interpreter_results #7*|10 images #8*|11 attached_folders 9*|12 approximate_lint_errors #9*|13 bubble_id 9|32 server_bubble_id 9?|14 attached_folders_new #10*|15 lints #11*|16 user_responses_to_suggested_code_blocks #12*|17 relevant_files 9*|18 tool_results #13*|19 notepads #14*|20 is_capability_iteration 8?|21 capabilities #15*|22 edit_trail_contexts #16*|23 suggested_code_blocks #17*|24 diffs_for_compressing_files #18*|25 multi_file_linter_errors #19*|26 diff_histories #20*|27 recently_viewed_files #1*|28 recent_locations_history #21*|29 is_agentic 8|30 file_diff_trajectories #22*|31 conversation_summary #23?|33 existed_subsequent_terminal_command 8|34 existed_previous_terminal_command 8|35 docs_references #24*|36 web_references #25*|75 ai_web_search_results #26*|37 git_context #27?|38 attached_folders_list_dir_results #28*|39 cached_conversation_summary #23?|40 human_changes #29*|41 attached_human_changes 8|42 summarized_composers #30*|43 cursor_rules #31*|44 context_pieces #32*|45 thinking #33?|46 all_thinking_blocks #33*|85 thinking_style #34?|47 unified_mode #35?|98 agent_mode #36?|48 diffs_since_last_apply #37*|49 deleted_files #38*|50 usage_uuid 9?|51 supported_tools #39*|52 current_file_location_data #40?|53 edit_tool_supports_search_and_replace 8?|54 last_terminal_cwd 9?|55 user_explicitly_asked_to_generate_cursor_rules 8?|56 console_logs #41*|57 rich_text 9?|58 knowledge_items #42*|59 ui_element_picked #43*|60 user_explicitly_asked_to_add_to_knowledge_base 8?|61 documentation_selections #44*|62 external_links #45*|63 use_web 8?|64 project_layouts #46*|65 thinking_duration_ms 5?|88 step_duration_ms 5?|66 subagent_return #47?|67 is_simple_looping_message 8?|68 capability_contexts #48*|69 checkpoint_commit_hash 9?|70 git_status_raw 9?|71 todos #49*|72 is_review_edits_followup 8?|74 request_id 9|73 ide_editors_state #50?|76 context_window_status #51?|77 is_plan_execution 8?|78 created_at 9|79 model_info #52|80 is_quick_search_query 8?|81 plan_update #53?|82 is_simulated_msg 8?|95 simulated_msg_reason #54?|97 simulated_message_metadata #55?|83 mcp_descriptors #56*|84 workspace_project_dir 9?|87 workspace_uris 9*|86 debug_mode_config #57?|89 text_blob_id 12?|90 rich_text_blob_id 12?|91 cursor_commands #58*|92 cursor_commands_explicitly_set 8|93 past_chats #59*|94 past_chats_explicitly_set 8|109 selected_repositories #60*|110 selected_environments #61*|96 triggering_user_info #62?|99 turn_steer 8?|100 sent_by_agent_id 9?|101 sent_by_voice_call 8?|102 sender #63?|103 reply_to 9?|104 reply_audience #64?|105 reply_to_tool_call_id 9?|106 summarized_tool_call_id 9?|107 reply_quote 9?|108 thread_id 9?",_t,wt,i.NG,Xt,Yt,i.o$,Qt,Wt,i.UR,xt,jt,kt,tr,It,Pt,l,vt,Zt,lt,i.U$,or,Et,nt,H,Z,Y,tt,ht,s.$PL,Tt,bt,i.DX,it,Ut,Jt,st,A.xyI,At,$t,s.XaY,zt,i.EZ,Mt,i.c5,Ot,i.ot,pr,ar,k,s.kWq,Dt,ot,i.Wj,Gt,A.c_h,Lt,Ft,$.TT,M.Ps,M.AW,M.uM,M.bf,A.iHX,A.D$r,A.HXb]}}var _t=(0,a.QT)(n.proto3,F,"ConversationMessage.MessageType",[[0,"UNSPECIFIED"],[1,"HUMAN"],[2,"AI"]],1),Jt=(0,a.QT)(n.proto3,F,"ConversationMessage.ThinkingStyle",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"CODEX"],[3,"GPT5"]],1);class wt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.languageIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["ConversationMessage.CodeChunk|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 summarization_strategy #0?|5 language_identifier 9|6 intent #1?|7 is_final_version 8?|8 is_first_version 8?|9 contents_are_missing 8?|10 is_only_included_from_folder 8?|11 code_chunk_git_context #2?",St,yt,qt]}}var yt=(0,a.QT)(n.proto3,F,"ConversationMessage.CodeChunk.Intent",[[0,"UNSPECIFIED"],[1,"COMPOSER_FILE"],[2,"COMPRESSED_COMPOSER_FILE"],[3,"RECENTLY_VIEWED_FILE"],[4,"OUTLINE"],[5,"MENTIONED_FILE"],[6,"CODE_SELECTION"],[7,"AI_EDITED_FILE"],[8,"VISIBLE_FILE"],[9,"TERMINAL_SELECTION"]],1),St=(0,a.QT)(n.proto3,F,"ConversationMessage.CodeChunk.SummarizationStrategy",[[0,"NONE_UNSPECIFIED"],[1,"SUMMARIZED"],[2,"EMBEDDED"]],1);class qt extends K{constructor(t){super(),this.gitInfo=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["ConversationMessage.CodeChunk.CodeChunkGitContext|1 git_info #0*",Bt]}}class Bt extends K{constructor(t){super(),this.commit="",this.author="",this.date="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["ConversationMessage.CodeChunk.CodeChunkGitContext.CodeChunkGitInfo|1 commit 9|2 author 9|3 date 9|4 message 9"]}}class It extends K{constructor(t){super(),this.toolCallId="",this.toolName="",this.toolIndex=0,this.args="",this.rawArgs="",this.attachedCodeChunks=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["ConversationMessage.ToolResult|1 tool_call_id 9|2 tool_name 9|3 tool_index 13|12 model_call_id 9?|4 args 9|5 raw_args 9|6 attached_code_chunks #0*|7 content 9?|8 result #1|9 error #2?|10 images #3*|11 tool_call #4?|13 started_at_ms 4?|14 completed_at_ms 4?",wt,s.Ue3,s.MtQ,i.UR,s.TE4]}}class Pt extends K{constructor(t){super(),this.name="",this.text="",this.attachedCodeChunks=[],this.attachedFolders=[],this.commits=[],this.pullRequests=[],this.gitDiffs=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["ConversationMessage.NotepadContext|1 name 9|2 text 9|3 attached_code_chunks #0*|4 attached_folders 9*|5 commits #1*|6 pull_requests #2*|7 git_diffs #3*|8 images #4*",wt,Xt,Yt,i.o$,i.UR]}}class bt extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bt,t,r)}static $(){return["ConversationMessage.ComposerContext|1 name 9|2 conversation_summary #0",H]}}class Rt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.contextLines="",this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rt,t,r)}static $(){return["ConversationMessage.EditLocation|1 relative_workspace_path 9|3 range #0|4 initial_range #0|5 context_lines 9|6 text 9|7 text_range #0",i.l2]}}class vt extends K{constructor(t){super(),this.uniqueId="",this.editTrailSorted=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["ConversationMessage.EditTrailContext|1 unique_id 9|2 edit_trail_sorted #0*",Rt]}}class xt extends K{constructor(t){super(),this.message="",this.value="",this.startLine=0,this.endLine=0,this.startColumn=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["ConversationMessage.ApproximateLintError|1 message 9|2 value 9|3 start_line 5|4 end_line 5|5 start_column 5|6 end_column 5"]}}class kt extends K{constructor(t){super(),this.chatCodeblockModelValue="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["ConversationMessage.Lints|1 lints #0|2 chat_codeblock_model_value 9",D]}}class Et extends K{constructor(t){super(),this.relativeWorkspacePath="",this.lineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["ConversationMessage.RecentLocation|1 relative_workspace_path 9|2 line_number 5"]}}class Ct extends K{constructor(t){super(),this.startLineNumber=0,this.endLineNumberExclusive=0,this.beforeContextLines=[],this.removedLines=[],this.addedLines=[],this.afterContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["ConversationMessage.RenderedDiff|1 start_line_number 5|2 end_line_number_exclusive 5|3 before_context_lines 9*|4 removed_lines 9*|5 added_lines 9*|6 after_context_lines 9*"]}}class Tt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.renderedDiffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["ConversationMessage.HumanChange|1 relative_workspace_path 9|2 rendered_diffs #0*",Ct]}}class Ut extends K{constructor(t){super(),this.text="",this.signature="",this.redactedThinking="",this.isLastThinkingChunk=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["ConversationMessage.Thinking|1 text 9|2 signature 9|3 redacted_thinking 9|4 is_last_thinking_chunk 8"]}}class At extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(At,t,r)}static $(){return["ConversationMessage.DiffSinceLastApply|1 relative_workspace_path 9|2 diff #0?|4 is_accepted 8?|5 is_rejected 8?|6 last_apply_chained_from_n_human_messages_ago 5?",s.KRm]}}class $t extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["ConversationMessage.DeletedFile|1 relative_workspace_path 9"]}}class Mt extends K{constructor(t){super(),this.title="",this.knowledge="",this.knowledgeId="",this.isGenerated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["ConversationMessage.KnowledgeItem|1 title 9|2 knowledge 9|3 knowledge_id 9|4 is_generated 8"]}}class Ot extends K{constructor(t){super(),this.docId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["ConversationMessage.DocumentationSelection|1 doc_id 9|2 name 9"]}}class Dt extends K{constructor(t){super(),this.isPillDisplayed=!1,this.visibleFilePaths=[],this.recentlyViewedFilePaths=[],this.visibleFiles=[],this.recentlyViewedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["ConversationMessage.IdeEditorsState|1 is_pill_displayed 8|2 visible_file_paths 9*|3 recently_viewed_file_paths 9*|4 visible_files #0*|5 recently_viewed_files #0*",Nt]}}class Nt extends K{constructor(t){super(),this.relativePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["ConversationMessage.IdeEditorsState.File|1 relative_path 9|2 is_currently_focused 8?|3 current_line_number 5?|4 current_line_text 9?|5 line_count 5?|6 absolute_path 9?"]}}class Gt extends K{constructor(t){super(),this.currentPlan="",this.isFirstTimeSeen=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gt,t,r)}static $(){return["ConversationMessage.PlanUpdate|1 current_plan 9|2 is_first_time_seen 8"]}}class Lt extends K{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lt,t,r)}static $(){return["ConversationMessage.SimulatedMessageMetadata|1 title 9?|2 task_id 9?|3 fsd_finding_action 9?|4 url 9?|5 subscription_source #0?|6 subscription_event_display #1?|7 interaction_response #2?",A.vns,A.gan,A.nh0]}}class Ft extends K{constructor(t){super(),this.folderPath="",this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["ConversationMessage.McpDescriptor|1 folder_path 9|2 server_name 9?|3 tools #0*|4 server_use_instructions 9?",Kt]}}class Kt extends K{constructor(t){super(),this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["ConversationMessage.McpDescriptor.Tool|1 tool_name 9|2 description 9?"]}}class zt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.lineNumber=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zt,t,r)}static $(){return["CurrentFileLocationData|1 relative_workspace_path 9|2 line_number 5|3 text 9"]}}class jt extends K{constructor(t){super(),this.relativePath="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["FolderInfo|1 relative_path 9|2 files #0*",Ht]}}class Ht extends K{constructor(t){super(),this.relativePath="",this.content="",this.truncated=!1,this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["FolderFileInfo|1 relative_path 9|2 content 9|3 truncated 8|4 score 2"]}}class Wt extends K{constructor(t){super(),this.output="",this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wt,t,r)}static $(){return["InterpreterResult|1 output 9|2 success 8"]}}class Qt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["SimpleFileDiff|1 relative_workspace_path 9|3 chunks #0*",Vt]}}class Vt extends K{constructor(t){super(),this.oldLines=[],this.newLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["SimpleFileDiff.Chunk|1 old_lines 9*|2 new_lines 9*|3 old_range #0|4 new_range #0",i.MT]}}class Xt extends K{constructor(t){super(),this.sha="",this.message="",this.description="",this.diff=[],this.author="",this.date="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["Commit|1 sha 9|2 message 9|3 description 9|4 diff #0*|5 author 9|6 date 9",i.QP]}}class Yt extends K{constructor(t){super(),this.title="",this.body="",this.diff=[],this.id=n.protoInt64.zero,this.number=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["PullRequest|1 title 9|2 body 9|3 diff #0*|4 id 3|5 number 3",i.QP]}}class Zt extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["SuggestedCodeBlock|1 relative_workspace_path 9"]}}class tr extends K{constructor(t){super(),this.userResponseType=rr.UNSPECIFIED,this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tr,t,r)}static $(){return["UserResponseToSuggestedCodeBlock|1 user_response_type #0|2 file_path 9|3 user_modifications_to_suggested_code_blocks #1?",rr,i.QP]}}var rr=(0,a.QT)(n.proto3,F,"UserResponseToSuggestedCodeBlock.UserResponseType",[[0,"UNSPECIFIED"],[1,"ACCEPT"],[2,"REJECT"],[3,"MODIFY"]],1);class er extends K{constructor(t){super(),this.fileName="",this.fileContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(er,t,r)}static $(){return["ContextRerankingCandidateFile|1 file_name 9|2 file_content 9"]}}class nr extends K{constructor(t){super(),this.chunks=[],this.editor=sr.UNSPECIFIED,this.hitTimeout=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nr,t,r)}static $(){return["ComposerFileDiff|1 chunks #0*|2 editor #1|3 hit_timeout 8",ir,sr]}}var sr=(0,a.QT)(n.proto3,F,"ComposerFileDiff.Editor",[[0,"UNSPECIFIED"],[1,"AI"],[2,"HUMAN"]],1);class ir extends K{constructor(t){super(),this.diffString="",this.oldStart=0,this.newStart=0,this.oldLines=0,this.newLines=0,this.linesRemoved=0,this.linesAdded=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ir,t,r)}static $(){return["ComposerFileDiff.ChunkDiff|1 diff_string 9|2 old_start 5|3 new_start 5|4 old_lines 5|5 new_lines 5|6 lines_removed 5|7 lines_added 5"]}}class or extends K{constructor(t){super(),this.relativeWorkspacePath="",this.diffs=[],this.timestamp=0,this.uniqueId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["DiffHistoryData|1 relative_workspace_path 9|2 diffs #0*|3 timestamp 1|4 unique_id 9|5 start_to_end_diff #0",nr]}}n.proto3,n.proto3,n.proto3,n.proto3;class ar extends K{constructor(t){super(),this.subagentType=j.UNSPECIFIED,this.returnValue={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["SubagentReturnCall|1 subagent_type #0|2 deep_search_return_value #1 return_value|3 fix_lints_return_value #2 return_value|4 task_return_value #3 return_value|5 spec_return_value #4 return_value",j,ur,lr,mr,fr]}}class ur extends K{constructor(t){super(),this.contextItems=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["DeepSearchSubagentReturnValue|1 context_items #0*",cr]}}class cr extends K{constructor(t){super(),this.file="",this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["DeepSearchSubagentReturnValue.ContextItem|1 file 9|2 line_range #0?|3 explanation 9",i.MT]}}class lr extends K{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["FixLintsSubagentReturnValue"]}}class mr extends K{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["TaskSubagentReturnValue|1 summary 9"]}}class fr extends K{constructor(t){super(),this.summary="",this.stringReplacements=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["SpecSubagentReturnValue|1 summary 9|2 string_replacements #0*",dr]}}class dr extends K{constructor(t){super(),this.oldString="",this.newString="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dr,t,r)}static $(){return["StringReplacement|1 old_string 9|2 new_string 9"]}}class pr extends K{constructor(t){super(),this.rootPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["ProjectLayout|1 root_path 9|2 content #0|3 list_dir_v2_result #1?",hr,s.$rP]}}class hr extends K{constructor(t){super(),this.directories=[],this.files=[],this.hiddenFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["ProjectLayoutDirectoryContent|1 directories #0*|2 files #1*|3 total_files 5?|4 total_subfolders 5?|5 hidden_files #1*",gr,_r]}}class gr extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["ProjectLayoutDirectory|1 name 9|2 content #0",hr]}}class _r extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["ProjectLayoutFile|1 name 9"]}}},"../proto/dist/generated/aiserver/v1/dashboard_pb.js"(t,r,e){e.d(r,{LRJ:()=>bm,bCe:()=>Rm,MSh:()=>xs,Hdf:()=>Is,uHx:()=>ll,yDS:()=>ml,bo5:()=>UC,xWW:()=>AC,fdV:()=>OM,VVb:()=>DM,gMg:()=>oP,yD7:()=>aP,zyk:()=>rz,LLT:()=>ez,Hcr:()=>UE,he9:()=>AE,Y9_:()=>aG,CeW:()=>uG,U8V:()=>oa,mf3:()=>aa,ggo:()=>ga,aHm:()=>_a,$n5:()=>li,pji:()=>v_,D3c:()=>x_,yqO:()=>Ua,Gc8:()=>Aa,Ipj:()=>Dz,a0c:()=>Nz,ZM7:()=>V_,ufl:()=>Q_,GJd:()=>DD,LmS:()=>ND,mi9:()=>ky,Izq:()=>Cy,flJ:()=>ED,SZm:()=>CD,Wew:()=>Yh,AZo:()=>Zh,c2n:()=>XD,ISv:()=>YD,flK:()=>Wb,Pqr:()=>Qb,X2v:()=>Md,B6m:()=>Od,bJ2:()=>ZK,TOY:()=>tz,aFD:()=>ok,W5r:()=>uk,t3S:()=>DE,PXK:()=>GE,VN4:()=>ki,nPy:()=>Ci,Vi2:()=>LF,lXe:()=>FF,v_r:()=>hl,$n:()=>gl,pAq:()=>Ex,LOM:()=>Cx,HZm:()=>Pg,lRG:()=>bg,oOo:()=>Rg,MIx:()=>vg,IV$:()=>bB,yW5:()=>AB,yD0:()=>al,MEI:()=>ul,ukN:()=>p_,cRU:()=>h_,MRM:()=>__,wb2:()=>J_,QKN:()=>iE,wmq:()=>oE,iOH:()=>HO,g5C:()=>WO,uBx:()=>Uw,_rf:()=>Aw,H5i:()=>cU,zah:()=>lU,wKn:()=>LK,wIY:()=>FK,n$8:()=>aK,VxM:()=>uK,KBr:()=>Ju,EAu:()=>wu,OjU:()=>Rn,Ohd:()=>vn,vJq:()=>OG,PaT:()=>DG,wm7:()=>IC,O$A:()=>PC,tI8:()=>ms,xpT:()=>fs,$bV:()=>ep,boh:()=>np,bWR:()=>xx,FQR:()=>kx,SH9:()=>Jn,_$M:()=>yn,X38:()=>_m,tZA:()=>Jm,wlK:()=>hx,Adp:()=>gx,ecT:()=>mk,YdR:()=>fk,ign:()=>ro,WSJ:()=>eo,vaB:()=>Cs,rzz:()=>Ts,nL6:()=>Cm,rEt:()=>Tm,S3E:()=>sc,o6Z:()=>oc,sJl:()=>ec,ukh:()=>nc,_do:()=>PS,EAb:()=>bS,Bdx:()=>SA,Zk6:()=>qA,CHh:()=>aA,GL9:()=>uA,ZN0:()=>Mf,DdV:()=>Of,byf:()=>nd,vXf:()=>sd,m5V:()=>zm,MSw:()=>jm,d7o:()=>NF,LRW:()=>GF,Z9k:()=>$K,rxf:()=>MK,Vbl:()=>wK,lQ7:()=>yK,p8r:()=>vE,Dsz:()=>xE,OoP:()=>LL,gZI:()=>FL,XQi:()=>Ah,FGN:()=>$h,KFb:()=>Bd,WRW:()=>Id,C1F:()=>Vo,wqi:()=>Xo,ed4:()=>Po,urU:()=>Ro,Cqw:()=>yu,mk5:()=>Su,JoU:()=>gu,vU:()=>_u,iQx:()=>Wi,uYE:()=>ao,bhY:()=>s_,XEQ:()=>i_,PTe:()=>_l,pF3:()=>Jl,hzU:()=>hD,rfl:()=>gD,XAW:()=>Pl,bTQ:()=>bl,IW3:()=>A_,wmn:()=>$_,BwS:()=>rC,dnd:()=>eC,PwZ:()=>hC,vFW:()=>gC,C10:()=>Yp,e7b:()=>th,EMn:()=>Dk,QEY:()=>Nk,Cbz:()=>GD,Gf$:()=>LD,_C2:()=>km,Mdl:()=>Em,Ctq:()=>GU,CXw:()=>LU,BEg:()=>Gy,Rz7:()=>Fy,qxp:()=>QC,uts:()=>VC,eW$:()=>qb,eQk:()=>Bb,Qx5:()=>Sy,M3e:()=>qy,oJv:()=>vu,UPX:()=>xu,cbD:()=>va,CiW:()=>xa,WxI:()=>BU,AkX:()=>IU,lW:()=>Nu,$a1:()=>Gu,wT7:()=>CU,a4I:()=>TU,J4c:()=>I_,fCO:()=>P_,nxO:()=>ig,vgA:()=>og,J7F:()=>hU,vZv:()=>gU,HYO:()=>xd,loJ:()=>kd,LAq:()=>yc,x2A:()=>Sc,BlC:()=>qc,Dd7:()=>Bc,cj_:()=>jy,SyP:()=>Hy,_Qn:()=>Jh,UzA:()=>wh,Q1P:()=>XM,kJb:()=>YM,cEg:()=>sp,Aa9:()=>ip,uDD:()=>El,EO4:()=>Cl,azC:()=>dd,cSQ:()=>pd,rhR:()=>zf,RVM:()=>jf,ndP:()=>wj,FRR:()=>yj,gqj:()=>Ss,wER:()=>qs,o0f:()=>iB,mTO:()=>oB,opt:()=>is,ABq:()=>os,hnR:()=>JA,Ld4:()=>wA,ONG:()=>RA,YYN:()=>vA,pj7:()=>mA,rP9:()=>fA,J5_:()=>x$,xQH:()=>k$,Yiy:()=>aF,YY6:()=>uF,mZ$:()=>Mn,WBx:()=>On,iVu:()=>Wn,wuD:()=>Qn,nc6:()=>Yf,Hdd:()=>Zf,aW7:()=>ad,_yh:()=>ud,nG3:()=>Hm,T78:()=>Wm,W5o:()=>NK,c0r:()=>GK,Pzk:()=>ZF,n2r:()=>tK,yqI:()=>_K,YxF:()=>JK,SBx:()=>CE,uDb:()=>TE,XeB:()=>jL,zNr:()=>HL,qtO:()=>Fh,eVU:()=>Kh,pe4:()=>ko,Huq:()=>Eo,tE7:()=>M_,R1c:()=>O_,gwk:()=>iC,CN_:()=>oC,gFI:()=>_C,c7s:()=>JC,shm:()=>VA,_Md:()=>XA,FUz:()=>D$,Z36:()=>N$,CGB:()=>Vk,sHT:()=>Xk,Bz7:()=>Gk,Tfn:()=>Lk,xo6:()=>zU,atP:()=>jU,t1u:()=>ZC,rFi:()=>tT,p9b:()=>Ca,VyS:()=>Ta,lIO:()=>RU,jqE:()=>vU,mA:()=>Lu,U1k:()=>Fu,x4u:()=>$U,FNs:()=>MU,m0x:()=>b_,Cw0:()=>R_,Ch8:()=>wU,uzD:()=>yU,IaO:()=>Ad,WLQ:()=>$d,LME:()=>ZM,rJY:()=>tO,hSg:()=>Jd,rGX:()=>wd,c9k:()=>Vb,gTH:()=>Xb,_mp:()=>tp,sX6:()=>rp,tm2:()=>jE,prK:()=>HE,I5D:()=>BL,e0h:()=>IL,ru_:()=>hF,dyp:()=>gF,jzf:()=>Im,zu1:()=>Pm,D57:()=>hs,llV:()=>gs,KQv:()=>SL,S0I:()=>qL,Xqi:()=>Bx,vXd:()=>Ix,dBq:()=>Jk,VS:()=>wk,sg4:()=>KG,a3K:()=>zG,m_x:()=>TN,EPm:()=>AN,toG:()=>Xc,V$m:()=>Yc,Cul:()=>ib,Y9v:()=>ob,UfC:()=>QI,gJO:()=>VI,jiB:()=>Cn,Z48:()=>Tn,ke0:()=>KK,q1P:()=>zK,RwL:()=>vs,oNu:()=>Bs,hWx:()=>il,dr7:()=>ol,pg$:()=>oU,fSY:()=>aU,gJU:()=>qC,mib:()=>BC,P1T:()=>Zq,VxL:()=>tB,CQB:()=>$s,WQf:()=>Ms,l4W:()=>pb,JZY:()=>hb,Mq$:()=>_b,mTp:()=>Jb,rav:()=>gh,$bx:()=>_h,T1q:()=>YU,RNi:()=>ZU,Nbg:()=>Ai,xel:()=>Mi,Qrr:()=>uy,DfW:()=>PL,lpX:()=>bL,y90:()=>JL,YmN:()=>wL,DrQ:()=>BS,ZhM:()=>IS,Jns:()=>jB,Fkp:()=>HB,meH:()=>KT,ym8:()=>zT,I6A:()=>XP,aBI:()=>YP,JWI:()=>FB,NXG:()=>KB,Nux:()=>OI,hxv:()=>DI,hp9:()=>dA,z7W:()=>pA,qF$:()=>BA,azW:()=>IA,wS2:()=>$T,sWv:()=>MT,sVJ:()=>NT,YHh:()=>GT,lvI:()=>EA,RK5:()=>CA,TOm:()=>UA,tkD:()=>AA,Ioc:()=>GB,GNy:()=>LB,nTs:()=>qI,ZJ6:()=>BI,N8K:()=>iA,RP_:()=>oA,BHX:()=>yP,DLm:()=>SP,zyT:()=>s$,hcJ:()=>i$,SNZ:()=>o$,wEJ:()=>a$,gDx:()=>u$,K6f:()=>l$,dAQ:()=>P$,$sY:()=>b$,Xhp:()=>Ag,JRd:()=>$g,u_0:()=>aS,gHM:()=>uS,V8e:()=>Vq,Pqo:()=>Xq,G24:()=>rA,gNl:()=>nA,ISZ:()=>lJ,yTE:()=>mJ,Hdt:()=>cR,F9z:()=>lR,mPq:()=>qm,i5j:()=>Bm,MjR:()=>Wq,CkD:()=>Qq,yI7:()=>MB,cTj:()=>OB,Dl4:()=>lS,bO3:()=>mS,pmk:()=>uq,LwP:()=>lq,y4P:()=>iL,WY9:()=>oL,irI:()=>_E,GlZ:()=>wE,hst:()=>dj,zUO:()=>pj,aPV:()=>XB,w_Q:()=>YB,LYo:()=>fE,PJy:()=>dE,r$m:()=>g$,ZB$:()=>J$,Upy:()=>Cg,AlS:()=>Ug,hVj:()=>KJ,b$E:()=>zJ,EwF:()=>xN,KhO:()=>EN,i6G:()=>Wg,i0P:()=>Qg,RiQ:()=>eU,XUY:()=>nU,iSm:()=>ws,aUJ:()=>ys,FHO:()=>fb,TpA:()=>db,i20:()=>UP,M7A:()=>AP,y$W:()=>IP,Ik0:()=>PP,Nmm:()=>tU,Xa_:()=>rU,Owv:()=>hI,yq_:()=>gI,kcC:()=>VB,UYU:()=>fI,XT3:()=>oI,HyV:()=>aI,jp5:()=>cs,dpH:()=>ls,Ryr:()=>nb,FPs:()=>sb,YSR:()=>WU,rL_:()=>QU,A9x:()=>Xv,u01:()=>Yv,$7Y:()=>hm,LoC:()=>gm,wcH:()=>GS,cQ7:()=>FS,ovf:()=>Wf,_oI:()=>Qf,_NS:()=>nf,eTm:()=>sf,nxD:()=>Af,Hux:()=>$f,lxC:()=>vf,nxh:()=>xf,SuU:()=>If,yms:()=>Pf,Muw:()=>_z,OFG:()=>Sz,yED:()=>Jz,_2X:()=>wz,jRA:()=>kF,N2o:()=>AF,X26:()=>OF,RhX:()=>EF,VGL:()=>UK,lj2:()=>AK,Vt$:()=>dK,$X0:()=>pK,Il7:()=>qz,SMz:()=>Pz,sLc:()=>xz,CC0:()=>Tz,eNQ:()=>uf,efP:()=>lf,Mly:()=>nK,QJW:()=>sK,dt7:()=>rK,p0o:()=>eK,i$e:()=>bE,StO:()=>RE,CY$:()=>IE,WsC:()=>PE,g6R:()=>$c,oyU:()=>Mc,toQ:()=>XI,P4d:()=>tP,L$Y:()=>HI,ljc:()=>WI,E8o:()=>DN,C17:()=>NN,m8H:()=>cL,G4o:()=>lL,k0s:()=>TL,EGh:()=>UL,XUt:()=>NL,ZU4:()=>GL,CJ0:()=>dL,qZs:()=>pL,WCk:()=>AL,CyC:()=>$L,ND4:()=>ag,Rkv:()=>cg,_9N:()=>dx,wet:()=>px,PG$:()=>nk,bBu:()=>sk,a3w:()=>rk,eZU:()=>ek,MFi:()=>Wx,C0g:()=>Qx,xGO:()=>Sx,zOq:()=>qx,v5z:()=>Gx,HMD:()=>Lx,X8g:()=>eL,p_E:()=>sL,fZH:()=>Qv,hBo:()=>Vv,pUz:()=>EG,hHr:()=>CG,Ewt:()=>Us,S7I:()=>As,BF8:()=>Bg,t__:()=>Ig,_GX:()=>Iq,Q50:()=>Pq,vDB:()=>_x,bIf:()=>Jx,iaP:()=>DB,KuC:()=>NB,yO3:()=>kc,Si_:()=>Ec,Udp:()=>Lv,_am:()=>jv,NEG:()=>Qh,dtn:()=>Vh,q$3:()=>cG,mht:()=>lG,ubJ:()=>yE,DXb:()=>jc,D42:()=>Wc,BHf:()=>ea,lqZ:()=>na,dIX:()=>Ib,fIK:()=>Pb,GoS:()=>Sv,O8k:()=>Bv,jIe:()=>KR,JEj:()=>zR,Yeg:()=>Ry,eBq:()=>xy,iS1:()=>_v,_ax:()=>Jv,QOh:()=>Lo,qbQ:()=>Fo,ZKL:()=>Co,f43:()=>To,nQH:()=>So,rd8:()=>qo,M89:()=>Oo,qlA:()=>Do,wH4:()=>Jo,uwp:()=>wo,bPz:()=>ma,H0j:()=>fa,H8G:()=>jo,rt0:()=>Ho,f5k:()=>go,ZJV:()=>_o,UvC:()=>au,SkP:()=>uu,lN3:()=>Ys,vBH:()=>Zs,cF_:()=>Qs,SY0:()=>Vs,bXT:()=>wi,TQ7:()=>yi,YtZ:()=>pu,UZr:()=>hu,Twg:()=>NR,$H2:()=>GR,Vie:()=>jz,vsf:()=>Hz,Ok7:()=>Vz,Ajm:()=>Yz,ZPB:()=>iv,vfT:()=>ov,C61:()=>Gg,_J0:()=>co,OBE:()=>lo,Exr:()=>pa,aYg:()=>ha,pPB:()=>dv,DxY:()=>pv,kxz:()=>cv,wFu:()=>lv,_v$:()=>WR,yj0:()=>QR,rgp:()=>mo,xa_:()=>po,q9G:()=>Jq,MQS:()=>wq,EcQ:()=>m_,nd7:()=>f_,pGh:()=>o_,XWY:()=>a_,Ig_:()=>ck,Esv:()=>lk,bo4:()=>hk,twU:()=>gk,JmO:()=>dk,bUD:()=>pk,qWG:()=>pB,YJY:()=>gB,jWS:()=>Gm,J41:()=>Lm,V4G:()=>kS,noV:()=>ES,vVx:()=>nD,fAb:()=>sD,Akd:()=>Ic,i7t:()=>Pc,kSp:()=>rD,O5b:()=>eD,TXH:()=>T_,P_k:()=>U_,dwF:()=>QO,t5n:()=>VO,aE$:()=>zA,OCF:()=>HA,ROu:()=>F$,xfP:()=>K$,Xoe:()=>Wl,ZoZ:()=>Ql,Vqj:()=>Vl,pty:()=>Xl,xGV:()=>tL,$EH:()=>rL,bT6:()=>e_,D2n:()=>n_,Gch:()=>t_,gBX:()=>r_,Xdv:()=>bR,hzd:()=>RR,LM4:()=>VU,hcQ:()=>XU,qc8:()=>tJ,Mtj:()=>rJ,n$I:()=>Dg,fMg:()=>Ng,l9M:()=>WE,nPZ:()=>XE,Lys:()=>tI,VS9:()=>rI,tJ9:()=>nI,lIF:()=>sI,ZPw:()=>PI,ZOX:()=>bI,f_r:()=>vR,bJx:()=>xR,JF:()=>FA,B2G:()=>KA,MyJ:()=>A$,mvz:()=>$$,u_Q:()=>xg,WsA:()=>kg,BaG:()=>mO,zYR:()=>fO,eOv:()=>jk,gpX:()=>Hk,St:()=>jl,QKj:()=>Hl,aew:()=>Ck,gjm:()=>Tk,lym:()=>Yl,ddf:()=>Zl,hE5:()=>Mk,LGY:()=>Ok,tcG:()=>Kl,no:()=>zl,YAE:()=>Dl,YyD:()=>Gl,e0r:()=>yk,ewI:()=>Sk,zEV:()=>Lc,pig:()=>Fc,_$o:()=>Mg,Opj:()=>Og,Din:()=>Xd,BMV:()=>Yd,Byz:()=>D_,V5U:()=>Hw,FFq:()=>Wy,LLA:()=>Qy,TdK:()=>Cu,v6H:()=>Tu,CNw:()=>kM,iR7:()=>EM,kfB:()=>UM,iwy:()=>AM,OmT:()=>IM,GoT:()=>PM,fQ:()=>KM,bNb:()=>zM,LRN:()=>$C,Lg7:()=>OC,XDt:()=>DU,lzR:()=>NU,qjo:()=>dl,M_:()=>pl,LWe:()=>aT,F8Y:()=>uT,mD_:()=>iT,wGo:()=>oT,n$w:()=>HC,R9K:()=>WC,ZvO:()=>mw,bhm:()=>fw,yk8:()=>sP,ecN:()=>iP,Mx4:()=>Va,gDX:()=>Xa,bK1:()=>Na,bJ:()=>Ga,J67:()=>ba,VBR:()=>Ra,s$M:()=>ja,MJ:()=>Ha,UQh:()=>Ba,cUB:()=>Ia,vdM:()=>SU,Xu9:()=>qU,DWT:()=>Mz,hSD:()=>Oz,hu7:()=>Iu,BPt:()=>Pu,JbB:()=>Sa,nrv:()=>qa,MrA:()=>Jc,gJp:()=>wc,$kg:()=>kU,PtB:()=>EU,_CN:()=>_g,Kww:()=>Jg,TB_:()=>ST,nE8:()=>qT,lax:()=>xT,rM7:()=>TT,Y44:()=>nu,kE_:()=>su,C4p:()=>im,gRj:()=>om,h1G:()=>vm,doQ:()=>xm,Pxo:()=>Ds,RR2:()=>Ns,v8R:()=>vw,dsv:()=>xw,Obu:()=>pg,S5H:()=>gg,jcw:()=>ZO,X5_:()=>tD,Imd:()=>tm,QI7:()=>sm,XRZ:()=>My,pv1:()=>Oy,NES:()=>N_,Fj9:()=>G_,ax8:()=>_N,_lt:()=>JN,LGu:()=>lN,PnF:()=>mN,i9d:()=>fN,sev:()=>pN,FcH:()=>Sl,$qn:()=>ql,lKh:()=>ju,rsP:()=>Hu,VNQ:()=>Zz,NYc:()=>tj,aJE:()=>yM,SRO:()=>SM,H1L:()=>oM,P8_:()=>aM,K$9:()=>NM,yVw:()=>GM,hUh:()=>Yy,dZ5:()=>Zy,DVl:()=>bv,V$7:()=>Rv,aYW:()=>y_,k1F:()=>S_,EwB:()=>Fd,Eav:()=>zd,yds:()=>dU,KZ$:()=>pU,Uto:()=>nl,EHd:()=>sl,e6P:()=>_B,SuY:()=>JB,Y$T:()=>mB,o35:()=>dB,LWu:()=>gM,fZU:()=>_M,_b6:()=>z$,yTb:()=>j$,FO$:()=>NG,hFv:()=>GG,WjG:()=>eM,OBF:()=>nM,$Sc:()=>aB,R2E:()=>cB,WsN:()=>YR,Afl:()=>ZR,ScF:()=>ev,rcf:()=>Wu,Jcx:()=>Qu,EZo:()=>tl,m0q:()=>rl,SK5:()=>rB,I9h:()=>eB,yIy:()=>Py,C2K:()=>by,nDb:()=>Vg,n8L:()=>Xg,qhH:()=>Aq,I_D:()=>Oq,S9t:()=>Dq,_ty:()=>Fq,_V:()=>rP,KLX:()=>eP,dcL:()=>Vy,n24:()=>Xy,V2d:()=>Os,NjL:()=>Ks,b4u:()=>Rl,$H_:()=>vl,KoG:()=>gR,mWk:()=>_R,mH6:()=>FO,CZF:()=>KO,Mq:()=>pP,M2w:()=>hP,Jjk:()=>JP,$DS:()=>wP,SC5:()=>AD,_kg:()=>$D,c$y:()=>fM,cHR:()=>dM,hsE:()=>XO,vuk:()=>YO,hD2:()=>Tl,ZoF:()=>$l,yq2:()=>Mx,$TS:()=>Px,$0p:()=>bx,jq0:()=>wB,f1t:()=>PB,WAE:()=>Ty,qSX:()=>Ay,DLp:()=>Kg,R$$:()=>zg,i24:()=>Vt,Pt$:()=>Bj,Tmx:()=>Ij,UEe:()=>vL,I67:()=>xL,hvD:()=>JI,p84:()=>wI,q0X:()=>pc,Rq9:()=>sr,lgO:()=>oy,NNb:()=>VS,Zm8:()=>XS,B5B:()=>YS,bh8:()=>ZS,Jjf:()=>SN,hsS:()=>IN,Bi3:()=>nN,jsr:()=>sN,WCl:()=>WS,GYE:()=>QS,p$r:()=>aE,Jag:()=>uE,vfb:()=>cE,$8m:()=>lE,HxK:()=>Yk,jAL:()=>Zk,E2N:()=>lg,iX6:()=>mg,Uao:()=>mL,Gdv:()=>fL,DWb:()=>WL,Fi2:()=>QL,AkD:()=>HD,w2N:()=>WD,PuH:()=>VG,n1r:()=>XG,pVr:()=>kj,jNM:()=>Ej,upR:()=>_j,U2t:()=>Jj,aul:()=>tg,c$T:()=>eg,$F$:()=>Yu,dnq:()=>Zu,Q3t:()=>Yn,Oef:()=>Zn,hHX:()=>mR,D7O:()=>fR,Ezc:()=>dm,cDB:()=>pm,gNW:()=>ym,SuV:()=>Sm,UkG:()=>nh,S$9:()=>ih,CCH:()=>cj,EdW:()=>lj,bHh:()=>sF,jWD:()=>oF,mbE:()=>rF,y5v:()=>nF,KHx:()=>zP,GPC:()=>jP,LdP:()=>xP,l1H:()=>kP,Hrn:()=>HP,pxf:()=>WP,CXL:()=>DP,ybH:()=>NP,k6E:()=>Un,a$2:()=>An,gvC:()=>Gn,WaG:()=>Ln,OOr:()=>Tf,iwb:()=>Uf,cl3:()=>rd,cf9:()=>ed,yeW:()=>SF,ANW:()=>qF,V5S:()=>Fm,lc$:()=>Km,Zav:()=>TF,DyZ:()=>UF,rih:()=>vF,dKG:()=>xF,FFN:()=>zF,dO8:()=>jF,RAf:()=>XK,nYQ:()=>YK,Q_u:()=>QK,Sj7:()=>VK,a_n:()=>CK,g$E:()=>TK,ned:()=>WF,R6h:()=>QF,udh:()=>mK,ahg:()=>fK,flG:()=>cz,fMA:()=>lz,_Yf:()=>gf,g9i:()=>_f,dU3:()=>df,pxp:()=>pf,Vg9:()=>yf,xXb:()=>Sf,AB7:()=>$N,g7m:()=>ON,yMo:()=>Rc,G8V:()=>xc,WXZ:()=>oR,YeS:()=>uR,LuE:()=>gL,VG3:()=>_L,KaV:()=>VL,ySt:()=>XL,ZMX:()=>xO,vEP:()=>kO,iPX:()=>iG,A8F:()=>oG,Cl5:()=>mp,UEj:()=>fp,NsN:()=>Wp,wLf:()=>uO,Sot:()=>cO,_2n:()=>Th,WAf:()=>Uh,bC9:()=>Rd,Xtv:()=>vd,UTl:()=>dC,i4X:()=>pC,rq6:()=>oi,dSe:()=>ai,AUt:()=>jp,Y1Y:()=>Si,G2s:()=>qi,jrM:()=>kv,quH:()=>Pk,eK8:()=>bk,YNI:()=>no,yaP:()=>so,Z_i:()=>dR,jiy:()=>hR,_YH:()=>yS,_i_:()=>qS,nMU:()=>TO,lqq:()=>UO,zdO:()=>HK,HwU:()=>WK,ERl:()=>Cv,Dxu:()=>ZE,LM8:()=>tC,lmw:()=>uC,na4:()=>cC,OWn:()=>mC,c3u:()=>fC,A_u:()=>Pj,IWi:()=>bj,v0n:()=>rh,X1$:()=>eh,xos:()=>WA,xTz:()=>QA,R28:()=>M$,nMz:()=>O$,vV7:()=>qk,vcR:()=>Ik,iHk:()=>oO,gsv:()=>aO,N8I:()=>kk,pZm:()=>Ek,W22:()=>YN,SwX:()=>rG,dMs:()=>Mm,Tsf:()=>Om,l2q:()=>Cj,Lsm:()=>Tj,pbO:()=>CM,xim:()=>TM,$_i:()=>hN,B0l:()=>gN,F70:()=>kp,$bL:()=>Ep,CAc:()=>Ky,GYk:()=>zy,qC3:()=>yb,wHV:()=>Sb,DEE:()=>Uu,xUt:()=>Au,nsd:()=>$u,xYI:()=>Mu,QE:()=>Ou,gsU:()=>Du,sbK:()=>Cb,ofK:()=>Ub,$WS:()=>xb,Rc0:()=>Eb,ryS:()=>jb,rV_:()=>Hb,Ifk:()=>Kp,E7o:()=>Db,MLT:()=>Nb,IJt:()=>GN,pNK:()=>LN,P0D:()=>Ev,SMM:()=>Ed,AhK:()=>Cd,rd_:()=>ph,rkz:()=>hh,kCx:()=>gS,izO:()=>_S,esR:()=>F_,eiD:()=>K_,QBt:()=>_F,SQ3:()=>JF,wfW:()=>QM,UB9:()=>VM,juR:()=>up,ZCs:()=>cp,P_7:()=>e$,H1r:()=>n$,OHt:()=>rN,UgB:()=>eN,R_i:()=>Ox,hN$:()=>Nx,_Br:()=>yd,ylO:()=>Sd,ruw:()=>md,xAe:()=>fd,DJN:()=>Aj,X4T:()=>$j,WEP:()=>ew,odJ:()=>tr,Not:()=>eE,T0x:()=>sE,HOD:()=>tE,pQL:()=>rE,ptC:()=>YA,$bK:()=>ZA,YUq:()=>Uj,JLr:()=>tt,mne:()=>BN,Vsr:()=>Z,eJC:()=>_c,SAH:()=>di,mOD:()=>pi,tE_:()=>at,E3$:()=>rb,MPB:()=>eb,LIs:()=>GC,lW1:()=>LC,kiI:()=>Bi,gqE:()=>Ii,WWi:()=>IR,U5k:()=>PR,_mX:()=>Qt,anf:()=>yC,WJW:()=>SC,P4:()=>bC,HdK:()=>RC,wfI:()=>ir,ggh:()=>SD,nXe:()=>BD,VWM:()=>ID,HiH:()=>PD,k_1:()=>PO,vwy:()=>eG,FMO:()=>hi,PUH:()=>_i,xYM:()=>wl,uif:()=>Bn,EJq:()=>bn,jPV:()=>kn,lP:()=>En,OeX:()=>LE,Wow:()=>zE,Q66:()=>MD,b48:()=>OD,CrG:()=>Xi,YQr:()=>Yi,dOz:()=>kD,smL:()=>xD,qkO:()=>_D,YPJ:()=>JD,sDp:()=>cb,Uj4:()=>mb,QL_:()=>EO,iMY:()=>CO,VF8:()=>sU,Djf:()=>iU,ziV:()=>YT,lme:()=>ZT,J_n:()=>JS,BLE:()=>wS,TGZ:()=>m$,d6S:()=>f$,YDo:()=>hG,cBR:()=>gG,H1p:()=>ds,DUo:()=>ps,Dxc:()=>wG,ZHm:()=>SG,hEC:()=>bh,XUz:()=>Rh,BRM:()=>_G,loc:()=>JG,h$Z:()=>az,lWu:()=>uz,WZo:()=>ZD,oGE:()=>tN,RJA:()=>Gf,$ph:()=>Lf,GsS:()=>iz,YjQ:()=>oz,im6:()=>$E,SSe:()=>ME,Bqo:()=>dG,PQd:()=>pG,mig:()=>Sg,sX9:()=>qg,xQP:()=>ua,TGX:()=>ca,dSX:()=>Ja,nS1:()=>wa,SFI:()=>mi,sw6:()=>zD,qVu:()=>jD,rLu:()=>Ri,Puo:()=>vi,MEU:()=>k_,U0s:()=>E_,rA4:()=>$a,lER:()=>Ma,X6C:()=>Gz,$Fl:()=>Lz,k5b:()=>E$,icQ:()=>C$,Bwq:()=>Cw,nUL:()=>Tw,JrS:()=>nO,HJo:()=>sO,Y6P:()=>ta,QeE:()=>ra,rF_:()=>Yo,DmQ:()=>Zo,be7:()=>ku,THz:()=>Eu,Y53:()=>Fb,Ip9:()=>Kb,ePV:()=>$o,EuD:()=>Mo,L2q:()=>lM,Jiu:()=>mM,I3c:()=>Ka,Qnc:()=>za,_dj:()=>UT,Mob:()=>AT,lpG:()=>uP,LlT:()=>lP,WvV:()=>nG,UgI:()=>sG,OaX:()=>oJ,MX_:()=>aJ,Eg0:()=>KS,c6S:()=>jS,ovZ:()=>sa,gdR:()=>ia,HCf:()=>Sj,x6X:()=>qj,X58:()=>ng,tXQ:()=>sg,AU3:()=>lc,keR:()=>mc,Eh$:()=>kL,aIo:()=>EL,H5R:()=>WT,Tcn:()=>QT,Rig:()=>yI,neC:()=>SI,$lB:()=>SK,XSC:()=>qK,Gci:()=>pp,K_N:()=>hp,ElN:()=>Qp,W6d:()=>Pd,G0c:()=>bd,fOQ:()=>Hp,CdP:()=>Av,lvC:()=>Mv,yYY:()=>uh,w$r:()=>ch,$qF:()=>FD,JUz:()=>KD,_Rg:()=>Um,ubM:()=>Am,yKm:()=>Rb,mmN:()=>vb,kwX:()=>Ab,WRC:()=>Mb,vDi:()=>zp,BaU:()=>Gb,tRU:()=>Lb,Apo:()=>$v,VDS:()=>kh,nRh:()=>Eh,g7r:()=>vh,A7H:()=>xh,kUF:()=>Ih,OV9:()=>Ph,GOY:()=>op,yQR:()=>ap,Z$K:()=>VT,FOE:()=>XT,QAx:()=>Oj,_Hq:()=>Dj,eor:()=>jn,oTi:()=>Hn,pTw:()=>Zm,DZc:()=>tf,wid:()=>Dh,MwB:()=>Nh,OCy:()=>Gd,sJP:()=>Ld,Rbl:()=>lh,t8U:()=>mh,B8P:()=>PT,HQR:()=>bT,Ebu:()=>d$,E7l:()=>p$,rb7:()=>xA,DkK:()=>kA,SDZ:()=>nr,JE6:()=>nw,h0i:()=>Xt,faf:()=>Wt,XRd:()=>$M,joE:()=>MM,v35:()=>jG,pdK:()=>WG,C4E:()=>vp,ya8:()=>xp,PBS:()=>dq,JZ6:()=>gq,EiN:()=>RS,e0Y:()=>vS,e5r:()=>pO,C3d:()=>hO,ZKX:()=>u_,tZb:()=>c_,cn:()=>am,YBJ:()=>um,Naf:()=>cm,pF$:()=>lm,wQX:()=>eq,izm:()=>iq,SAF:()=>Lg,Ix8:()=>Fg,uKx:()=>w$,_w7:()=>y$,V6X:()=>EP,tJA:()=>CP,YBO:()=>GP,Soi:()=>LP,Rns:()=>Kn,PFp:()=>zn,AB3:()=>Zv,IXm:()=>tx,dhe:()=>Ff,PjD:()=>Kf,RDD:()=>Xm,lmF:()=>Ym,$ZN:()=>hc,NtP:()=>gc,iiN:()=>Rz,Qdp:()=>vz,S8y:()=>Uz,QjN:()=>Az,yL5:()=>Oc,se9:()=>Dc,B$8:()=>aL,JgL:()=>uL,xHb:()=>xG,fxk:()=>kG,Ldy:()=>bq,BDC:()=>Rq,ak0:()=>wx,YrR:()=>yx,sy:()=>Gh,uV:()=>Lh,yWy:()=>Qc,as5:()=>Vc,v_8:()=>jR,VgQ:()=>HR,bpP:()=>ci,xBJ:()=>Oi,jFq:()=>Di,NW8:()=>Pi,tP0:()=>bi,$VK:()=>qu,tfN:()=>Bu,xO$:()=>OR,b07:()=>DR,zYy:()=>LR,dwD:()=>FR,yjV:()=>VR,c4k:()=>XR,CLT:()=>yq,q5s:()=>Sq,rhB:()=>nj,p5Q:()=>sj,bkm:()=>kR,Vau:()=>ER,gNG:()=>Rj,QNN:()=>vj,WKP:()=>Ml,mys:()=>Ol,GLj:()=>ij,deZ:()=>oj,dn0:()=>Wk,P7l:()=>Qk,LMY:()=>Kc,LLB:()=>zc,JQv:()=>kw,LQe:()=>Ew,rJW:()=>UG,G_8:()=>AG,RZJ:()=>$G,sst:()=>MG,Kfp:()=>QG,kMn:()=>RG,YOY:()=>vG,npU:()=>Nv,PGd:()=>Gv,HOq:()=>$R,xEn:()=>MR,$ty:()=>Bl,VN6:()=>Il,HeY:()=>iS,V_5:()=>oS,kau:()=>LG,YMP:()=>FG,O8H:()=>tv,wDw:()=>rv,WUm:()=>nv,IHq:()=>By,qks:()=>Iy,DEp:()=>qh,zBo:()=>Bh,ZU_:()=>Yg,X8H:()=>Zg,tol:()=>Ls,b0C:()=>Fs,H16:()=>CR,Tw9:()=>TR,lEN:()=>UR,Z1Y:()=>AR,hk4:()=>Ov,ZpC:()=>Dv,h3x:()=>xl,D9s:()=>kl,eWf:()=>JR,Wig:()=>wR,w9j:()=>Vn,c1o:()=>Xn,MS0:()=>Dn,k09:()=>Nn,tE3:()=>GA,lL7:()=>LA,kHo:()=>T$,QhI:()=>U$,jOB:()=>qR,dGI:()=>BR,yY2:()=>Lp,Ja4:()=>Np,ogM:()=>Gp,vxR:()=>$p,bOn:()=>Mp,S2v:()=>Tp,w9I:()=>Up,MGn:()=>Op,ISK:()=>Dp,NS4:()=>$I,xx6:()=>MI,piC:()=>Ti,T_o:()=>Ui,tVV:()=>cF,zHj:()=>lF,sGA:()=>mD,MmU:()=>fD,PZt:()=>Wd,tJL:()=>Qd,ptw:()=>Rx,zlM:()=>vx,h5c:()=>kC,b9h:()=>EC,vCC:()=>QD,D7h:()=>VD,zuj:()=>CC,NMG:()=>TC,qKw:()=>Fz,SmK:()=>Ku,kjp:()=>zu,L7H:()=>Tq,jGg:()=>Uq,ZrD:()=>as,ffl:()=>us,Xvt:()=>ot,cxP:()=>tu,acM:()=>it,bZb:()=>sv,ybE:()=>rT,YiF:()=>eT,bQB:()=>Hv,Z6E:()=>Wv,hDl:()=>Ax,hWK:()=>$x,UHP:()=>ab,UBK:()=>ub,m:()=>RN,E3F:()=>vN,w66:()=>aN,Mmr:()=>uN,ceB:()=>ZL,WXO:()=>tF,nun:()=>YG,bzo:()=>ZG,h0F:()=>Rk,dTt:()=>vk,GTA:()=>Tx,ev7:()=>Ux,VJo:()=>wD,ZuH:()=>yD,CNn:()=>NI,QOJ:()=>FI,zYv:()=>fc,FmW:()=>dc,KEO:()=>mF,qA0:()=>pF,fKS:()=>rs,tkR:()=>ss,dj5:()=>jT,PFI:()=>HT,hSh:()=>ZP,P8G:()=>tb,BIT:()=>gA,Xmf:()=>_A,UBx:()=>PA,ead:()=>bA,NQP:()=>LT,LK4:()=>FT,rtb:()=>cA,v0c:()=>lA,QWx:()=>qP,Qsl:()=>BP,YG:()=>R$,uNt:()=>v$,PvX:()=>fJ,JPA:()=>dJ,kFu:()=>pE,Mpk:()=>hE,rjZ:()=>_s,FFm:()=>Js,DWR:()=>QP,pGw:()=>VP,zuZ:()=>$P,Dfi:()=>MP,DrI:()=>bP,BRX:()=>RP,J9i:()=>CI,T1W:()=>TI,hxG:()=>UI,Lre:()=>AI,NZ_:()=>kI,l8$:()=>EI,XKz:()=>of,H7s:()=>af,uuc:()=>Df,eo$:()=>Nf,wOq:()=>id,M2G:()=>od,GKl:()=>kf,GIW:()=>Ef,rCL:()=>bf,nbk:()=>Rf,laE:()=>Qm,TCm:()=>Vm,X0z:()=>nz,zxO:()=>sz,kZD:()=>OK,U$g:()=>DK,F5S:()=>XF,PTw:()=>YF,gSd:()=>hK,Egt:()=>gK,$yS:()=>cf,XrM:()=>mf,Eh9:()=>kE,wrT:()=>EE,zFs:()=>KL,bQQ:()=>zL,Fuf:()=>ML,HCj:()=>OL,tJW:()=>Yx,RYJ:()=>Zx,$H8:()=>Vx,XMd:()=>Xx,UJO:()=>mG,Cel:()=>fG,yoo:()=>Mh,fzp:()=>Oh,fS9:()=>Iv,EvY:()=>Pv,b3B:()=>wv,vym:()=>yv,DtR:()=>Ko,dDc:()=>zo,Cwp:()=>Uo,_i8:()=>Ao,rj1:()=>Bo,jWT:()=>Io,$bH:()=>No,nCl:()=>Go,Bhj:()=>vo,LBR:()=>xo,Yir:()=>Wo,GDG:()=>Qo,DqU:()=>Ki,X99:()=>zi,BDH:()=>fi,XwO:()=>ui,vvr:()=>cu,J3N:()=>lu,Tjf:()=>Wz,eWF:()=>Qz,AL:()=>av,EDv:()=>uv,SC0:()=>Ni,kz1:()=>Gi,aam:()=>hv,AF:()=>gv,pmc:()=>mv,PW:()=>fv,Dmk:()=>ji,RAD:()=>Hi,$ht:()=>wg,BrS:()=>yg,Spq:()=>nC,YCH:()=>sC,pNh:()=>KI,vTx:()=>jI,RZf:()=>jd,d6k:()=>Hd,Fo6:()=>oh,rA8:()=>ah,NPW:()=>G$,JAL:()=>L$,xcI:()=>Fk,hbx:()=>Kk,HFD:()=>Ll,Fr4:()=>Fl,F5_:()=>Uk,Lt9:()=>Ak,sCz:()=>cy,aP5:()=>ly,da6:()=>RM,zwl:()=>vM,QRZ:()=>jM,Iz5:()=>HM,sNl:()=>DC,Mlf:()=>NC,XQ_:()=>FU,DZr:()=>KU,UvX:()=>cT,G8P:()=>lT,LJ3:()=>XC,Hen:()=>YC,CoZ:()=>ax,YZV:()=>ux,bLK:()=>dw,YbK:()=>pw,gPk:()=>wy,wZY:()=>yy,yog:()=>fg,K_o:()=>dg,dXc:()=>Ya,zF8:()=>Za,KTu:()=>La,_$O:()=>Fa,jG:()=>Oa,jFj:()=>Da,pbs:()=>Wa,PD$:()=>Qa,NS0:()=>ka,JL8:()=>Ea,dpZ:()=>PU,Lxb:()=>bU,Gor:()=>bu,WWO:()=>Ru,TeW:()=>UU,$lk:()=>AU,Hdl:()=>ix,hHL:()=>ox,qJd:()=>BT,IIB:()=>IT,vq0:()=>iu,npe:()=>ou,cCB:()=>Yb,mFP:()=>Zb,Lr1:()=>my,Bpu:()=>fy,i_X:()=>Ow,wBS:()=>Dw,moj:()=>Nw,k3$:()=>Gw,Vpq:()=>PG,vfz:()=>bG,WFw:()=>TD,gqu:()=>UD,tdz:()=>dy,N4Y:()=>py,l5I:()=>rx,FsH:()=>ex,AKO:()=>Dy,C7S:()=>Ny,YgU:()=>cx,G3W:()=>lx,izj:()=>hy,Qul:()=>gy,hLv:()=>wN,VCH:()=>yN,iRP:()=>PN,y13:()=>bN,es2:()=>vC,CKk:()=>xC,Ozh:()=>rj,wcT:()=>ej,xvP:()=>qM,nhk:()=>BM,omy:()=>uM,wgB:()=>cM,VIg:()=>LM,lxh:()=>FM,ORt:()=>vv,yL9:()=>xv,gez:()=>sJ,MYI:()=>iJ,qEG:()=>_U,CMB:()=>JU,zul:()=>mx,L5U:()=>fx,Ca8:()=>Dd,m6C:()=>Nd,iXm:()=>JM,k8Q:()=>wM,TIw:()=>H$,rRJ:()=>W$,Xtc:()=>sM,bIg:()=>iM,WL_:()=>_y,SPf:()=>Jy,Ebf:()=>yh,Huz:()=>Sh,D3G:()=>rO,rew:()=>eO,Vry:()=>jJ,nNe:()=>HJ,bjc:()=>tR,lLB:()=>rR,__V:()=>iN,c3q:()=>oN,hLX:()=>sR,lYk:()=>iR,LjR:()=>zO,Hoz:()=>jO,G6u:()=>eJ,_E_:()=>nJ,ZVF:()=>pM,zri:()=>hM,dR6:()=>gd,P1K:()=>_d,bBp:()=>jg,rk2:()=>Hg,fRF:()=>Vf,TkS:()=>Xf,P1X:()=>zh,VxX:()=>jh,Jt2:()=>Li,Fmo:()=>Fi,DLo:()=>nx,zQx:()=>sx,J3_:()=>eR,jzZ:()=>nR,Z8m:()=>nB,VbN:()=>sB,Ll_:()=>MS,rKG:()=>OS,rG0:()=>DS,lWs:()=>NS,sRz:()=>yR,mEf:()=>SR,_P7:()=>wF});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"),i=e("../proto/dist/generated/aiserver/v1/usage_pb.js"),o=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="aiserver.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}class l extends c{constructor(t){super(),this.sessionId="",this.type=m.UNSPECIFIED,this.createdAt="",this.expiresAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["Session|1 session_id 9|2 type #0|3 created_at 9|4 expires_at 9",m]}}var m=(0,a.QT)(n.proto3,u,"Session.SessionType",[[0,"UNSPECIFIED"],[1,"WEB"],[2,"CLIENT"],[3,"BUGBOT"],[4,"BACKGROUND_AGENT"],[5,"SUPPORT_IMPERSONATION"],[6,"API_KEY_TOKEN"],[7,"TRAINING"],[8,"EXEC_DAEMON"],[9,"GRAPHITE"],[10,"MOBILE"],[11,"SAND_MOBILE"]],1);n.proto3,n.proto3,n.proto3;class f extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class d extends f{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["RemoteControlV2AdminSettings|1 enabled 8?|2 automatic_registration_enabled 8?"]}}class p extends f{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["RemoteControlV2Policy|1 enabled 8?|2 automatic_registration_enabled 8?|3 available 8?|4 automatic_registration_released 8?|5 remote_control_denying_org_name 9?|6 automatic_registration_denying_org_name 9?"]}}var h=e("../proto/dist/generated/agent/v1/requested_model_pb.js");a.HL;var g=(0,a.QT)(n.proto3,"aiserver.v1.","FullSelfDrivingMode",[[0,"UNSPECIFIED"],[1,"SUGGEST"],[2,"APPLY"]],1);n.proto3,n.proto3;var _=e("../proto/dist/generated/aiserver/v1/chat_pb.js");class J extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class w extends J{constructor(t){super(),this.name="",this.sha256="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["CanvasVisualizationRuntimePin|1 name 9|2 sha256 9"]}}const y="aiserver.v1.";class S extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return y}}var q=(0,a.QT)(n.proto3,y,"AppSecretState",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"SET"]],1),B=(n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,(0,a.QT)(n.proto3,y,"PublishReviewOverrideState",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"APPROVED"],[3,"DENIED"],[4,"REVOKED"],[5,"EXPIRED"]],1)),I=(n.proto3,(0,a.QT)(n.proto3,y,"AppPublishStatus",[[0,"UNSPECIFIED"],[1,"QUEUED"],[2,"BUILDING"],[3,"READY"],[4,"ERROR"],[5,"CANCELED"]],1)),P=(n.proto3,(0,a.QT)(n.proto3,y,"AppVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1));n.proto3,n.proto3,n.proto3,n.proto3,n.proto3;class b extends S{constructor(t){super(),this.type="",this.version="",this.sha256="",this.markdown="",this.coversTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PublishTerms|1 type 9|2 version 9|3 sha256 9|4 markdown 9|5 covers_team 8"]}}class R extends S{constructor(t){super(),this.type="",this.version="",this.sha256="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["AcceptedPublishTerms|1 type 9|2 version 9|3 sha256 9"]}}class v extends S{constructor(t){super(),this.id="",this.source="",this.category="",this.severity="",this.blocking=!1,this.description="",this.path="",this.line=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["PublishReviewFinding|1 id 9|2 source 9|3 category 9|4 severity 9|5 blocking 8|6 description 9|7 path 9|8 line 5"]}}class x extends S{constructor(t){super(),this.reason="",this.disabledAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["AppDisabledByCursor|1 reason 9|2 disabled_at_ms 3"]}}n.proto3,n.proto3;class k extends S{constructor(t){super(),this.width=0,this.url="",this.contentType="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["CanvasAssetPreview|1 width 5|2 url 9|3 content_type 9|4 size_bytes 3"]}}var E=e("../proto/dist/generated/agent/v1/agent_pb.js");const C="aiserver.v1.";class T extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return C}}var U=(0,a.QT)(n.proto3,C,"ScmConnectIntentSource",[[0,"UNSPECIFIED"],[1,"PORTAL"],[2,"GLASS_CLOUD_AGENT"],[3,"GLASS_DIFF"],[4,"GLASS_AUTOMATIONS"]],1),A=(0,a.QT)(n.proto3,C,"GitlabReposSyncStatus",[[0,"UNSPECIFIED"],[1,"NOT_FOUND"],[2,"RUNNING"],[3,"COMPLETED"],[4,"FAILED"]],1),$=(0,a.QT)(n.proto3,C,"AccountSectionStatus",[[0,"UNSPECIFIED"],[1,"OK"],[2,"NOT_LINKED"],[3,"UNAVAILABLE"]],1),M=(0,a.QT)(n.proto3,C,"AccountHandoffTarget",[[0,"UNSPECIFIED"],[1,"EMAIL"],[2,"PASSWORD"],[3,"TWO_STEP"],[4,"SIGN_IN_METHODS"]],1),O=(0,a.QT)(n.proto3,C,"UserOrganizationRole",[[0,"UNSPECIFIED"],[1,"ADMIN"],[2,"MEMBER"],[4,"BILLING_ADMIN"]],1),D=(0,a.QT)(n.proto3,C,"OrganizationTeamSettingsCopyCategory",[[0,"UNSPECIFIED"],[1,"MODELS"],[2,"SECURITY"],[3,"RULES_AND_COMMANDS"],[4,"HOOKS"],[5,"MCP_AND_PLUGIN_POLICY"],[6,"SPENDING_LIMITS"],[7,"TEAM_ACCESS_DEFAULTS"],[8,"GROK_BOT"]],1),N=(0,a.QT)(n.proto3,C,"OrganizationTeamSettingsCopyOutcome",[[0,"UNSPECIFIED"],[1,"COPIED"],[2,"EMPTY"],[3,"SKIPPED_BY_POLICY"],[4,"BLOCKED"]],1),G=(0,a.QT)(n.proto3,C,"CreateOrganizationTeamIdentityProviderMode",[[0,"UNSPECIFIED"],[1,"USE_ORGANIZATION"],[2,"CREATE_NEW"]],1),L=(0,a.QT)(n.proto3,C,"XaiTeamMembershipHoldSource",[[0,"UNSPECIFIED"],[1,"MIGRATION"],[2,"OPERATOR_MERGE"],[3,"SCIM"],[4,"SSO"],[5,"AUTO_ENROLL"]],1),F=(0,a.QT)(n.proto3,C,"OrganizationScimSource",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),K=(0,a.QT)(n.proto3,C,"OrganizationScimSourceResolution",[[0,"UNSPECIFIED"],[1,"EXPLICIT"],[2,"DEFAULT"]],1),z=(0,a.QT)(n.proto3,C,"AnthropicCyberVerificationStatus",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"PENDING"],[3,"REJECTED"]],1),j=(0,a.QT)(n.proto3,C,"AnthropicEfsStatus",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"APPROVED"],[3,"REJECTED"]],1),H=(0,a.QT)(n.proto3,C,"GroupVisibility",[[0,"UNSPECIFIED"],[1,"TEAM_ADMIN"],[2,"TEAM"]],1),W=(0,a.QT)(n.proto3,C,"AnthropicEfsReviewDecision",[[0,"UNSPECIFIED"],[1,"APPROVE"],[2,"REJECT"],[3,"REVOKE"]],1),Q=(0,a.QT)(n.proto3,C,"XaiDataRetention",[[0,"UNSPECIFIED"],[1,"ZDR"],[2,"ZDR_EXCEPT_SOC_AUDIT"],[3,"GENERAL"]],1),V=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretLevel",[[0,"UNSPECIFIED"],[1,"ENVIRONMENT_VARIABLE"],[2,"INJECTED_SECRET"],[3,"BUILD_SECRET"],[4,"HTTP_SECRET"]],1),X=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretHttpScheme",[[0,"UNSPECIFIED"],[1,"BEARER"],[2,"TOKEN"],[3,"BASIC"],[4,"HEADER"]],1),Y=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretSurface",[[0,"UNSPECIFIED"],[1,"CLOUD_AGENT"],[2,"GROK_BOT"],[3,"APP"]],1),Z=(0,a.QT)(n.proto3,C,"McpServerAppliesTo",[[0,"UNSPECIFIED"],[1,"LOCAL_AND_CLOUD"],[2,"LOCAL"],[3,"CLOUD"],[4,"NONE"]],1),tt=(0,a.QT)(n.proto3,C,"McpServedBy",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),rt=(0,a.QT)(n.proto3,C,"McpSignOutReason",[[0,"UNSPECIFIED"],[1,"EXPIRED"],[2,"REVOKED"],[3,"ORGANIZATION_POLICY"],[4,"MFA_REQUIRED"],[5,"ADMIN_BLOCKED"],[6,"ACCOUNT_DISABLED"],[7,"CLIENT_INVALID"],[8,"ACCOUNT_RESTRICTED"],[9,"PROVIDER_UNAVAILABLE"],[10,"PROVIDER_ERROR"]],1),et=(0,a.QT)(n.proto3,C,"CycleType",[[0,"UNSPECIFIED"],[1,"MONTH"],[2,"START_TIME"]],1),nt=(0,a.QT)(n.proto3,C,"SpendLimitPolicyScope",[[0,"UNSPECIFIED"],[1,"TEAM_TOTAL"],[2,"TEAM_MEMBER_DEFAULT"],[3,"GROUP_MEMBER_DEFAULT"]],1),st=(0,a.QT)(n.proto3,C,"SpendLimitPolicyType",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"HARD"],[3,"SOFT"]],1),it=(0,a.QT)(n.proto3,C,"TeamRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"MEMBER"],[3,"FREE_OWNER"],[4,"REMOVED"]],1),ot=(0,a.QT)(n.proto3,C,"TeamMemberBillingTier",[[0,"UNSPECIFIED"],[1,"TIER_1000"],[2,"TIER_2000"]],1),at=(0,a.QT)(n.proto3,C,"MergedTeamSeatTier",[[0,"UNSPECIFIED"],[1,"FREE"],[2,"PLUS"],[3,"SUPER"],[4,"ULTRA"],[5,"PREMIUM"]],1),ut=(0,a.QT)(n.proto3,C,"TeamBillingSource",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"STRIPE"],[3,"XAI"],[4,"CONTRACT"]],1),ct=(0,a.QT)(n.proto3,C,"PrivateInferenceEnablement",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"]],1),lt=(0,a.QT)(n.proto3,C,"PrepaidBillingMode",[[0,"UNSPECIFIED"],[1,"ON_DEMAND"],[2,"PREPAID"]],1),mt=(0,a.QT)(n.proto3,C,"XaiCommerceBearerPurpose",[[0,"UNSPECIFIED"],[1,"BROWSER_COMMERCE"],[2,"PREPAID_TOP_UP"]],1),ft=(0,a.QT)(n.proto3,C,"XaiCommerceBearerTokenSource",[[0,"UNSPECIFIED"],[1,"PARTNER_JWT"],[2,"DEV_OVERRIDE"]],1),dt=(0,a.QT)(n.proto3,C,"XaiCommerceBearerRefusalReason",[[0,"UNSPECIFIED"],[1,"UNAVAILABLE"],[2,"INTERACTIVE_ONLY"],[3,"NOT_CONFIGURED"],[4,"NOT_LINKED"],[5,"RATE_LIMITED"]],1),pt=(0,a.QT)(n.proto3,C,"SlackConnectSource",[[0,"UNSPECIFIED"],[1,"LEGACY_UNKNOWN"],[2,"GLASS_CHECKLIST"],[3,"GLASS_SETTINGS"],[4,"GLASS_AUTOMATIONS"],[5,"IDE_SETTINGS"],[6,"IDE_IN_APP_AD"],[7,"DASHBOARD_INTEGRATIONS"],[8,"DASHBOARD_OVERVIEW"],[9,"DASHBOARD_SETUP_PROGRESS"],[10,"DASHBOARD_CHECKLIST"],[11,"DASHBOARD_AUTOMATIONS"],[12,"DASHBOARD_SLACK_SETTINGS"],[13,"DASHBOARD_SAND_SETUP"],[14,"CLOUD_ENVIRONMENT_ONBOARDING"],[15,"MANAGED_AGENTS"],[16,"REVIEW_SETTINGS"],[17,"SAND_LISTENER"],[18,"EMAIL"],[19,"PUBLIC_INSTALL"],[20,"PUBLIC_INSTALL_USER_SCOPES"],[21,"SLACK_AUTH_PROMPT"],[22,"SLACK_LINK_UNFURL"],[23,"GLASS_UNATTRIBUTED"],[24,"IDE_UNATTRIBUTED"],[25,"WEB_UNATTRIBUTED"],[26,"GROK_BOT_UNATTRIBUTED"]],1),ht=(0,a.QT)(n.proto3,C,"SlackConnectSite",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),gt=(0,a.QT)(n.proto3,C,"TeamEnterpriseGrantState",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"NONE"],[3,"UNAVAILABLE"]],1),_t=(0,a.QT)(n.proto3,C,"ContactImportProvider",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"GOOGLE"]],1),Jt=(0,a.QT)(n.proto3,C,"ContactImportSyncRunStatus",[[0,"UNSPECIFIED"],[1,"IN_PROGRESS"],[2,"ACTIVE"],[3,"SUPERSEDED"],[4,"FAILED"]],1),wt=(0,a.QT)(n.proto3,C,"GrokAdminOutcome",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"TEAM_NOT_MERGED"],[3,"ACCOUNT_NOT_LINKED"],[4,"NOT_ADMIN"],[5,"BLOCKED_BY_SECURITY"],[6,"NOT_AVAILABLE"],[7,"UNAVAILABLE"]],1),yt=(0,a.QT)(n.proto3,C,"GrokAdminFeatureControlField",[[0,"UNSPECIFIED"],[1,"ENABLE_FILE_UPLOADS"],[2,"ENABLE_IMAGE_UPLOADS"],[3,"ENABLE_WEB_SEARCH"],[4,"ENABLE_X_SEARCH"],[5,"ENABLE_VOICE_MODE"],[6,"ENABLE_IMAGINE"],[7,"ENABLE_IMAGINE_CHAT"],[8,"ENABLE_GROK_CHAT"],[9,"ENABLE_DICTATION"],[10,"ENABLE_BOTS"]],1),St=(0,a.QT)(n.proto3,C,"GrokUserDataControlsStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[3,"NOT_LINKED"],[4,"REFUSED"],[5,"NO_ACCESS"],[6,"CURSOR_ONLY_ENTERPRISE"]],1),qt=(0,a.QT)(n.proto3,C,"GrokRequestLogKind",[[0,"UNSPECIFIED"],[1,"CHAT"],[2,"IMAGE"],[3,"VIDEO"]],1),Bt=(0,a.QT)(n.proto3,C,"GrokAdminConversationSharingScope",[[0,"UNSPECIFIED"],[1,"PUBLIC"],[2,"ORGANIZATION"],[3,"TEAM"],[4,"PRIVATE"]],1),It=(0,a.QT)(n.proto3,C,"GrokAdminProjectSharingScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"],[3,"PRIVATE"]],1),Pt=(0,a.QT)(n.proto3,C,"GrokAdminSkillSharingScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"],[3,"PRIVATE"]],1),bt=(0,a.QT)(n.proto3,C,"GrokAdminOrganizationRetentionUpdate",[[0,"UNSPECIFIED"],[1,"SET_DAYS"],[2,"KEEP_FOREVER"],[3,"CLEAR"]],1),Rt=(0,a.QT)(n.proto3,C,"StepUpLinkRefusal",[[0,"UNSPECIFIED"],[1,"WRONG_BROWSER"],[2,"EXPIRED"],[3,"USED"],[4,"REPLACED"]],1),vt=(0,a.QT)(n.proto3,C,"ApiKeyInventoryKind",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM"],[3,"ORGANIZATION"],[4,"FINE_GRAINED"]],1),xt=(0,a.QT)(n.proto3,C,"StaffActionReason",[[0,"UNSPECIFIED"],[1,"SECURITY_INCIDENT"],[2,"LEAKED_KEY"],[3,"CUSTOMER_REQUEST"],[4,"ABUSE"],[5,"OTHER"]],1),kt=(0,a.QT)(n.proto3,C,"ServiceTokenOwnerType",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM"],[3,"ORGANIZATION"]],1),Et=(0,a.QT)(n.proto3,C,"CursorApiKeyOwner",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"PERSONAL"]],1),Ct=(0,a.QT)(n.proto3,C,"TrustedIssuerStatus",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"],[3,"REVOKED"]],1),Tt=(0,a.QT)(n.proto3,C,"OAuthGrantResourceType",[[0,"UNSPECIFIED"],[1,"PERSONAL_ACCOUNT"],[2,"TEAM"],[3,"ORGANIZATION"]],1),Ut=(0,a.QT)(n.proto3,C,"OAuthGrokBotSource",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"SHARED"],[3,"TEAM"]],1),At=(0,a.QT)(n.proto3,C,"ProtectedGitProvider",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GITLAB"],[3,"GITHUB_ENTERPRISE"],[4,"GITLAB_SELF_HOSTED"],[5,"ORIGIN"],[6,"BITBUCKET"]],1),$t=(0,a.QT)(n.proto3,C,"UnlistedMemberServerKind",[[0,"UNSPECIFIED"],[1,"MARKETPLACE_PLUGIN"],[2,"REMOTE_MCP"],[3,"LOCAL_COMMAND_MCP"]],1),Mt=(0,a.QT)(n.proto3,C,"FirstPartyPluginMode",[[0,"UNSPECIFIED"],[1,"ENABLE_ALL"],[2,"ALLOWLIST"]],1),Ot=(0,a.QT)(n.proto3,C,"AutoCreatePrMode",[[0,"UNSPECIFIED"],[1,"ALWAYS"],[2,"SINGLE"],[3,"NEVER"]],1),Dt=(0,a.QT)(n.proto3,C,"PrReviewOpenDestinationMode",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GRAPHITE"],[3,"REVIEW_CURSOR"]],1),Nt=(0,a.QT)(n.proto3,C,"GithubArtifactPostingMode",[[0,"UNSPECIFIED"],[1,"POST_ARTIFACT"],[2,"LINK_ONLY"]],1),Gt=(0,a.QT)(n.proto3,C,"PublicArtifactSharingMode",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DISABLED"]],1),Lt=(0,a.QT)(n.proto3,C,"CloudAgentEgressProtectionMode",[[0,"UNSPECIFIED"],[1,"ALLOW_ALL"],[2,"DEFAULT_WITH_NETWORK_SETTINGS"],[3,"NETWORK_SETTINGS_ONLY"],[4,"PARENT_PLUS_NETWORK_SETTINGS"]],1),Ft=(0,a.QT)(n.proto3,C,"TeamFollowupEnabledMode",[[0,"UNSPECIFIED"],[1,"DISABLED"],[2,"SERVICE_ACCOUNTS_ONLY"],[3,"ALL"]],1),Kt=(0,a.QT)(n.proto3,C,"SlackReplyMode",[[0,"UNSPECIFIED"],[1,"FOLLOW_THREADS"],[2,"MENTIONS_ONLY"]],1),zt=(0,a.QT)(n.proto3,C,"PreferredRepoSourceMode",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"ORIGIN"]],1),jt=(0,a.QT)(n.proto3,C,"AutomationDefaultVisibility",[[0,"UNSPECIFIED"],[1,"VISIBLE"],[2,"EDITABLE"],[3,"PRIVATE"]],1),Ht=(0,a.QT)(n.proto3,C,"PersonalSecretsPolicy",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DISABLED"]],1),Wt=(0,a.QT)(n.proto3,C,"SandboxingMode",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"],[3,"ENFORCED"]],1),Qt=(0,a.QT)(n.proto3,C,"NetworkingMode",[[0,"UNSPECIFIED"],[1,"USER_CONTROLLED"],[2,"ALWAYS_DISABLED"]],1),Vt=(0,a.QT)(n.proto3,C,"GitMode",[[0,"UNSPECIFIED"],[1,"USER_CONTROLLED"],[2,"ALWAYS_DISABLED"]],1),Xt=(0,a.QT)(n.proto3,C,"SandboxReadBoundaryMode",[[0,"UNSPECIFIED"],[1,"SYSTEM"],[2,"WORKSPACE"],[4,"NONE"]],1),Yt=(0,a.QT)(n.proto3,C,"SlackInboundInstallMode",[[0,"UNSPECIFIED"],[1,"OPEN"],[2,"LOCKED"]],1),Zt=(0,a.QT)(n.proto3,C,"GoogleDriveSharedDrivesMode",[[0,"UNSPECIFIED"],[1,"BLOCK"],[2,"ALLOW_ONLY"]],1),tr=(0,a.QT)(n.proto3,C,"LocalToolPermissionCeiling",[[0,"UNSPECIFIED"],[1,"NEVER"],[2,"ASK"],[3,"ALWAYS"]],1),rr=(0,a.QT)(n.proto3,C,"LocalToolOtherCommandsPolicy",[[0,"UNSPECIFIED"],[1,"ASK"],[2,"BLOCK"]],1),er=(0,a.QT)(n.proto3,C,"SandEgressMode",[[0,"UNSPECIFIED"],[1,"ALLOW_ALL"],[2,"DEFAULT_WITH_NETWORK_SETTINGS"],[3,"NETWORK_SETTINGS_ONLY"]],1),nr=(0,a.QT)(n.proto3,C,"SandLocalEgressMode",[[0,"UNSPECIFIED"],[1,"ALWAYS_ON"],[2,"MEMBER_DECIDES"],[3,"ALWAYS_OFF"]],1),sr=(0,a.QT)(n.proto3,C,"GrokBotTeamBotSharing",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"ADMINS_ONLY"],[3,"DISABLED"],[4,"DESIGNATED"]],1),ir=(0,a.QT)(n.proto3,C,"PagesTeamSharingLevel",[[0,"UNSPECIFIED"],[1,"EVERYONE"],[2,"SPECIFIC_TEAMMATES"],[3,"OFF"]],1),or=(0,a.QT)(n.proto3,C,"LlmGatewayAuthMode",[[0,"UNSPECIFIED"],[1,"JWT_ACCESS"],[2,"CUSTOMER_MANAGED"]],1),ar=(0,a.QT)(n.proto3,C,"LlmGatewayRoutingMode",[[0,"UNSPECIFIED"],[1,"LEGACY"],[2,"MODEL_LIST"],[3,"CUSTOM"]],1),ur=(0,a.QT)(n.proto3,C,"LlmGatewayCredentialSourceStrategy",[[0,"UNSPECIFIED"],[1,"TEAM_CREDENTIAL_ALL_SURFACES"],[2,"CLIENT_LOCAL_TEAM_CLOUD"]],1),cr=(0,a.QT)(n.proto3,C,"LlmGatewayDiscoveryScope",[[0,"UNSPECIFIED"],[1,"ALL_MODELS"],[2,"CATALOG_PLUS_UNPUBLISHED"]],1),lr=(0,a.QT)(n.proto3,C,"SandGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),mr=(0,a.QT)(n.proto3,C,"CloudAgentGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),fr=(0,a.QT)(n.proto3,C,"CursorGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),dr=(0,a.QT)(n.proto3,C,"TrialType",[[0,"UNSPECIFIED"],[1,"REQUEST"],[2,"TOKEN"]],1),pr=(0,a.QT)(n.proto3,C,"FreeTrialCodePurpose",[[0,"UNSPECIFIED"],[1,"FREE_TRIAL"],[2,"ORG_INVITE"]],1),hr=(0,a.QT)(n.proto3,C,"CreditGrantOwnership",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"ORGANIZATION"]],1),gr=(0,a.QT)(n.proto3,C,"BankedUsageResetKind",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1),_r=(0,a.QT)(n.proto3,C,"UserAccessRequestKind",[[0,"UNSPECIFIED"],[1,"SAND_TEAM_ACCESS"],[2,"TEAM_JOIN"]],1),Jr=(0,a.QT)(n.proto3,C,"IapVerificationProvenance",[[0,"UNSPECIFIED"],[1,"PURCHASE_RETURN"],[2,"PURCHASE_LISTENER"],[3,"COLD_START"],[4,"FOREGROUND"],[5,"MANUAL_RESTORE"],[6,"AUTH_CHANGE"]],1),wr=(0,a.QT)(n.proto3,C,"RestoreCommerceStorePurchaseOutcome",[[0,"UNSPECIFIED"],[1,"BOUND"],[2,"REFUSED"],[3,"UNAVAILABLE"]],1),yr=(0,a.QT)(n.proto3,C,"GooglePlayInventoryClientState",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"SUSPENDED"],[3,"PENDING"]],1),Sr=(0,a.QT)(n.proto3,C,"GooglePlayInventoryTrigger",[[0,"UNSPECIFIED"],[1,"COLD_START"],[2,"FOREGROUND"],[3,"MANUAL_RESTORE"]],1),qr=(0,a.QT)(n.proto3,C,"TestPushScenario",[[0,"UNSPECIFIED"],[1,"FINISHED_SUCCESS"],[2,"FINISHED_ERROR"],[3,"CUSTOM"],[4,"SAND_AGENT_FINISHED"]],1),Br=(0,a.QT)(n.proto3,C,"TestPushPlatform",[[0,"UNSPECIFIED"],[1,"IOS"],[2,"ANDROID"]],1),Ir=(0,a.QT)(n.proto3,C,"TestPushApp",[[0,"UNSPECIFIED"],[1,"GROK_BUILD_IOS"],[2,"GROK_BUILD_ANDROID"],[3,"GROK_BOT_IOS"],[4,"GROK_BOT_ANDROID"]],1),Pr=(0,a.QT)(n.proto3,C,"LimitHitStage",[[0,"UNSPECIFIED"],[1,"AUTO_SWITCH"],[2,"SLOW_POOL"],[3,"HARD_BLOCK"],[4,"WEEKLY_LIMIT"]],1),br=(0,a.QT)(n.proto3,C,"ProjectsCreditSurface",[[0,"UNSPECIFIED"],[1,"COMPOSER_BANNER"],[2,"SIDEBAR_TAG"]],1),Rr=(0,a.QT)(n.proto3,C,"SeatUpgradePoolDriver",[[0,"UNSPECIFIED"],[1,"FIRST_PARTY"],[2,"THIRD_PARTY"],[3,"BOTH"]],1),vr=(0,a.QT)(n.proto3,C,"XaiTeamPlanChangeOutcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"PLAN_CANCELLING"],[3,"MANAGE_ON_GROK"],[4,"TRY_AGAIN"],[5,"REQUIRES_ACTION"],[6,"PAYMENT_FAILED"],[7,"CHARGE_IN_FLIGHT"],[8,"CHECK_GONE"],[9,"ADD_PAYMENT_METHOD"],[10,"GROK_SECURITY_BLOCKED"],[11,"GROK_SIGN_IN_REQUIRED"],[12,"GROK_OTHER_ACCOUNT"]],1),xr=(0,a.QT)(n.proto3,C,"DeploymentIntegration",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"LINEAR"],[3,"ATLASSIAN"],[4,"MICROSOFT_TEAMS"],[5,"SHAREPOINT"],[6,"GROK_CONNECTORS"],[7,"SENTRY"],[8,"PAGERDUTY"],[9,"APP_STORE_CONNECT"],[10,"MERGE"],[11,"GITHUB"],[12,"GITLAB"],[13,"AZURE_DEVOPS"],[14,"BITBUCKET_CLOUD"],[15,"ORIGIN"],[16,"BITBUCKET_DATA_CENTER"],[17,"TAILSCALE"],[18,"PRIVATE_TUNNELS"],[19,"FINANCE"],[20,"XAI_TEAM_MERGE"]],1),kr=(0,a.QT)(n.proto3,C,"ConnectionHealth",[[0,"UNSPECIFIED"],[1,"HEALTHY"],[2,"SETUP_INCOMPLETE"],[3,"DEGRADED"],[4,"NEEDS_REAUTH"],[5,"NEEDS_ADMIN"],[6,"ERROR"],[7,"DISCONNECTED"]],1),Er=(0,a.QT)(n.proto3,C,"ScmReasonCode",[[0,"UNSPECIFIED"],[1,"NEEDS_REAUTH"],[2,"NEEDS_ADMIN"],[3,"REPO_NOT_IN_SELECTION"],[4,"WRONG_TEAM"],[5,"RATE_LIMITED"],[6,"NETWORK_BLOCKED"],[7,"PROVIDER_OUTAGE"],[8,"CAPABILITY_UNSUPPORTED"],[9,"CURSOR_ROLE_REQUIRED"],[10,"READ_ONLY"],[11,"PERSONAL_REPO"],[12,"BLOCKED_BY_POLICY"],[13,"ARCHIVED"],[14,"NO_REPO_ACCESS"],[15,"ACCESS_UNCHECKED"],[16,"MISSING_PERMISSION"]],1),Cr=(0,a.QT)(n.proto3,C,"SecurityAgentType",[[0,"UNSPECIFIED"],[1,"SECURITY_REVIEWER"],[2,"VULNERABILITY_SCANNER"]],1),Tr=(0,a.QT)(n.proto3,C,"AllowlistConfig",[[0,"UNSPECIFIED"],[1,"ALLOWLIST"],[2,"BLOCKLIST"]],1),Ur=(0,a.QT)(n.proto3,C,"BugbotAutofixMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"MANUAL"],[3,"AUTO_PR"],[4,"AUTO_MERGE"]],1),Ar=(0,a.QT)(n.proto3,C,"BugbotBackfillStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"COMPLETED"],[3,"FAILED"]],1),$r=(0,a.QT)(n.proto3,C,"BugbotUsageTier",[[0,"UNSPECIFIED"],[1,"FREE_TIER"],[2,"TRIAL"],[3,"PAID"]],1),Mr=(0,a.QT)(n.proto3,C,"BugbotBillingMode",[[0,"UNSPECIFIED"],[1,"SEAT"],[2,"TOKEN"]],1),Or=(0,a.QT)(n.proto3,C,"BugbotRepoAutoEnablePolicy",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"DEFAULT_ON"]],1),Dr=(0,a.QT)(n.proto3,C,"TeamPendingInvitePurchaseState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"RETRY_NEEDED"],[3,"WAITING_ON_GROK"],[4,"AWAITING_CARD_CHECK"]],1),Nr=(0,a.QT)(n.proto3,C,"LinearActor",[[0,"UNSPECIFIED"],[1,"APP"],[2,"USER"]],1),Gr=(0,a.QT)(n.proto3,C,"MicrosoftTeamsLinkState",[[0,"UNSPECIFIED"],[1,"READY"],[2,"ALREADY_LINKED"],[3,"EXPIRED"],[4,"SUPERSEDED"]],1),Lr=(0,a.QT)(n.proto3,C,"XaiCreditTransferOutcome",[[0,"UNSPECIFIED"],[1,"SUCCEEDED"],[2,"NOT_CONFIGURED"],[3,"FAILED"],[4,"NEEDS_RECONCILIATION"],[5,"PENDING"]],1),Fr=(0,a.QT)(n.proto3,C,"LinearRunOption",[[0,"UNSPECIFIED"],[1,"AUTOMATICALLY"],[2,"BASED_ON_CONDITIONS"],[3,"MANUALLY"]],1),Kr=(0,a.QT)(n.proto3,C,"LabelFilterMode",[[0,"UNSPECIFIED"],[1,"AND"],[2,"OR"]],1),zr=(0,a.QT)(n.proto3,C,"LinearIssuesOrderBy",[[0,"UNSPECIFIED"],[1,"UPDATED_AT"],[2,"CREATED_AT"]],1),jr=(0,a.QT)(n.proto3,C,"LinearIssueSummariesUnavailableReason",[[0,"UNSPECIFIED"],[1,"NOT_CONNECTED"],[2,"WORKSPACE_MISMATCH"],[3,"BUDGET_RESERVED"],[4,"RATE_LIMITED"]],1),Hr=(0,a.QT)(n.proto3,C,"SlackLinkedWorkspaceStatus",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NEEDS_RECONNECT"],[3,"RESTRICTED"]],1),Wr=(0,a.QT)(n.proto3,C,"SlackRoutingRuleTargetType",[[0,"UNSPECIFIED"],[1,"REPOSITORY"],[2,"ENVIRONMENT"]],1),Qr=(0,a.QT)(n.proto3,C,"GroupType",[[0,"UNSPECIFIED"],[1,"BILLING"],[2,"PRODUCT"]],1),Vr=(0,a.QT)(n.proto3,C,"SpendGroupByCategory",[[0,"UNSPECIFIED"],[1,"MODEL"],[2,"USAGE_TYPE"],[3,"ORIGINATING_FLOW"],[4,"GROK_BOT"],[5,"PRODUCT"],[6,"USER"]],1),Xr=(0,a.QT)(n.proto3,C,"DailySpendRankingMetric",[[0,"UNSPECIFIED"],[1,"SPEND"],[2,"TOKENS"]],1),Yr=(0,a.QT)(n.proto3,C,"SpendType",[[0,"UNSPECIFIED"],[1,"ON_DEMAND"],[2,"INCLUDED"],[3,"ALL"]],1),Zr=(0,a.QT)(n.proto3,C,"GroupMemberChangeType",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"REMOVE"]],1),te=(0,a.QT)(n.proto3,C,"ScimDirectoryOwnerType",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"]],1),re=(0,a.QT)(n.proto3,C,"ScimDirectoryProvider",[[0,"UNSPECIFIED"],[1,"WORKOS"]],1),ee=(0,a.QT)(n.proto3,C,"ScimTargetMappingTargetType",[[0,"UNSPECIFIED"],[1,"GROUP"],[2,"TEAM"]],1),ne=(0,a.QT)(n.proto3,C,"ScimTargetMappingSyncState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"SYNCED"],[3,"ERRORED"]],1),se=(0,a.QT)(n.proto3,C,"ScimTargetMappingSourceType",[[0,"UNSPECIFIED"],[1,"SCIM_DIRECTORY_GROUP"],[2,"CURSOR_GROUP"]],1),ie=(0,a.QT)(n.proto3,C,"ScimTargetMappingRole",[[0,"UNSPECIFIED"],[1,"MEMBER"],[2,"ADMIN"],[3,"UNPAID_ADMIN"]],1),oe=(0,a.QT)(n.proto3,C,"AdminNotificationRequestType",[[0,"UNSPECIFIED"],[1,"PRIVACY_MODE"],[2,"BUGBOT"],[3,"BUGBOT_ENABLE_REPOS"],[4,"ORIGIN"],[5,"SECURITY_REVIEWER_ENABLE_REPOS"],[6,"VULNERABILITY_SCANNER_ENABLE_REPOS"]],1),ae=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationKind",[[0,"UNSPECIFIED"],[1,"OTLP_HTTP"]],1),ue=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationTestSignal",[[0,"UNSPECIFIED"],[1,"LOGS"],[2,"METRICS"]],1),ce=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationTestOutcome",[[0,"UNSPECIFIED"],[1,"OK"],[2,"VALIDATION_ERROR"],[3,"HTTP_ERROR"],[4,"REDIRECT"],[5,"TIMED_OUT"],[6,"TLS_ERROR"],[7,"NETWORK_ERROR"]],1),le=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationHealthStatus",[[0,"UNSPECIFIED"],[1,"HEALTHY"],[2,"DEGRADED"],[3,"FAILING"],[4,"IDLE"]],1),me=(0,a.QT)(n.proto3,C,"InferenceHookMode",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"BLOCK"],[3,"SHADOW"]],1),fe=(0,a.QT)(n.proto3,C,"InferenceHookSurface",[[0,"UNSPECIFIED"],[1,"GROK_BOT"],[2,"CLOUD_AGENT"],[3,"EDITOR"],[4,"CLI"],[5,"SDK"]],1),de=(0,a.QT)(n.proto3,C,"InferenceHookKind",[[0,"UNSPECIFIED"],[1,"HTTPS_ENDPOINT"],[2,"MICROSOFT_PURVIEW"],[3,"DECISION_RULES"]],1),pe=(0,a.QT)(n.proto3,C,"InferenceHookDecisionRuleOperator",[[0,"UNSPECIFIED"],[1,"AT_LEAST"],[2,"AT_MOST"]],1),he=(0,a.QT)(n.proto3,C,"InferenceHookDecisionRuleMode",[[0,"UNSPECIFIED"],[1,"BLOCK"],[2,"SHADOW"]],1),ge=(0,a.QT)(n.proto3,C,"InferenceHookSensitivityLabelMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"BLOCK_LISTED"],[3,"BLOCK_AT_OR_ABOVE"]],1),_e=(0,a.QT)(n.proto3,C,"InferenceHookEndpointStatus",[[0,"UNSPECIFIED"],[1,"NOT_CONFIGURED"],[2,"NOT_ENFORCING"],[3,"HEALTHY"],[4,"TRIPPED"]],1),Je=(0,a.QT)(n.proto3,C,"InferenceHookEventType",[[0,"UNSPECIFIED"],[1,"PROMPT"],[2,"TOOL_CALL"]],1),we=(0,a.QT)(n.proto3,C,"BugbotMode",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"HIGH"],[3,"AUTO"],[5,"LOW"]],1),ye=(0,a.QT)(n.proto3,C,"EventCodeClaimState",[[0,"UNSPECIFIED"],[1,"UPCOMING"],[2,"OPEN"],[3,"FULL"],[4,"CLOSED"],[5,"DISABLED"]],1),Se=(0,a.QT)(n.proto3,C,"EventCodeCreditDestination",[[0,"UNSPECIFIED"],[1,"USAGE_GRANT"],[2,"STRIPE_CUSTOMER_BALANCE"]],1),qe=(0,a.QT)(n.proto3,C,"TeamRuleAgentType",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"SAND"],[3,"CURSOR"]],1),Be=(0,a.QT)(n.proto3,C,"GlobalCommandAvailability",[[0,"UNSPECIFIED"],[1,"ALL_AGENTS"],[2,"CLOUD_ONLY"],[3,"LOCAL_ONLY"]],1),Ie=(0,a.QT)(n.proto3,C,"GlobalCommandSurface",[[0,"UNSPECIFIED"],[1,"CLASSIC"],[2,"GLASS"],[3,"CLI"]],1),Pe=(0,a.QT)(n.proto3,C,"ProjectRepoSkillsOmissionReason",[[0,"UNSPECIFIED"],[1,"NO_GITHUB_CONNECTION"],[2,"GITHUB_APP_CANNOT_READ"],[3,"GITHUB_ENTERPRISE_HOST"],[4,"ATTENUATED_ORIGIN_SESSION"],[5,"REPO_LIMIT"],[6,"ORIGIN_NO_ACCESS"],[7,"ORIGIN_IP_ALLOWLIST"],[9,"ORIGIN_NOT_FOUND"]],1),be=(0,a.QT)(n.proto3,C,"DiamondToBugbotMigrationMode",[[0,"UNSPECIFIED"],[1,"DRY_RUN"],[2,"APPLY"]],1),Re=(0,a.QT)(n.proto3,C,"SharedConversationVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1),ve=(0,a.QT)(n.proto3,C,"SharedCanvasVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1),xe=(0,a.QT)(n.proto3,C,"CanvasBrand",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),ke=(0,a.QT)(n.proto3,C,"CanvasVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM_VIEW"],[3,"PUBLIC"]],1),Ee=(0,a.QT)(n.proto3,C,"ImposedModel",[[0,"UNSPECIFIED"],[1,"LATEST_CURSOR_MODEL"]],1),Ce=(0,a.QT)(n.proto3,C,"ImposedModelMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"SOFT"],[3,"HARD"]],1),Te=(0,a.QT)(n.proto3,C,"SmartAutoModelSeverity",[[0,"UNSPECIFIED"],[1,"REQUIRED"],[2,"RECOMMENDED"]],1),Ue=(0,a.QT)(n.proto3,C,"ClaudeCacheTtlPolicy",[[0,"UNSPECIFIED"],[1,"STANDARD_5M"],[2,"EXTENDED_1H"]],1),Ae=(0,a.QT)(n.proto3,C,"IndividualLimitsOptOutOutcome",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ALREADY_ALLOWED"],[3,"ENTERPRISE"],[4,"NOT_ADMIN"],[5,"CREATED_AFTER_CUTOFF"]],1),$e=(0,a.QT)(n.proto3,C,"SlackConversationType",[[0,"UNSPECIFIED"],[1,"CHANNEL"],[2,"DM"],[3,"GROUP_DM"]],1),Me=(0,a.QT)(n.proto3,C,"PluginStatus",[[0,"UNSPECIFIED"],[1,"DRAFT"],[2,"PENDING_APPROVAL"],[3,"APPROVED"],[4,"REJECTED"],[5,"UNLISTED"]],1),Oe=(0,a.QT)(n.proto3,C,"PluginLifecycleState",[[0,"UNSPECIFIED"],[1,"PUBLIC_LISTED"],[2,"PUBLIC_UNLISTED"],[3,"PUBLIC_DRAFT"],[4,"PUBLIC_PENDING"],[5,"PUBLIC_REJECTED"],[6,"PUBLISHER_SUBMISSION"],[7,"PRIVATE_ACTIVE"],[10,"PUBLIC_DEPRECATED"],[11,"PRIVATE_DEPRECATED"],[12,"PUBLIC_INVALID"],[13,"PRIVATE_INVALID"],[14,"PRIVATE_PUBLISHED"]],1),De=(0,a.QT)(n.proto3,C,"PluginSharepointInstallBlockDetail",[[0,"UNSPECIFIED"],[1,"NO_TEAM"],[2,"TEAM_NOT_CONNECTED"],[3,"TEAM_SETUP_UNFINISHED"]],1),Ne=(0,a.QT)(n.proto3,C,"PluginAccountUnavailableReason",[[0,"UNSPECIFIED"],[1,"TAILSCALE_NOT_ENABLED"]],1),Ge=(0,a.QT)(n.proto3,C,"PluginTeamAdminInstallBlockReason",[[0,"UNSPECIFIED"],[1,"MCP_ADMIN_POLICY"],[2,"FIRST_PARTY_ALLOWLIST"],[3,"TEAM_LIST"],[4,"SHAREPOINT_TEAM_ONLY"]],1),Le=(0,a.QT)(n.proto3,C,"ConnectorPolicyBlockedStage",[[0,"UNSPECIFIED"],[1,"IMPRESSION"],[2,"CONNECT_CLICK"]],1),Fe=(0,a.QT)(n.proto3,C,"ConnectorPolicyBlockedClient",[[0,"UNSPECIFIED"],[1,"GROK_BOT_DESKTOP"],[2,"GROK_BOT_MOBILE"],[3,"GROK_BOT_WEB"]],1),Ke=(0,a.QT)(n.proto3,C,"PluginMcpServerLinkUnknownCause",[[0,"UNSPECIFIED"],[1,"TEAM_NOT_LINKED"],[2,"ACCOUNT_NOT_LINKED"],[3,"NOT_GROK_TEAM_MEMBER"]],1),ze=(0,a.QT)(n.proto3,C,"ServedPlanResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"UNAVAILABLE"]],1),je=(0,a.QT)(n.proto3,C,"XaiOrganizationTeamLinkOutcomeKind",[[0,"UNSPECIFIED"],[1,"LINKED"],[2,"ALREADY_LINKED"],[3,"SKIPPED_DISABLED"],[4,"SKIPPED_UNMAPPED"],[5,"SKIPPED_OWNER_UNLINKED"],[6,"OWNER_LEFT_ORGANIZATION"],[7,"NOT_CONFIGURED"],[8,"GRANT_ROUTE_UNAVAILABLE"],[9,"GRANT_REFUSED"],[10,"CONFLICT"],[11,"UNAVAILABLE"],[12,"REJECTED"],[13,"FAILED"]],1),He=(0,a.QT)(n.proto3,C,"PluginPrimitiveType",[[0,"UNSPECIFIED"],[1,"SKILL"],[2,"MCP"],[3,"SUBAGENT"],[4,"COMMAND"]],1),We=(0,a.QT)(n.proto3,C,"PluginPrimitiveUsageInterval",[[0,"UNSPECIFIED"],[1,"LAST_1W"],[2,"ALL_TIME"],[3,"LAST_1D"],[4,"LAST_14D"],[5,"LAST_90D"],[6,"LAST_30D"]],1),Qe=(0,a.QT)(n.proto3,C,"McpServerAddBlockingSetting",[[0,"UNSPECIFIED"],[1,"MCP_ALLOWLIST"],[2,"CLOUD_AGENT_MCP_ALLOWLIST"]],1),Ve=(0,a.QT)(n.proto3,C,"EffectivePluginInstallMode",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM_DEFAULT"],[3,"TEAM_REQUIRED"]],1),Xe=(0,a.QT)(n.proto3,C,"TeamPluginsTableRowKind",[[0,"UNSPECIFIED"],[1,"PLUGIN"],[2,"MCP_SERVER"]],1),Ye=(0,a.QT)(n.proto3,C,"TeamPluginsTableAccessState",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"ENABLED"],[3,"DISABLED"],[4,"DISABLED_BY_ADMIN"]],1),Ze=(0,a.QT)(n.proto3,C,"TeamPluginsTableRuleKind",[[0,"UNSPECIFIED"],[1,"NO_ALLOWLIST"],[2,"RULE"],[3,"TEAM_LIST"],[4,"NOT_ALLOWED"]],1),tn=(0,a.QT)(n.proto3,C,"MarketplaceAccessPrincipalKind",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM_MEMBER_GROUP"],[3,"TEAM_ADMIN_GROUP"],[4,"GROUP"]],1),rn=(0,a.QT)(n.proto3,C,"TeamMarketplacePluginInstallMode",[[0,"OPTIONAL"],[1,"DEFAULT"],[2,"REQUIRED"]],1),en=(0,a.QT)(n.proto3,C,"GrokBatchRequestState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"SUCCEEDED"],[3,"CANCELLED"],[4,"FAILED"]],1),nn=(0,a.QT)(n.proto3,C,"GrokBatchResultFormat",[[0,"UNSPECIFIED"],[1,"JSON_REST"],[2,"PROTOBUF_B64"]],1),sn=(0,a.QT)(n.proto3,C,"GrokVoiceCloningRestriction",[[0,"UNSPECIFIED"],[1,"REGION"]],1),on=(0,a.QT)(n.proto3,C,"GrokVoiceCloneFailure",[[0,"UNSPECIFIED"],[1,"PASSPHRASE_MISMATCH"],[2,"SPEAKER_MISMATCH"],[3,"PASSPHRASE_EXPIRED"],[4,"AUDIO_QUALITY"],[5,"REGION_RESTRICTED"],[6,"CAP_REACHED"],[7,"TEMPORARY"]],1),an=(0,a.QT)(n.proto3,C,"GrokFilesSortBy",[[0,"UNSPECIFIED"],[1,"NAME"],[2,"SIZE"],[3,"AGE"]],1),un=(0,a.QT)(n.proto3,C,"GrokSortOrder",[[0,"UNSPECIFIED"],[1,"ASCENDING"],[2,"DESCENDING"]],1),cn=(0,a.QT)(n.proto3,C,"GrokFieldDefinitionOperation",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"DELETE"]],1),ln=(0,a.QT)(n.proto3,C,"GrokCollectionsSortBy",[[0,"UNSPECIFIED"],[1,"NAME"],[2,"AGE"],[3,"STATUS"],[4,"ACCESS"]],1),mn=(0,a.QT)(n.proto3,C,"GrokDocumentStatus",[[0,"UNSPECIFIED"],[1,"PROCESSING"],[2,"PROCESSED"],[3,"FAILED"],[4,"CHUNKED"],[5,"EMBEDDING"],[6,"WRITING"]],1),fn=(0,a.QT)(n.proto3,C,"GrokModelType",[[0,"UNSPECIFIED"],[1,"LANGUAGE"],[2,"EMBEDDING"],[3,"IMAGE"],[4,"VIDEO"],[5,"AUDIO"]],1),dn=(0,a.QT)(n.proto3,C,"GrokModelModality",[[0,"UNSPECIFIED"],[1,"TEXT"],[2,"IMAGE"],[3,"AUDIO"],[4,"VIDEO"]],1),pn=(0,a.QT)(n.proto3,C,"GrokVoiceEndpointKind",[[0,"UNSPECIFIED"],[1,"TTS"],[2,"STT"],[3,"REALTIME"]],1),hn=(0,a.QT)(n.proto3,C,"DashboardAppScope",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM"],[3,"SHARED"]],1),gn=(0,a.QT)(n.proto3,C,"DashboardAppViewerRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"TEAM_ADMIN"],[3,"EDITOR"]],1),_n=(0,a.QT)(n.proto3,C,"AppApiKeyAccess",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"TEAM_KEYS_OFF"],[3,"UNAVAILABLE"]],1);class Jn extends T{constructor(t){super(),this.code="",this.installationId="",this.setupAction="",this.cursorCode="",this.source=wn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["ConnectGithubCallbackRequest|1 code 9|2 installation_id 9|3 setup_action 9|4 cursor_code 9|5 source #0|7 ghe_application 9?",wn]}}var wn=(0,a.QT)(n.proto3,C,"ConnectGithubCallbackRequest.Source",[[0,"UNSPECIFIED"],[1,"APP"],[2,"SLACK"]],1);class yn extends T{constructor(t){super(),this.needConfirmation=!1,this.installationId="",this.confirmationCode="",this.githubLogin="",this.pendingApproval=!1,this.githubUserNodeId="",this.githubUserDatabaseId="",this.githubName="",this.githubAvatarUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["ConnectGithubCallbackResponse|1 need_confirmation 8|2 installation_id 9|3 confirmation_code 9|4 github_login 9|5 pending_approval 8|6 github_user_node_id 9|7 github_user_database_id 9|8 github_name 9|9 github_avatar_url 9"]}}class Sn extends T{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["ScmConnectIntentTarget|1 user #0 target|2 team_id 5 target",qn]}}class qn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["ScmConnectIntentTarget.User"]}}class Bn extends T{constructor(t){super(),this.githubRepo="",this.source=In.UNSPECIFIED,this.verifierHash="",this.forceOauth=!1,this.completionBinding=Pn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["PrepareGithubConnectFlowRequest|1 github_repo 9|2 ghe_application 9?|3 source #0|4 verifier_hash 9|5 force_oauth 8|6 connect_target #1?|7 connect_source #2?|8 completion_binding #3|9 grok_bot_callback_url 9?",In,Sn,U,Pn]}}var In=(0,a.QT)(n.proto3,C,"PrepareGithubConnectFlowRequest.Source",[[0,"UNSPECIFIED"],[1,"GLASS_CLOUD_AGENT"],[2,"GLASS_DIFF"],[3,"GLASS_AUTOMATIONS"],[4,"GROK_BOT"]],1),Pn=(0,a.QT)(n.proto3,C,"PrepareGithubConnectFlowRequest.CompletionBinding",[[0,"UNSPECIFIED"],[1,"CLIENT_VERIFIER"],[2,"ACCOUNT"]],1);class bn extends T{constructor(t){super(),this.flowId="",this.state="",this.githubUrl="",this.expiresAtMs=n.protoInt64.zero,this.shouldInstall=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["PrepareGithubConnectFlowResponse|1 flow_id 9|2 state 9|3 github_url 9|4 expires_at_ms 3|5 should_install 8|6 ghe_application 9?"]}}class Rn extends T{constructor(t){super(),this.state="",this.verifier="",this.code="",this.installationId="",this.setupAction="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["CompleteGithubConnectFlowRequest|1 state 9|2 verifier 9|3 code 9|4 installation_id 9|5 setup_action 9|6 ghe_application 9?"]}}class vn extends T{constructor(t){super(),this.outcome=xn.UNSPECIFIED,this.installationId="",this.confirmationCode="",this.githubLogin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["CompleteGithubConnectFlowResponse|1 outcome #0|2 installation_id 9|3 confirmation_code 9|4 github_login 9|5 ghe_application 9?",xn]}}var xn=(0,a.QT)(n.proto3,C,"CompleteGithubConnectFlowResponse.Outcome",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"PENDING_APPROVAL"],[3,"NEEDS_CONFIRMATION"]],1);class kn extends T{constructor(t){super(),this.hostname="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["PrepareSetupGithubEnterpriseAppRequest|1 hostname 9|2 external_host 9?|3 team_id 5?"]}}class En extends T{constructor(t){super(),this.pendingAppUuid="",this.serializedManifest="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["PrepareSetupGithubEnterpriseAppResponse|1 pending_app_uuid 9|2 serialized_manifest 9"]}}class Cn extends T{constructor(t){super(),this.installationCode="",this.pendingAppUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["FinishSetupGithubEnterpriseAppRequest|1 installation_code 9|2 pending_app_uuid 9"]}}class Tn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["FinishSetupGithubEnterpriseAppResponse|1 install_url 9?"]}}class Un extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["ListGithubEnterpriseAppsRequest|1 team_id 5?"]}}class An extends T{constructor(t){super(),this.apps=[],this.canManage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["ListGithubEnterpriseAppsResponse|1 apps #0*|2 can_manage 8",$n]}}class $n extends T{constructor(t){super(),this.uuid="",this.slug="",this.hostname="",this.canDelete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["ListGithubEnterpriseAppsResponse.GithubEnterpriseApp|1 uuid 9|2 slug 9|3 hostname 9|4 can_delete 8|5 html_url 9?"]}}class Mn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["DeleteGithubEnterpriseAppRequest|1 uuid 9"]}}class On extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["DeleteGithubEnterpriseAppResponse"]}}class Dn extends T{constructor(t){super(),this.hostname="",this.accessToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["SetupGitlabEnterpriseInstanceRequest|1 hostname 9|2 access_token 9|3 group_path 9?|4 slug 9?|5 client_id 9?|6 client_secret 9?|7 external_host 9?|8 team_id 5?"]}}class Nn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["SetupGitlabEnterpriseInstanceResponse|1 uuid 9"]}}class Gn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["ListGitlabEnterpriseInstancesRequest|1 team_id 5?"]}}class Ln extends T{constructor(t){super(),this.instances=[],this.gitlabServiceAccountTokenConfigured=!1,this.canManageGitlabServiceAccountToken=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["ListGitlabEnterpriseInstancesResponse|1 instances #0*|2 gitlab_service_account_token_configured 8|3 can_manage_gitlab_service_account_token 8",Fn]}}class Fn extends T{constructor(t){super(),this.uuid="",this.hostname="",this.username="",this.canDelete=!1,this.hostControlledWebhookUrl="",this.hostControlledWebhookSecret="",this.hostControlledServiceAccountTokenConfigured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["ListGitlabEnterpriseInstancesResponse.GitlabEnterpriseInstance|1 uuid 9|2 hostname 9|3 username 9|4 can_delete 8|5 host_controlled_webhook_url 9|6 host_controlled_webhook_secret 9|7 host_controlled_service_account_token_configured 8|8 external_host 9?"]}}class Kn extends T{constructor(t){super(),this.gitEnterpriseUuid="",this.accessToken="",this.clearToken=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["SetGitlabEnterpriseHostControlledServiceAccountTokenRequest|1 git_enterprise_uuid 9|2 access_token 9|3 clear_token 8|4 team_id 5?"]}}class zn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["SetGitlabEnterpriseHostControlledServiceAccountTokenResponse"]}}class jn extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["RotateGitlabEnterpriseWebhookSecretRequest|1 git_enterprise_uuid 9|2 team_id 5?"]}}class Hn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["RotateGitlabEnterpriseWebhookSecretResponse"]}}class Wn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["DeleteGitlabEnterpriseInstanceRequest|1 uuid 9|2 team_id 5?"]}}class Qn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["DeleteGitlabEnterpriseInstanceResponse"]}}class Vn extends T{constructor(t){super(),this.hostname="",this.accessToken="",this.oauthClientId="",this.oauthClientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["SetupBitbucketServerInstanceRequest|1 hostname 9|2 external_host 9?|3 access_token 9|4 oauth_client_id 9|5 oauth_client_secret 9"]}}class Xn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["SetupBitbucketServerInstanceResponse|1 uuid 9"]}}class Yn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ListBitbucketServerInstancesRequest"]}}class Zn extends T{constructor(t){super(),this.instances=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ListBitbucketServerInstancesResponse|1 instances #0*",ts]}}class ts extends T{constructor(t){super(),this.uuid="",this.hostname="",this.externalHost="",this.canDelete=!1,this.serviceAccountTokenConfigured=!1,this.browserBaseUrl="",this.outboundBaseUrl="",this.oauthAppConfigured=!1,this.currentUserConnected=!1,this.membersCanLink=!1,this.currentUserReconnectRequired=!1,this.connectedAccountCount=0,this.listsReposWithOwnAccount=!1,this.currentUserWriteAccessMissing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["ListBitbucketServerInstancesResponse.BitbucketServerInstance|1 uuid 9|2 hostname 9|3 external_host 9|4 can_delete 8|5 service_account_token_configured 8|6 browser_base_url 9|7 outbound_base_url 9|8 oauth_app_configured 8|9 current_user_connected 8|10 members_can_link 8|11 current_user_reconnect_required 8|12 connected_account_count 5|13 lists_repos_with_own_account 8|14 current_user_write_access_missing 8"]}}class rs extends T{constructor(t){super(),this.uuid="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest|1 uuid 9|2 set_token #0 action|3 clear_token #1 action",es,ns]}}class es extends T{constructor(t){super(),this.accessToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest.SetToken|1 access_token 9"]}}class ns extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest.ClearToken"]}}class ss extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenResponse"]}}class is extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["DeleteBitbucketServerInstanceRequest|1 uuid 9"]}}class os extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["DeleteBitbucketServerInstanceResponse"]}}class as extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["SyncGitlabReposRequest|1 git_enterprise_uuid 9|2 team_id 5?"]}}class us extends T{constructor(t){super(),this.started=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["SyncGitlabReposResponse|1 started 8|2 error_message 9"]}}class cs extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["GetGitlabReposSyncStatusRequest|1 git_enterprise_uuid 9"]}}class ls extends T{constructor(t){super(),this.status=A.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["GetGitlabReposSyncStatusResponse|1 status #0|2 error_message 9?|3 repos_populated 5?",A]}}class ms extends T{constructor(t){super(),this.installationId="",this.confirmationCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["ConfirmGithubInstallationRequest|1 installation_id 9|2 confirmation_code 9"]}}class fs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["ConfirmGithubInstallationResponse|1 ghe_application 9?"]}}class ds extends T{constructor(t){super(),this.githubRepo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["RegisterGithubCursorCodeRequest|1 github_repo 9|3 ghe_application 9?|4 connect_target #0?|5 connect_source #1?",Sn,U]}}class ps extends T{constructor(t){super(),this.cursorCode="",this.shouldInstall=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["RegisterGithubCursorCodeResponse|1 cursor_code 9|2 should_install 8|3 ghe_hostname 9?|4 ghe_app_slug 9?|5 ghe_client_id 9?|6 github_oauth_client_id 9?|7 github_app_slug 9?|8 ghe_app_html_url 9?"]}}class hs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["DisconnectGithubRequest|2 ghe_application 9?|3 user_only 8?"]}}class gs extends T{constructor(t){super(),this.removedConnectionsCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["DisconnectGithubResponse|1 removed_connections_count 5"]}}class _s extends T{constructor(t){super(),this.requestQuota=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["UpdateFastRequestsRequest|1 request_quota 5"]}}class Js extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["UpdateFastRequestsResponse"]}}class ws extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["GetFastRequestsRequest"]}}class ys extends T{constructor(t){super(),this.requestQuota=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["GetFastRequestsResponse|1 request_quota 5"]}}class Ss extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["DeleteAccountRequest"]}}class qs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["DeleteAccountResponse"]}}class Bs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["GetAccountSettingsRequest"]}}class Is extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["AccountSettings|1 profile #0|2 xai_link #1|3 cursor #2",Ps,bs,Rs]}}class Ps extends T{constructor(t){super(),this.givenName="",this.familyName="",this.email="",this.profileImageUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["AccountProfile|1 given_name 9|2 family_name 9|3 email 9|4 profile_image_url 9"]}}class bs extends T{constructor(t){super(),this.status=$.UNSPECIFIED,this.sessionsAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["AccountXaiLink|1 status #0|2 sessions_available 8",$]}}class Rs extends T{constructor(t){super(),this.onPaidTeam=!1,this.pricingOptedOut=!1,this.unpaidTeamAdminDeletionMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["AccountCursorControls|1 on_paid_team 8|2 pricing_opted_out 8|3 unpaid_team_admin_deletion_message 9"]}}class vs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["GetAccountDeletionSummaryRequest"]}}class xs extends T{constructor(t){super(),this.grokBotCount=0,this.recentGrokBots=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["AccountDeletionSummary|1 cursor_member_since #0|2 grok_bot_count 5|3 recent_grok_bots #1*|4 cursor_profile #2|5 grok_account #3",n.Timestamp,Es,Ps,ks]}}class ks extends T{constructor(t){super(),this.email="",this.xUsername="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["AccountDeletionGrokAccount|1 email 9|2 x_username 9"]}}class Es extends T{constructor(t){super(),this.agentId="",this.name="",this.avatarUrl="",this.avatarShape="",this.avatarColor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["AccountDeletionGrokBot|1 agent_id 9|2 name 9|3 avatar_url 9|4 avatar_shape 9|5 avatar_color 9"]}}class Cs extends T{constructor(t){super(),this.target=M.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["CreateAccountHandoffRequest|1 target #0",M]}}class Ts extends T{constructor(t){super(),this.url="",this.signedIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["CreateAccountHandoffResponse|1 url 9|2 signed_in 8"]}}class Us extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Us,t,r)}static $(){return["GetMeRequest|1 team_id 5?|2 source_site_hostname 9?|3 include_mobile_app_status 8?|4 include_individual_plan 8?"]}}class As extends T{constructor(t){super(),this.authId="",this.userId=0,this.adminSessionManagementEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(As,t,r)}static $(){return["GetMeResponse|1 auth_id 9|2 user_id 5|3 email 9?|4 first_name 9?|5 last_name 9?|6 workos_id 9?|7 team_id 5?|8 created_at 9?|9 is_enterprise_user 8?|10 team_name 9?|11 email_domain_type 9?|12 country 9?|13 profile_picture_url 9?|14 cursor_review_onboarding_use_cursor_github_app 8?|15 organization_id 3?|16 organization_public_id 9?|17 is_team_admin 8?|18 has_active_mobile_session 8?|19 public_user_id 9?|20 scm_only_restricted 8?|21 email_is_synthetic 8?|22 signup_source 9?|23 admin_session_management_enabled 8|24 has_individual_plan 8?|25 membership_type 9?"]}}class $s extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($s,t,r)}static $(){return["GetAgenticOnboardingConfigRequest"]}}class Ms extends T{constructor(t){super(),this.agenticOnboardingEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ms,t,r)}static $(){return["GetAgenticOnboardingConfigResponse|1 agentic_onboarding_enabled 8"]}}class Os extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["GetUserOrganizationsRequest"]}}class Ds extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["GetTeamLinkedOrganizationRequest|1 team_id 5"]}}class Ns extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["GetTeamLinkedOrganizationResponse|1 organization #0?",Gs]}}class Gs extends T{constructor(t){super(),this.organizationId="",this.organizationName="",this.organizationSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["GetTeamLinkedOrganizationResponse.Organization|1 organization_id 9|2 organization_name 9|3 organization_slug 9"]}}class Ls extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["SetUserDefaultTeamRequest|1 team_id 5"]}}class Fs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["SetUserDefaultTeamResponse"]}}class Ks extends T{constructor(t){super(),this.organizations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["GetUserOrganizationsResponse|1 organizations #0*",js]}}class zs extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.teamSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["GetUserOrganizationsResponse.Team|1 team_id 5|2 team_name 9|3 team_slug 9|4 team_organization_membership_created_at_ms 3?|5 viewer_team_role #0?|6 team_deleted_at_ms 3?|7 icon_url 9?",it]}}class js extends T{constructor(t){super(),this.organizationId="",this.organizationName="",this.organizationSlug="",this.role=O.UNSPECIFIED,this.teams=[],this.grantedPermissions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["GetUserOrganizationsResponse.Organization|1 organization_id 9|2 organization_name 9|3 organization_slug 9|4 role #0|5 teams #1*|6 default_team_id 5?|7 effective_max_teams 5?|8 granted_permissions 9*|9 can_create_organization_teams 8?|10 root_team_id 5?|11 xai_team_linked 8?|12 icon_url 9?",O,zs]}}class Hs extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.teamSlug="",this.teamRole=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["OrganizationMemberTeam|1 team_id 5|2 team_name 9|3 team_slug 9|4 team_role #0",it]}}class Ws extends T{constructor(t){super(),this.userId=0,this.authId="",this.role=O.UNSPECIFIED,this.teams=[],this.memberPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["OrganizationMember|1 user_id 5|2 auth_id 9|3 email 9?|4 first_name 9?|5 last_name 9?|6 role #0|7 teams #1*|8 member_public_id 9",O,Hs]}}class Qs extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["GetOrganizationMembersRequest|1 organization_id 9|2 page 5?|3 page_size 5?|4 search_term 9?|5 sort_by 9?|6 sort_direction 9?|7 role_filter #0?|8 team_id 5?",O]}}class Vs extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["GetOrganizationMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5",Ws]}}class Xs extends T{constructor(t){super(),this.groupPublicId="",this.groupName="",this.joinedAt=n.protoInt64.zero,this.isAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xs).fromBinary(t,r)}static fromJson(t,r){return(new Xs).fromJson(t,r)}static fromJsonString(t,r){return(new Xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xs,t,r)}static $(){return["OrganizationMemberGroup|1 group_public_id 9|2 group_name 9|3 joined_at 3|4 is_admin 8|5 monthly_spending_limit_dollars 5?"]}}class Ys extends T{constructor(t){super(),this.organizationId="",this.memberPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ys,t,r)}static $(){return["GetOrganizationMemberRequest|1 organization_id 9|2 member_public_id 9"]}}class Zs extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zs,t,r)}static $(){return["GetOrganizationMemberResponse|1 member #0|2 groups #1*",Ws,Xs]}}class ti extends T{constructor(t){super(),this.teamPublicId="",this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ti,t,r)}static $(){return["OrganizationIdentityProviderUsedByTeam|1 team_public_id 9|2 team_name 9"]}}class ri extends T{constructor(t){super(),this.connected=!1,this.summary="",this.manageLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ri,t,r)}static $(){return["OrganizationIdentityProviderSsoSettings|1 connected 8|2 summary 9|3 manage_link 9"]}}class ei extends T{constructor(t){super(),this.verified=[],this.pending=[],this.verifyLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ei,t,r)}static $(){return["OrganizationIdentityProviderDomains|1 verified 9*|2 pending 9*|3 verify_link 9"]}}class ni extends T{constructor(t){super(),this.connected=!1,this.summary="",this.manageLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ni,t,r)}static $(){return["OrganizationIdentityProviderScimSettings|1 connected 8|2 summary 9|3 manage_link 9"]}}class si extends T{constructor(t){super(),this.enabled=!1,this.allowedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new si).fromBinary(t,r)}static fromJson(t,r){return(new si).fromJson(t,r)}static fromJsonString(t,r){return(new si).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(si,t,r)}static $(){return["OrganizationIdentityProviderDomainJoinSettings|1 enabled 8|2 allowed_domains 9*"]}}class ii extends T{constructor(t){super(),this.publicId="",this.isDefault=!1,this.status="",this.usedByTeams=[],this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ii,t,r)}static $(){return["OrganizationIdentityProvider|1 public_id 9|2 is_default 8|3 status 9|4 used_by_teams #0*|5 description 9|6 sso #1|7 domains #2|8 scim #3|9 domain_join #4",ti,ri,ei,ni,si]}}class oi extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oi,t,r)}static $(){return["ListOrganizationIdentityProvidersRequest|1 organization_id 9"]}}class ai extends T{constructor(t){super(),this.providers=[],this.mergeEnabled=!1,this.scimInsideIdentityProviderEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ai,t,r)}static $(){return["ListOrganizationIdentityProvidersResponse|1 providers #0*|2 merge_enabled 8|3 scim_inside_identity_provider_enabled 8",ii]}}class ui extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.allowSso=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ui,t,r)}static $(){return["UpdateOrganizationIdentityProviderSsoSettingsRequest|1 organization_id 9|2 identity_provider_public_id 9|3 allow_sso 8"]}}class ci extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.allowDomainJoin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ci,t,r)}static $(){return["SetOrganizationIdentityProviderAllowDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 allow_domain_join 8"]}}class li extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.domain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new li).fromBinary(t,r)}static fromJson(t,r){return(new li).fromJson(t,r)}static fromJsonString(t,r){return(new li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(li,t,r)}static $(){return["AddOrganizationIdentityProviderDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 domain 9"]}}class mi extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.domain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mi).fromBinary(t,r)}static fromJson(t,r){return(new mi).fromJson(t,r)}static fromJsonString(t,r){return(new mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mi,t,r)}static $(){return["RemoveOrganizationIdentityProviderDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 domain 9"]}}class fi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fi).fromBinary(t,r)}static fromJson(t,r){return(new fi).fromJson(t,r)}static fromJsonString(t,r){return(new fi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fi,t,r)}static $(){return["UpdateOrganizationIdentityProviderResponse|1 provider #0",ii]}}class di extends T{constructor(t){super(),this.organizationId="",this.sourceIdentityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new di).fromBinary(t,r)}static fromJson(t,r){return(new di).fromJson(t,r)}static fromJsonString(t,r){return(new di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(di,t,r)}static $(){return["MergeOrganizationIdentityProviderRequest|1 organization_id 9|2 source_identity_provider_public_id 9"]}}class pi extends T{constructor(t){super(),this.requestPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pi,t,r)}static $(){return["MergeOrganizationIdentityProviderResponse|1 request_public_id 9"]}}class hi extends T{constructor(t){super(),this.organizationId="",this.sourceIdentityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hi,t,r)}static $(){return["PreflightMergeOrganizationIdentityProviderRequest|1 organization_id 9|2 source_identity_provider_public_id 9"]}}class gi extends T{constructor(t){super(),this.code="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gi).fromBinary(t,r)}static fromJson(t,r){return(new gi).fromJson(t,r)}static fromJsonString(t,r){return(new gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gi,t,r)}static $(){return["OrganizationMergeIdpBlocker|1 code 9|2 message 9"]}}class _i extends T{constructor(t){super(),this.canMerge=!1,this.blockers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_i,t,r)}static $(){return["PreflightMergeOrganizationIdentityProviderResponse|1 can_merge 8|2 blockers #0*",gi]}}class Ji extends T{constructor(t){super(),this.requestPublicId="",this.status="",this.processedUsers=0,this.movedMembershipCount=0,this.skippedMembershipCount=0,this.failedMembershipCount=0,this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ji,t,r)}static $(){return["OrganizationMergeIdpRequestInfo|1 request_public_id 9|2 status 9|3 current_phase 9?|4 source_identity_provider_public_id 9?|5 target_identity_provider_public_id 9?|6 total_users 5?|7 processed_users 5|8 moved_membership_count 5|9 skipped_membership_count 5|10 failed_membership_count 5|11 last_error 9?|12 created_at_ms 3|13 started_at_ms 3?|14 completed_at_ms 3?|15 source_deletion_eligible_at_ms 3?"]}}class wi extends T{constructor(t){super(),this.organizationId="",this.requestPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wi).fromBinary(t,r)}static fromJson(t,r){return(new wi).fromJson(t,r)}static fromJsonString(t,r){return(new wi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wi,t,r)}static $(){return["GetOrganizationMergeIdpRequestRequest|1 organization_id 9|2 request_public_id 9"]}}class yi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yi).fromBinary(t,r)}static fromJson(t,r){return(new yi).fromJson(t,r)}static fromJsonString(t,r){return(new yi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yi,t,r)}static $(){return["GetOrganizationMergeIdpRequestResponse|1 request #0",Ji]}}class Si extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Si).fromBinary(t,r)}static fromJson(t,r){return(new Si).fromJson(t,r)}static fromJsonString(t,r){return(new Si).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Si,t,r)}static $(){return["ListOrganizationMergeIdpRequestsRequest|1 organization_id 9"]}}class qi extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qi,t,r)}static $(){return["ListOrganizationMergeIdpRequestsResponse|1 requests #0*",Ji]}}class Bi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.destinationTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bi,t,r)}static $(){return["MoveOrganizationMemberToTeamRequest|1 organization_id 9|2 user_id 5|3 destination_team_id 5"]}}class Ii extends T{constructor(t){super(),this.moved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ii,t,r)}static $(){return["MoveOrganizationMemberToTeamResponse|1 moved 8"]}}class Pi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.teamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pi,t,r)}static $(){return["SetOrganizationMemberTeamsRequest|1 organization_id 9|2 user_id 5|3 team_ids 5*"]}}class bi extends T{constructor(t){super(),this.changed=!1,this.addedTeamIds=[],this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bi,t,r)}static $(){return["SetOrganizationMemberTeamsResponse|1 changed 8|2 added_team_ids 5*|3 removed_team_ids 5*"]}}class Ri extends T{constructor(t){super(),this.organizationId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ri).fromBinary(t,r)}static fromJson(t,r){return(new Ri).fromJson(t,r)}static fromJsonString(t,r){return(new Ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ri,t,r)}static $(){return["RemoveOrganizationMemberRequest|1 organization_id 9|2 user_id 5"]}}class vi extends T{constructor(t){super(),this.removed=!1,this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vi).fromBinary(t,r)}static fromJson(t,r){return(new vi).fromJson(t,r)}static fromJsonString(t,r){return(new vi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vi,t,r)}static $(){return["RemoveOrganizationMemberResponse|1 removed 8|2 removed_team_ids 5*"]}}class xi extends T{constructor(t){super(),this.email="",this.destinationTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xi).fromBinary(t,r)}static fromJson(t,r){return(new xi).fromJson(t,r)}static fromJsonString(t,r){return(new xi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xi,t,r)}static $(){return["OrganizationMemberTeamMove|1 email 9|2 destination_team_id 5|3 destination_team_name 9?"]}}class ki extends T{constructor(t){super(),this.organizationId="",this.moves=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ki,t,r)}static $(){return["BulkMoveOrganizationMembersRequest|1 organization_id 9|2 moves #0*",xi]}}class Ei extends T{constructor(t){super(),this.addedCount=0,this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ei,t,r)}static $(){return["BulkOrganizationMemberMoveResult|1 added_count 5|2 removed_count 5|3 error_message 9?"]}}class Ci extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ci,t,r)}static $(){return["BulkMoveOrganizationMembersResponse|1 results #0*",Ei]}}class Ti extends T{constructor(t){super(),this.organizationId="",this.moves=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ti,t,r)}static $(){return["StartBulkMoveOrganizationMembersRequest|1 organization_id 9|2 moves #0*",xi]}}class Ui extends T{constructor(t){super(),this.jobHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ui,t,r)}static $(){return["StartBulkMoveOrganizationMembersResponse|1 job_handle 9"]}}class Ai extends T{constructor(t){super(),this.jobHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ai,t,r)}static $(){return["GetBackgroundJobRequest|1 job_handle 9"]}}class $i extends T{constructor(t){super(),this.phase="",this.percentDone=0,this.metadata={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $i).fromBinary(t,r)}static fromJson(t,r){return(new $i).fromJson(t,r)}static fromJsonString(t,r){return(new $i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($i,t,r)}static $(){return["BackgroundJobStatus|1 phase 9|2 percent_done 2|3 message 9?|4 error 9?|5 metadata 9,9|6 result_json 9?"]}}class Mi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mi).fromBinary(t,r)}static fromJson(t,r){return(new Mi).fromJson(t,r)}static fromJsonString(t,r){return(new Mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mi,t,r)}static $(){return["GetBackgroundJobResponse|1 status #0?",$i]}}class Oi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.role=O.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oi).fromBinary(t,r)}static fromJson(t,r){return(new Oi).fromJson(t,r)}static fromJsonString(t,r){return(new Oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oi,t,r)}static $(){return["SetOrganizationMemberRoleRequest|1 organization_id 9|2 user_id 5|3 role #0",O]}}class Di extends T{constructor(t){super(),this.updated=!1,this.role=O.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Di).fromBinary(t,r)}static fromJson(t,r){return(new Di).fromJson(t,r)}static fromJsonString(t,r){return(new Di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Di,t,r)}static $(){return["SetOrganizationMemberRoleResponse|1 updated 8|2 role #0",O]}}class Ni extends T{constructor(t){super(),this.organizationId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ni).fromBinary(t,r)}static fromJson(t,r){return(new Ni).fromJson(t,r)}static fromJsonString(t,r){return(new Ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ni,t,r)}static $(){return["UpdateOrganizationRequest|1 organization_id 9|2 name 9"]}}class Gi extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gi).fromBinary(t,r)}static fromJson(t,r){return(new Gi).fromJson(t,r)}static fromJsonString(t,r){return(new Gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gi,t,r)}static $(){return["UpdateOrganizationResponse|1 name 9"]}}class Li extends T{constructor(t){super(),this.organizationId="",this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Li).fromBinary(t,r)}static fromJson(t,r){return(new Li).fromJson(t,r)}static fromJsonString(t,r){return(new Li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Li,t,r)}static $(){return["UploadOrganizationIconRequest|1 organization_id 9|2 content_type 9|3 bytes 12"]}}class Fi extends T{constructor(t){super(),this.iconUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fi).fromBinary(t,r)}static fromJson(t,r){return(new Fi).fromJson(t,r)}static fromJsonString(t,r){return(new Fi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fi,t,r)}static $(){return["UploadOrganizationIconResponse|1 icon_url 9"]}}class Ki extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ki).fromBinary(t,r)}static fromJson(t,r){return(new Ki).fromJson(t,r)}static fromJsonString(t,r){return(new Ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ki,t,r)}static $(){return["UpdateOrganizationIconRequest|1 organization_id 9|2 icon_url 9?"]}}class zi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zi).fromBinary(t,r)}static fromJson(t,r){return(new zi).fromJson(t,r)}static fromJsonString(t,r){return(new zi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zi,t,r)}static $(){return["UpdateOrganizationIconResponse|1 icon_url 9?"]}}class ji extends T{constructor(t){super(),this.organizationId="",this.teamId=0,this.name="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ji).fromBinary(t,r)}static fromJson(t,r){return(new ji).fromJson(t,r)}static fromJsonString(t,r){return(new ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ji,t,r)}static $(){return["UpdateOrganizationTeamRequest|1 organization_id 9|2 team_id 5|3 name 9|4 slug 9"]}}class Hi extends T{constructor(t){super(),this.name="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hi).fromBinary(t,r)}static fromJson(t,r){return(new Hi).fromJson(t,r)}static fromJsonString(t,r){return(new Hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hi,t,r)}static $(){return["UpdateOrganizationTeamResponse|1 name 9|2 slug 9"]}}class Wi extends T{constructor(t){super(),this.organizationId="",this.name="",this.slug="",this.ownerUserId=0,this.identityProviderMode=G.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wi).fromBinary(t,r)}static fromJson(t,r){return(new Wi).fromJson(t,r)}static fromJsonString(t,r){return(new Wi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wi,t,r)}static $(){return["CreateOrganizationTeamRequest|1 organization_id 9|2 name 9|3 slug 9|4 owner_user_id 5|5 scim_mapping #0?|6 identity_provider_mode #1|7 settings_copy #2?",oo,G,Qi]}}class Qi extends T{constructor(t){super(),this.sourceTeamId=0,this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qi).fromBinary(t,r)}static fromJson(t,r){return(new Qi).fromJson(t,r)}static fromJsonString(t,r){return(new Qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qi,t,r)}static $(){return["OrganizationTeamSettingsCopy|1 source_team_id 5|2 categories #0*",D]}}class Vi extends T{constructor(t){super(),this.category=D.UNSPECIFIED,this.outcome=N.UNSPECIFIED,this.itemCount=0,this.detail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vi).fromBinary(t,r)}static fromJson(t,r){return(new Vi).fromJson(t,r)}static fromJsonString(t,r){return(new Vi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vi,t,r)}static $(){return["OrganizationTeamSettingsCopyCategoryResult|1 category #0|2 outcome #1|3 item_count 5|4 detail 9",D,N]}}class Xi extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xi).fromBinary(t,r)}static fromJson(t,r){return(new Xi).fromJson(t,r)}static fromJsonString(t,r){return(new Xi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xi,t,r)}static $(){return["PreviewOrganizationTeamSettingsCopyRequest|1 organization_id 9|2 settings_copy #0|3 target_team_id 5?",Qi]}}class Yi extends T{constructor(t){super(),this.results=[],this.reconnectTypes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yi).fromBinary(t,r)}static fromJson(t,r){return(new Yi).fromJson(t,r)}static fromJsonString(t,r){return(new Yi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yi,t,r)}static $(){return["PreviewOrganizationTeamSettingsCopyResponse|1 results #0*|2 reconnect_types 9*|3 existing_team #1",Vi,Zi]}}class Zi extends T{constructor(t){super(),this.changedAreas=[],this.setupScriptsRemovedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zi).fromBinary(t,r)}static fromJson(t,r){return(new Zi).fromJson(t,r)}static fromJsonString(t,r){return(new Zi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zi,t,r)}static $(){return["OrganizationTeamSettingsCopyExistingTeamPreview|1 changed_areas 9*|2 setup_scripts_removed_count 5|3 team_rules #0|4 refused_reason 9?",to]}}class to extends T{constructor(t){super(),this.addedCount=0,this.skippedExistingNameCount=0,this.notCopiedReason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new to).fromBinary(t,r)}static fromJson(t,r){return(new to).fromJson(t,r)}static fromJsonString(t,r){return(new to).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(to,t,r)}static $(){return["OrganizationTeamSettingsCopyGrokBotTeamRules|1 added_count 5|2 skipped_existing_name_count 5|3 not_copied_reason 9"]}}class ro extends T{constructor(t){super(),this.organizationId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ro).fromBinary(t,r)}static fromJson(t,r){return(new ro).fromJson(t,r)}static fromJsonString(t,r){return(new ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ro,t,r)}static $(){return["CopyOrganizationTeamSettingsToTeamRequest|1 organization_id 9|2 target_team_id 5|3 settings_copy #0",Qi]}}class eo extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eo).fromBinary(t,r)}static fromJson(t,r){return(new eo).fromJson(t,r)}static fromJsonString(t,r){return(new eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eo,t,r)}static $(){return["CopyOrganizationTeamSettingsToTeamResponse|1 results #0*|2 team_rules #1",Vi,to]}}class no extends T{constructor(t){super(),this.organizationId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new no).fromBinary(t,r)}static fromJson(t,r){return(new no).fromJson(t,r)}static fromJsonString(t,r){return(new no).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(no,t,r)}static $(){return["ListOrganizationTeamSettingsCopySourcesRequest|1 organization_id 9|2 target_team_id 5|3 category #0?",D]}}class so extends T{constructor(t){super(),this.sourceTeams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new so).fromBinary(t,r)}static fromJson(t,r){return(new so).fromJson(t,r)}static fromJsonString(t,r){return(new so).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(so,t,r)}static $(){return["ListOrganizationTeamSettingsCopySourcesResponse|1 source_teams #0*",io]}}class io extends T{constructor(t){super(),this.teamId=0,this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new io).fromBinary(t,r)}static fromJson(t,r){return(new io).fromJson(t,r)}static fromJsonString(t,r){return(new io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(io,t,r)}static $(){return["OrganizationTeamSettingsCopySourceTeam|1 team_id 5|2 team_name 9"]}}class oo extends T{constructor(t){super(),this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oo).fromBinary(t,r)}static fromJson(t,r){return(new oo).fromJson(t,r)}static fromJsonString(t,r){return(new oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oo,t,r)}static $(){return["CreateOrganizationTeamScimMapping|1 scim_directory_id 3|2 scim_group_external_id 9"]}}class ao extends T{constructor(t){super(),this.teamId=0,this.name="",this.slug="",this.settingsCopyResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ao,t,r)}static $(){return["CreateOrganizationTeamResponse|1 team_id 5|2 name 9|3 slug 9|4 settings_copy_results #0*",Vi]}}class uo extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.step="",this.source=L.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uo,t,r)}static $(){return["TeamXaiMembershipHold|1 team_id 5|2 user_id 5|3 step 9|4 source #0|5 xai_status 5?|6 well_known_code 9?|7 xai_user_id 9?|8 link_next_step 9?|9 reason 9?|10 held_since #1|11 note 9?",L,n.Timestamp]}}class co extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(co,t,r)}static $(){return["GetOrganizationScimSourceRequest|1 organization_id 9"]}}class lo extends T{constructor(t){super(),this.source=F.UNSPECIFIED,this.resolution=K.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lo,t,r)}static $(){return["GetOrganizationScimSourceResponse|1 source #0|2 resolution #1",F,K]}}class mo extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mo,t,r)}static $(){return["GetOrganizationTeamAdminCandidatesRequest|1 organization_id 9"]}}class fo extends T{constructor(t){super(),this.userId=0,this.email="",this.firstName="",this.lastName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fo,t,r)}static $(){return["OrganizationTeamAdminCandidate|1 user_id 5|2 email 9|3 first_name 9|4 last_name 9"]}}class po extends T{constructor(t){super(),this.candidates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(po,t,r)}static $(){return["GetOrganizationTeamAdminCandidatesResponse|1 candidates #0*",fo]}}class ho extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.organizationId="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.memberCount=0,this.publicId="",this.antCyberApproved=!1,this.visibility=H.UNSPECIFIED,this.anthropicEfsStatus=j.UNSPECIFIED,this.isIdpSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ho,t,r)}static $(){return["OrganizationGroup|1 id 3|2 name 9|3 organization_id 9|4 created_at 3|5 updated_at 3|6 member_count 5|7 public_id 9|8 monthly_spending_limit_dollars 5?|9 ant_cyber_approved 8|10 ant_cyber_verification_status #0?|11 visibility #1|12 anthropic_efs_status #2|13 is_idp_synced 8|14 slug 9?",z,H,j]}}class go extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(go,t,r)}static $(){return["GetOrganizationGroupsRequest|1 organization_id 9|2 page 5?|3 page_size 5?|4 search_term 9?"]}}class _o extends T{constructor(t){super(),this.groups=[],this.totalGroups=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_o,t,r)}static $(){return["GetOrganizationGroupsResponse|1 groups #0*|2 total_groups 5|3 total_pages 5",ho]}}class Jo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jo,t,r)}static $(){return["GetOrganizationGroupRequest|1 organization_id 9|3 group_public_id 9"]}}class wo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wo,t,r)}static $(){return["GetOrganizationGroupResponse|1 group #0",ho]}}class yo extends T{constructor(t){super(),this.userId=0,this.joinedAt=n.protoInt64.zero,this.isAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yo,t,r)}static $(){return["OrganizationGroupMember|1 user_id 5|2 email 9?|3 first_name 9?|4 last_name 9?|5 joined_at 3|6 is_admin 8|7 monthly_spending_limit_dollars 5?|8 monthly_usage_cents 5?"]}}class So extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new So).fromBinary(t,r)}static fromJson(t,r){return(new So).fromJson(t,r)}static fromJsonString(t,r){return(new So).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(So,t,r)}static $(){return["GetOrganizationGroupMembersRequest|1 organization_id 9|3 group_public_id 9|4 page 5?|5 page_size 5?|6 search_term 9?|7 sort_by 9?|8 sort_direction 9?"]}}class qo extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qo,t,r)}static $(){return["GetOrganizationGroupMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5",yo]}}class Bo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userId=0,this.clearMonthlySpendingLimitDollars=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bo,t,r)}static $(){return["UpdateOrganizationGroupMemberRequest|1 organization_id 9|2 group_id 3|3 user_id 5|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8"]}}class Io extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Io,t,r)}static $(){return["UpdateOrganizationGroupMemberResponse|1 member #0",yo]}}class Po extends T{constructor(t){super(),this.organizationId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Po,t,r)}static $(){return["CreateOrganizationGroupRequest|1 organization_id 9|2 name 9|3 scim_mapping #0?",bo]}}class bo extends T{constructor(t){super(),this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bo,t,r)}static $(){return["CreateOrganizationGroupScimMapping|1 scim_directory_id 3|2 scim_group_external_id 9"]}}class Ro extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ro,t,r)}static $(){return["CreateOrganizationGroupResponse|1 group #0|2 shadowing_reviewer_group_handle 9?",ho]}}class vo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.name="",this.clearMonthlySpendingLimitDollars=!1,this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vo,t,r)}static $(){return["UpdateOrganizationGroupRequest|1 organization_id 9|2 group_id 3|3 name 9|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8|6 visibility #0",H]}}class xo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xo,t,r)}static $(){return["UpdateOrganizationGroupResponse|1 group #0",ho]}}class ko extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ko,t,r)}static $(){return["DeleteOrganizationGroupRequest|1 organization_id 9|2 group_id 3"]}}class Eo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eo,t,r)}static $(){return["DeleteOrganizationGroupResponse"]}}class Co extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Co,t,r)}static $(){return["GetOrganizationGroupAutorunSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class To extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(To,t,r)}static $(){return["GetOrganizationGroupAutorunSettingsResponse|1 auto_run_controls #0|2 auto_review_run_mode_reset #1",j_,jw]}}class Uo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uo,t,r)}static $(){return["UpdateOrganizationGroupAutorunSettingsRequest|1 organization_id 9|2 group_id 3|3 auto_run_controls #0",j_]}}class Ao extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ao,t,r)}static $(){return["UpdateOrganizationGroupAutorunSettingsResponse"]}}class $o extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($o,t,r)}static $(){return["ResetOrganizationGroupAgentRunModeToAutoReviewRequest|1 organization_id 9|2 group_id 3"]}}class Mo extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mo,t,r)}static $(){return["ResetOrganizationGroupAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class Oo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oo,t,r)}static $(){return["GetOrganizationGroupModelAllowlistRequest|1 organization_id 9|2 group_public_id 9"]}}class Do extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Do,t,r)}static $(){return["GetOrganizationGroupModelAllowlistResponse|1 model_allowlist #0?",qw]}}class No extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(No,t,r)}static $(){return["UpdateOrganizationGroupModelAllowlistRequest|1 organization_id 9|2 group_id 3|3 model_allowlist #0?",qw]}}class Go extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Go,t,r)}static $(){return["UpdateOrganizationGroupModelAllowlistResponse"]}}class Lo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lo,t,r)}static $(){return["GetOrganizationGroupAutoReviewSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class Fo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fo,t,r)}static $(){return["GetOrganizationGroupAutoReviewSettingsResponse|1 auto_review #0",H_]}}class Ko extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ko,t,r)}static $(){return["UpdateOrganizationGroupAutoReviewSettingsRequest|1 organization_id 9|2 group_id 3|3 auto_review #0",H_]}}class zo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zo,t,r)}static $(){return["UpdateOrganizationGroupAutoReviewSettingsResponse"]}}class jo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jo,t,r)}static $(){return["GetOrganizationGroupSmartAutoSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class Ho extends T{constructor(t){super(),this.canEnable=!1,this.memberTeamConflicts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ho,t,r)}static $(){return["GetOrganizationGroupSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 new_chat_nudge_all_to_smart_auto 8?|4 member_team_conflicts #1*|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$,rM]}}class Wo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wo,t,r)}static $(){return["UpdateOrganizationGroupSmartAutoSettingsRequest|1 organization_id 9|2 group_id 3|3 settings #0|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class Qo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qo,t,r)}static $(){return["UpdateOrganizationGroupSmartAutoSettingsResponse"]}}class Vo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vo,t,r)}static $(){return["CreateOrganizationGroupAnthropicCyberEnrollmentUrlRequest|1 organization_id 9|2 group_id 3"]}}class Xo extends T{constructor(t){super(),this.enrollmentUrl="",this.userProfileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xo,t,r)}static $(){return["CreateOrganizationGroupAnthropicCyberEnrollmentUrlResponse|1 enrollment_url 9|2 user_profile_id 9"]}}class Yo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yo,t,r)}static $(){return["RequestOrganizationGroupAnthropicEfsRequest|1 organization_id 9|2 group_id 3"]}}class Zo extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zo,t,r)}static $(){return["RequestOrganizationGroupAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class ta extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ta,t,r)}static $(){return["RequestOrganizationAnthropicEfsRequest|1 organization_id 9"]}}class ra extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ra,t,r)}static $(){return["RequestOrganizationAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class ea extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ea,t,r)}static $(){return["GetOrganizationAnthropicEfsStatusRequest|1 organization_id 9"]}}class na extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,this.canRequestAnthropicEfs=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(na,t,r)}static $(){return["GetOrganizationAnthropicEfsStatusResponse|1 anthropic_efs_status #0|2 can_request_anthropic_efs 8",j]}}class sa extends T{constructor(t){super(),this.target={case:void 0},this.decision=W.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sa,t,r)}static $(){return["ReviewAnthropicEfsRequestInternalRequest|1 group_id 3 target|3 organization_id 3 target|2 decision #0",W]}}class ia extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ia,t,r)}static $(){return["ReviewAnthropicEfsRequestInternalResponse|1 anthropic_efs_status #0",j]}}class oa extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oa,t,r)}static $(){return["AddOrganizationGroupMembersRequest|1 organization_id 9|2 group_id 3|3 user_ids 5*"]}}class aa extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aa,t,r)}static $(){return["AddOrganizationGroupMembersResponse|1 added_count 5"]}}class ua extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ua,t,r)}static $(){return["RemoveOrganizationGroupMembersRequest|1 organization_id 9|2 group_id 3|3 user_ids 5*"]}}class ca extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ca,t,r)}static $(){return["RemoveOrganizationGroupMembersResponse|1 removed_count 5"]}}class la extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.joinedAt=n.protoInt64.zero,this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(la,t,r)}static $(){return["OrganizationGroupServiceAccountMember|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5?|5 owning_team_name 9?|6 joined_at 3|7 archived 8"]}}class ma extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ma,t,r)}static $(){return["GetOrganizationGroupServiceAccountMembersRequest|1 organization_id 9|2 group_public_id 9"]}}class fa extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fa).fromBinary(t,r)}static fromJson(t,r){return(new fa).fromJson(t,r)}static fromJsonString(t,r){return(new fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fa,t,r)}static $(){return["GetOrganizationGroupServiceAccountMembersResponse|1 service_accounts #0*",la]}}class da extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.owningTeamId=0,this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new da).fromBinary(t,r)}static fromJson(t,r){return(new da).fromJson(t,r)}static fromJsonString(t,r){return(new da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(da,t,r)}static $(){return["OrganizationServiceAccount|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5|5 owning_team_name 9?|6 created_at 3"]}}class pa extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pa).fromBinary(t,r)}static fromJson(t,r){return(new pa).fromJson(t,r)}static fromJsonString(t,r){return(new pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pa,t,r)}static $(){return["GetOrganizationServiceAccountsRequest|1 organization_id 9"]}}class ha extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ha).fromBinary(t,r)}static fromJson(t,r){return(new ha).fromJson(t,r)}static fromJsonString(t,r){return(new ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ha,t,r)}static $(){return["GetOrganizationServiceAccountsResponse|1 service_accounts #0*",da]}}class ga extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ga,t,r)}static $(){return["AddOrganizationGroupServiceAccountsRequest|1 organization_id 9|2 group_id 3|3 service_account_ids 9*"]}}class _a extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_a,t,r)}static $(){return["AddOrganizationGroupServiceAccountsResponse|1 added_count 5"]}}class Ja extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ja,t,r)}static $(){return["RemoveOrganizationGroupServiceAccountsRequest|1 organization_id 9|2 group_id 3|3 service_account_ids 9*"]}}class wa extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wa,t,r)}static $(){return["RemoveOrganizationGroupServiceAccountsResponse|1 removed_count 5"]}}class ya extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.teamId=0,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.memberCount=0,this.publicId="",this.antCyberApproved=!1,this.visibility=H.UNSPECIFIED,this.anthropicEfsStatus=j.UNSPECIFIED,this.isIdpSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ya,t,r)}static $(){return["TeamGroup|1 id 3|2 name 9|3 team_id 5|4 created_at 3|5 updated_at 3|6 member_count 5|7 public_id 9|8 monthly_spending_limit_dollars 5?|9 ant_cyber_approved 8|10 ant_cyber_verification_status #0?|11 visibility #1|12 grok_bot_enabled 8?|15 cloud_agent_enabled 8?|13 anthropic_efs_status #2|14 is_idp_synced 8|16 slug 9?|17 cursor_enabled 8?",z,H,j]}}class Sa extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sa).fromBinary(t,r)}static fromJson(t,r){return(new Sa).fromJson(t,r)}static fromJsonString(t,r){return(new Sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sa,t,r)}static $(){return["GetTeamGroupsRequest|1 team_id 5|2 page 5?|3 page_size 5?|4 search_term 9?"]}}class qa extends T{constructor(t){super(),this.groups=[],this.totalGroups=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qa).fromBinary(t,r)}static fromJson(t,r){return(new qa).fromJson(t,r)}static fromJsonString(t,r){return(new qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qa,t,r)}static $(){return["GetTeamGroupsResponse|1 groups #0*|2 total_groups 5|3 total_pages 5",ya]}}class Ba extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ba).fromBinary(t,r)}static fromJson(t,r){return(new Ba).fromJson(t,r)}static fromJsonString(t,r){return(new Ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ba,t,r)}static $(){return["GetTeamGroupRequest|1 team_id 5|2 group_public_id 9"]}}class Ia extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ia).fromBinary(t,r)}static fromJson(t,r){return(new Ia).fromJson(t,r)}static fromJsonString(t,r){return(new Ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ia,t,r)}static $(){return["GetTeamGroupResponse|1 group #0",ya]}}class Pa extends T{constructor(t){super(),this.userId=0,this.joinedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pa).fromBinary(t,r)}static fromJson(t,r){return(new Pa).fromJson(t,r)}static fromJsonString(t,r){return(new Pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pa,t,r)}static $(){return["TeamGroupMember|1 user_id 5|2 email 9?|3 first_name 9?|4 last_name 9?|5 joined_at 3|6 monthly_spending_limit_dollars 5?|7 spend_cents 5?|8 included_spend_cents 5?|9 overall_spend_cents 5?|10 fast_premium_requests 5?"]}}class ba extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ba).fromBinary(t,r)}static fromJson(t,r){return(new ba).fromJson(t,r)}static fromJsonString(t,r){return(new ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ba,t,r)}static $(){return["GetTeamGroupMembersRequest|1 team_id 5|2 group_public_id 9|3 page 5?|4 page_size 5?|5 search_term 9?|6 sort_by 9?|7 sort_direction 9?"]}}class Ra extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,this.isPooledPlan=!1,this.hasTokenBasedPricing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ra).fromBinary(t,r)}static fromJson(t,r){return(new Ra).fromJson(t,r)}static fromJsonString(t,r){return(new Ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ra,t,r)}static $(){return["GetTeamGroupMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5|4 is_pooled_plan 8|5 has_token_based_pricing 8",Pa]}}class va extends T{constructor(t){super(),this.teamId=0,this.name="",this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new va).fromBinary(t,r)}static fromJson(t,r){return(new va).fromJson(t,r)}static fromJsonString(t,r){return(new va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(va,t,r)}static $(){return["CreateTeamGroupRequest|1 team_id 5|2 name 9|3 scim_mapping #0?|4 visibility #1",bo,H]}}class xa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xa).fromBinary(t,r)}static fromJson(t,r){return(new xa).fromJson(t,r)}static fromJsonString(t,r){return(new xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xa,t,r)}static $(){return["CreateTeamGroupResponse|1 group #0|2 shadowing_reviewer_group_handle 9?",ya]}}class ka extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.name="",this.clearMonthlySpendingLimitDollars=!1,this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ka,t,r)}static $(){return["UpdateTeamGroupRequest|1 team_id 5|2 group_id 3|3 name 9|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8|6 visibility #0|7 grok_bot_enabled 8?|8 cloud_agent_enabled 8?|9 cursor_enabled 8?",H]}}class Ea extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ea,t,r)}static $(){return["UpdateTeamGroupResponse|1 group #0",ya]}}class Ca extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ca,t,r)}static $(){return["DeleteTeamGroupRequest|1 team_id 5|2 group_id 3"]}}class Ta extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ta,t,r)}static $(){return["DeleteTeamGroupResponse"]}}class Ua extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ua,t,r)}static $(){return["AddTeamGroupMembersRequest|1 team_id 5|2 group_id 3|3 user_ids 5*"]}}class Aa extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aa,t,r)}static $(){return["AddTeamGroupMembersResponse|1 added_count 5"]}}class $a extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($a,t,r)}static $(){return["RemoveTeamGroupMembersRequest|1 team_id 5|2 group_id 3|3 user_ids 5*"]}}class Ma extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ma).fromBinary(t,r)}static fromJson(t,r){return(new Ma).fromJson(t,r)}static fromJsonString(t,r){return(new Ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ma,t,r)}static $(){return["RemoveTeamGroupMembersResponse|1 removed_count 5"]}}class Oa extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userId=0,this.clearMonthlySpendingLimitDollars=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oa,t,r)}static $(){return["UpdateTeamGroupMemberRequest|1 team_id 5|2 group_id 3|3 user_id 5|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8"]}}class Da extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Da,t,r)}static $(){return["UpdateTeamGroupMemberResponse|1 member #0",Pa]}}class Na extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Na,t,r)}static $(){return["GetTeamGroupAutorunSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Ga extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ga,t,r)}static $(){return["GetTeamGroupAutorunSettingsResponse|1 auto_run_controls #0|2 auto_review_run_mode_reset #1",j_,jw]}}class La extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(La,t,r)}static $(){return["UpdateTeamGroupAutorunSettingsRequest|1 team_id 5|2 group_id 3|3 auto_run_controls #0",j_]}}class Fa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fa,t,r)}static $(){return["UpdateTeamGroupAutorunSettingsResponse"]}}class Ka extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ka,t,r)}static $(){return["ResetTeamGroupAgentRunModeToAutoReviewRequest|1 team_id 5|2 group_id 3"]}}class za extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(za,t,r)}static $(){return["ResetTeamGroupAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class ja extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ja,t,r)}static $(){return["GetTeamGroupModelAllowlistRequest|1 team_id 5|2 group_public_id 9"]}}class Ha extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ha,t,r)}static $(){return["GetTeamGroupModelAllowlistResponse|1 model_allowlist #0?",qw]}}class Wa extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wa).fromBinary(t,r)}static fromJson(t,r){return(new Wa).fromJson(t,r)}static fromJsonString(t,r){return(new Wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wa,t,r)}static $(){return["UpdateTeamGroupModelAllowlistRequest|1 team_id 5|2 group_id 3|3 model_allowlist #0?",qw]}}class Qa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qa).fromBinary(t,r)}static fromJson(t,r){return(new Qa).fromJson(t,r)}static fromJsonString(t,r){return(new Qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qa,t,r)}static $(){return["UpdateTeamGroupModelAllowlistResponse"]}}class Va extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Va).fromBinary(t,r)}static fromJson(t,r){return(new Va).fromJson(t,r)}static fromJsonString(t,r){return(new Va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Va,t,r)}static $(){return["GetTeamGroupAutoReviewSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Xa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xa).fromBinary(t,r)}static fromJson(t,r){return(new Xa).fromJson(t,r)}static fromJsonString(t,r){return(new Xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xa,t,r)}static $(){return["GetTeamGroupAutoReviewSettingsResponse|1 auto_review #0",H_]}}class Ya extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ya).fromBinary(t,r)}static fromJson(t,r){return(new Ya).fromJson(t,r)}static fromJsonString(t,r){return(new Ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ya,t,r)}static $(){return["UpdateTeamGroupAutoReviewSettingsRequest|1 team_id 5|2 group_id 3|3 auto_review #0",H_]}}class Za extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Za).fromBinary(t,r)}static fromJson(t,r){return(new Za).fromJson(t,r)}static fromJsonString(t,r){return(new Za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Za,t,r)}static $(){return["UpdateTeamGroupAutoReviewSettingsResponse"]}}class tu extends T{constructor(t){super(),this.applies=!1,this.viewerIsOrgAdmin=!1,this.organizationPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tu).fromBinary(t,r)}static fromJson(t,r){return(new tu).fromJson(t,r)}static fromJsonString(t,r){return(new tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tu,t,r)}static $(){return["TeamOrganizationNetworkBlocklist|1 applies 8|2 viewer_is_org_admin 8|3 organization_public_id 9|4 entry_counts #0|5 enforced_kinds #1",du,fu]}}class ru extends T{constructor(t){super(),this.enabled=!1,this.shadow=!1,this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ru).fromBinary(t,r)}static fromJson(t,r){return(new ru).fromJson(t,r)}static fromJsonString(t,r){return(new ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ru,t,r)}static $(){return["TeamIngressIpAllowlist|1 enabled 8|2 shadow 8|3 entries #0*",eu]}}class eu extends T{constructor(t){super(),this.cidr="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eu).fromBinary(t,r)}static fromJson(t,r){return(new eu).fromJson(t,r)}static fromJsonString(t,r){return(new eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eu,t,r)}static $(){return["TeamIngressIpAllowlistEntry|1 cidr 9|2 description 9"]}}class nu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nu).fromBinary(t,r)}static fromJson(t,r){return(new nu).fromJson(t,r)}static fromJsonString(t,r){return(new nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nu,t,r)}static $(){return["GetTeamIngressIpAllowlistRequest|1 team_id 5"]}}class su extends T{constructor(t){super(),this.available=!1,this.organizationInheritanceAvailable=!1,this.organizationPolicyApplied=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new su).fromBinary(t,r)}static fromJson(t,r){return(new su).fromJson(t,r)}static fromJsonString(t,r){return(new su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(su,t,r)}static $(){return["GetTeamIngressIpAllowlistResponse|1 available 8|2 allowlist #0|3 organization_inheritance_available 8|4 inherited_organization_allowlist #0|5 organization_policy_applied 8|6 inherited_organization_id 9?",ru]}}class iu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iu).fromBinary(t,r)}static fromJson(t,r){return(new iu).fromJson(t,r)}static fromJsonString(t,r){return(new iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iu,t,r)}static $(){return["UpdateTeamIngressIpAllowlistRequest|1 team_id 5|2 allowlist #0",ru]}}class ou extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ou).fromBinary(t,r)}static fromJson(t,r){return(new ou).fromJson(t,r)}static fromJsonString(t,r){return(new ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ou,t,r)}static $(){return["UpdateTeamIngressIpAllowlistResponse"]}}class au extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new au).fromBinary(t,r)}static fromJson(t,r){return(new au).fromJson(t,r)}static fromJsonString(t,r){return(new au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(au,t,r)}static $(){return["GetOrganizationIngressIpAllowlistRequest|1 organization_id 9"]}}class uu extends T{constructor(t){super(),this.available=!1,this.teamInheritanceAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uu).fromBinary(t,r)}static fromJson(t,r){return(new uu).fromJson(t,r)}static fromJsonString(t,r){return(new uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uu,t,r)}static $(){return["GetOrganizationIngressIpAllowlistResponse|1 available 8|2 allowlist #0|3 team_inheritance_available 8",ru]}}class cu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cu).fromBinary(t,r)}static fromJson(t,r){return(new cu).fromJson(t,r)}static fromJsonString(t,r){return(new cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cu,t,r)}static $(){return["UpdateOrganizationIngressIpAllowlistRequest|1 organization_id 9|2 allowlist #0",ru]}}class lu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lu).fromBinary(t,r)}static fromJson(t,r){return(new lu).fromJson(t,r)}static fromJsonString(t,r){return(new lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lu,t,r)}static $(){return["UpdateOrganizationIngressIpAllowlistResponse|1 allowlist #0",ru]}}class mu extends T{constructor(t){super(),this.version=0,this.sha256="",this.entryCount=0,this.rowCount=0,this.updatedAt="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mu).fromBinary(t,r)}static fromJson(t,r){return(new mu).fromJson(t,r)}static fromJsonString(t,r){return(new mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mu,t,r)}static $(){return["OrganizationNetworkBlocklistSummary|1 version 13|2 sha256 9|3 entry_count 13|4 row_count 13|5 updated_at 9|6 enabled 8|7 entry_counts #0|8 enforced_kinds #1|9 grok_bot_direct_entry_count 13?|10 grok_bot_site_rule_cap 13?",du,fu]}}class fu extends T{constructor(t){super(),this.site=!1,this.address=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fu).fromBinary(t,r)}static fromJson(t,r){return(new fu).fromJson(t,r)}static fromJsonString(t,r){return(new fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fu,t,r)}static $(){return["NetworkBlocklistEntryKinds|1 site 8|3 address 8"]}}class du extends T{constructor(t){super(),this.site=0,this.address=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new du).fromBinary(t,r)}static fromJson(t,r){return(new du).fromJson(t,r)}static fromJsonString(t,r){return(new du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(du,t,r)}static $(){return["NetworkBlocklistEntryCounts|1 site 13|3 address 13"]}}class pu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pu).fromBinary(t,r)}static fromJson(t,r){return(new pu).fromJson(t,r)}static fromJsonString(t,r){return(new pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pu,t,r)}static $(){return["GetOrganizationNetworkBlocklistRequest|1 organization_id 9"]}}class hu extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hu).fromBinary(t,r)}static fromJson(t,r){return(new hu).fromJson(t,r)}static fromJsonString(t,r){return(new hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hu,t,r)}static $(){return["GetOrganizationNetworkBlocklistResponse|1 available 8|2 summary #0",mu]}}class gu extends T{constructor(t){super(),this.organizationId="",this.sizeBytes=0,this.sha256=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gu,t,r)}static $(){return["CreateOrganizationNetworkBlocklistUploadRequest|1 organization_id 9|2 size_bytes 13|3 sha256 12"]}}class _u extends T{constructor(t){super(),this.uploadId="",this.putUrl="",this.putHeaders={},this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_u,t,r)}static $(){return["CreateOrganizationNetworkBlocklistUploadResponse|1 upload_id 9|2 put_url 9|3 put_headers 9,9|4 expires_at_ms 3"]}}class Ju extends T{constructor(t){super(),this.organizationId="",this.uploadId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ju,t,r)}static $(){return["CommitOrganizationNetworkBlocklistUploadRequest|1 organization_id 9|2 upload_id 9|3 expected_version 13?"]}}class wu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wu,t,r)}static $(){return["CommitOrganizationNetworkBlocklistUploadResponse|1 summary #0",mu]}}class yu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yu,t,r)}static $(){return["CreateOrganizationNetworkBlocklistExportRequest|1 organization_id 9"]}}class Su extends T{constructor(t){super(),this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Su,t,r)}static $(){return["CreateOrganizationNetworkBlocklistExportResponse|1 url 9|2 expires_at_ms 3|3 summary #0",mu]}}class qu extends T{constructor(t){super(),this.organizationId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qu).fromBinary(t,r)}static fromJson(t,r){return(new qu).fromJson(t,r)}static fromJsonString(t,r){return(new qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qu,t,r)}static $(){return["SetOrganizationNetworkBlocklistEnabledRequest|1 organization_id 9|2 enabled 8|3 expected_version 13?"]}}class Bu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bu,t,r)}static $(){return["SetOrganizationNetworkBlocklistEnabledResponse|1 summary #0",mu]}}class Iu extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iu,t,r)}static $(){return["GetTeamGroupSmartAutoSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Pu extends T{constructor(t){super(),this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pu,t,r)}static $(){return["GetTeamGroupSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 new_chat_nudge_all_to_smart_auto 8?|4 models_auto_only 8?|5 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class bu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bu,t,r)}static $(){return["UpdateTeamGroupSmartAutoSettingsRequest|1 team_id 5|2 group_id 3|3 settings #0|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class Ru extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ru,t,r)}static $(){return["UpdateTeamGroupSmartAutoSettingsResponse"]}}class vu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vu).fromBinary(t,r)}static fromJson(t,r){return(new vu).fromJson(t,r)}static fromJsonString(t,r){return(new vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vu,t,r)}static $(){return["CreateTeamGroupAnthropicCyberEnrollmentUrlRequest|1 team_id 5|2 group_id 3"]}}class xu extends T{constructor(t){super(),this.enrollmentUrl="",this.userProfileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xu).fromBinary(t,r)}static fromJson(t,r){return(new xu).fromJson(t,r)}static fromJsonString(t,r){return(new xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xu,t,r)}static $(){return["CreateTeamGroupAnthropicCyberEnrollmentUrlResponse|1 enrollment_url 9|2 user_profile_id 9"]}}class ku extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ku).fromBinary(t,r)}static fromJson(t,r){return(new ku).fromJson(t,r)}static fromJsonString(t,r){return(new ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ku,t,r)}static $(){return["RequestTeamGroupAnthropicEfsRequest|1 team_id 5|2 group_id 3"]}}class Eu extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eu,t,r)}static $(){return["RequestTeamGroupAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class Cu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cu,t,r)}static $(){return["GetTeamAnthropicEfsStatusRequest|1 team_id 5"]}}class Tu extends T{constructor(t){super(),this.organizationAnthropicEfsStatus=j.UNSPECIFIED,this.canRequestAnthropicEfs=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tu,t,r)}static $(){return["GetTeamAnthropicEfsStatusResponse|1 organization_anthropic_efs_status #0|2 can_request_anthropic_efs 8",j]}}class Uu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uu,t,r)}static $(){return["ListTeamGroupScimDirectoriesRequest|1 team_id 5"]}}class Au extends T{constructor(t){super(),this.directories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Au,t,r)}static $(){return["ListTeamGroupScimDirectoriesResponse|1 directories #0*",YE]}}class $u extends T{constructor(t){super(),this.teamId=0,this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($u,t,r)}static $(){return["ListTeamGroupScimGroupsFromUpstreamRequest|1 team_id 5|2 scim_directory_id 3"]}}class Mu extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mu,t,r)}static $(){return["ListTeamGroupScimGroupsFromUpstreamResponse|1 groups #0*",aC]}}class Ou extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ou,t,r)}static $(){return["ListTeamGroupScimTargetMappingsRequest|1 team_id 5|2 group_public_id 9"]}}class Du extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Du,t,r)}static $(){return["ListTeamGroupScimTargetMappingsResponse|1 mappings #0*",lC]}}class Nu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nu,t,r)}static $(){return["CreateTeamGroupScimTargetMappingRequest|1 team_id 5|2 group_id 3|3 scim_directory_id 3|4 scim_group_external_id 9"]}}class Gu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gu,t,r)}static $(){return["CreateTeamGroupScimTargetMappingResponse|1 mapping #0",lC]}}class Lu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.scimTargetMappingId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lu,t,r)}static $(){return["DeleteTeamGroupScimTargetMappingRequest|1 team_id 5|2 group_id 3|3 scim_target_mapping_id 3"]}}class Fu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fu,t,r)}static $(){return["DeleteTeamGroupScimTargetMappingResponse"]}}class Ku extends T{constructor(t){super(),this.teamId=0,this.privacyModeForced=!1,this.privacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ku,t,r)}static $(){return["SwitchTeamPrivacyModeRequest|1 team_id 5|2 privacy_mode_forced 8|3 privacy_mode #0",s.Y]}}class zu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zu,t,r)}static $(){return["SwitchTeamPrivacyModeResponse"]}}class ju extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ju,t,r)}static $(){return["GetTeamPrivacyModeForcedRequest|1 team_id 5"]}}class Hu extends T{constructor(t){super(),this.privacyModeForced=!1,this.privacyMode=s.Y.UNSPECIFIED,this.privacyModeMigrationOptedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hu,t,r)}static $(){return["GetTeamPrivacyModeForcedResponse|1 privacy_mode_forced 8|2 privacy_mode #0|3 privacy_mode_migration_opted_out 8",s.Y]}}class Wu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wu,t,r)}static $(){return["GetTeamXaiDataRetentionRequest|1 team_id 5"]}}class Qu extends T{constructor(t){super(),this.retention=Q.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qu,t,r)}static $(){return["GetTeamXaiDataRetentionResponse|1 retention #0",Q]}}class Vu extends T{constructor(t){super(),this.kind={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vu,t,r)}static $(){return["BackgroundComposerSecretOwner|1 user 8 kind|2 team 8 kind|3 environment_id 9 kind"]}}class Xu extends T{constructor(t){super(),this.appIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xu,t,r)}static $(){return["BackgroundComposerSecretAppScope|1 app_ids 9*"]}}class Yu extends T{constructor(t){super(),this.teamScope=!1,this.surface=Y.UNSPECIFIED,this.includeMemberSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yu,t,r)}static $(){return["ListBackgroundComposerSecretsRequest|1 team_scope 8|2 owner #0|3 surface #1|4 include_member_secrets 8",Vu,Y]}}class Zu extends T{constructor(t){super(),this.secrets=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zu,t,r)}static $(){return["ListBackgroundComposerSecretsResponse|1 secrets #0*|2 truncated 8",rc]}}class tc extends T{constructor(t){super(),this.appId=n.protoInt64.zero,this.slug="",this.apex="",this.live=!1,this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tc,t,r)}static $(){return["ListBackgroundComposerSecretsResponse.BoundApp|1 app_id 3|2 slug 9|3 apex 9|4 live 8|5 display_name 9"]}}class rc extends T{constructor(t){super(),this.name="",this.createdAt=0,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.id=0,this.surface=Y.UNSPECIFIED,this.boundApps=[],this.bindingCount=0,this.scopedToApps=[],this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rc,t,r)}static $(){return["ListBackgroundComposerSecretsResponse.Secret|1 name 9|2 created_at 1|3 scoped_to_repos 9*|4 level #0|5 id 5|6 owner #1|7 surface #2|8 owner_user_id 5?|9 owner_email 9?|10 owner_name 9?|11 bound_apps #3*|12 binding_count 5|13 scoped_to_apps 9*|14 http_scheme #4|15 http_host 9?|16 http_username_placeholder 9?|17 http_placeholder 9?|18 http_header_name 9?|19 http_value_prefix 9?",V,Vu,Y,tc,X]}}class ec extends T{constructor(t){super(),this.name="",this.value="",this.teamScope=!1,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.surface=Y.UNSPECIFIED,this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ec,t,r)}static $(){return["CreateBackgroundComposerSecretRequest|1 name 9|2 value 9|3 team_scope 8|4 scoped_to_repos 9*|5 level #0|6 owner #1|7 surface #2|8 http_scheme #3|9 http_host 9?|10 http_username 9?|11 http_header_name 9?|12 http_value_prefix 9?",V,Vu,Y,X]}}class nc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nc,t,r)}static $(){return["CreateBackgroundComposerSecretResponse"]}}class sc extends T{constructor(t){super(),this.secrets=[],this.teamScope=!1,this.scopedToRepos=[],this.surface=Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchRequest|1 secrets #0*|2 team_scope 8|3 scoped_to_repos 9*|4 owner #1|5 surface #2|6 app_scope #3",ic,Vu,Y,Xu]}}class ic extends T{constructor(t){super(),this.name="",this.value="",this.level=V.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ic,t,r)}static $(){return["CreateBackgroundComposerSecretBatchRequest.Secret|1 name 9|2 value 9|3 level #0",V]}}class oc extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchResponse|1 results #0*",cc]}}var ac=(0,a.QT)(n.proto3,C,"CreateBackgroundComposerSecretBatchResponse.Status",[[0,"UNSPECIFIED"],[1,"CREATED"],[2,"UPDATED"],[3,"ERROR"]],1),uc=(0,a.QT)(n.proto3,C,"CreateBackgroundComposerSecretBatchResponse.ErrorType",[[0,"UNSPECIFIED"],[1,"BAD_REQUEST"],[2,"UNAUTHORIZED"],[3,"INTERNAL"]],1);class cc extends T{constructor(t){super(),this.name="",this.status=ac.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchResponse.Result|1 name 9|2 status #0|3 error_message 9?|4 error_type #1?",ac,uc]}}class lc extends T{constructor(t){super(),this.name="",this.teamScope=!1,this.id=0,this.surface=Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lc,t,r)}static $(){return["RevokeBackgroundComposerSecretRequest|1 name 9|2 team_scope 8|3 id 5|4 owner #0|5 surface #1",Vu,Y]}}class mc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mc,t,r)}static $(){return["RevokeBackgroundComposerSecretResponse"]}}class fc extends T{constructor(t){super(),this.name="",this.teamScope=!1,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.id=0,this.surface=Y.UNSPECIFIED,this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fc,t,r)}static $(){return["UpdateBackgroundComposerSecretRequest|1 name 9|2 team_scope 8|3 scoped_to_repos 9*|4 level #0|5 value 9?|6 id 5|7 owner #1|8 surface #2|9 app_scope #3|10 http_scheme #4|11 http_host 9?|12 http_username 9?|13 http_header_name 9?|14 http_value_prefix 9?",V,Vu,Y,Xu,X]}}class dc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dc,t,r)}static $(){return["UpdateBackgroundComposerSecretResponse"]}}class pc extends T{constructor(t){super(),this.agentId="",this.sessionKind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pc,t,r)}static $(){return["GrokBotPluginScope|1 agent_id 9|2 session_kind 9"]}}class hc extends T{constructor(t){super(),this.serverIdentifier="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hc).fromBinary(t,r)}static fromJson(t,r){return(new hc).fromJson(t,r)}static fromJsonString(t,r){return(new hc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hc,t,r)}static $(){return["SetGrokConnectorEnabledRequest|1 server_identifier 9|2 enabled 8"]}}class gc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gc).fromBinary(t,r)}static fromJson(t,r){return(new gc).fromJson(t,r)}static fromJsonString(t,r){return(new gc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gc,t,r)}static $(){return["SetGrokConnectorEnabledResponse"]}}class _c extends T{constructor(t){super(),this.reason=rt.UNSPECIFIED,this.signedOutAtMs=n.protoInt64.zero,this.clientConfigured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _c).fromBinary(t,r)}static fromJson(t,r){return(new _c).fromJson(t,r)}static fromJsonString(t,r){return(new _c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_c,t,r)}static $(){return["McpSignOut|1 reason #0|2 signed_out_at_ms 3|3 client_configured 8",rt]}}class Jc extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jc).fromBinary(t,r)}static fromJson(t,r){return(new Jc).fromJson(t,r)}static fromJsonString(t,r){return(new Jc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jc,t,r)}static $(){return["GetTeamHasValidPaymentMethodRequest|1 team_id 5"]}}class wc extends T{constructor(t){super(),this.hasValidPaymentMethod=!1,this.trialDaysRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wc).fromBinary(t,r)}static fromJson(t,r){return(new wc).fromJson(t,r)}static fromJsonString(t,r){return(new wc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wc,t,r)}static $(){return["GetTeamHasValidPaymentMethodResponse|1 has_valid_payment_method 8|2 trial_days_remaining 5"]}}class yc extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yc).fromBinary(t,r)}static fromJson(t,r){return(new yc).fromJson(t,r)}static fromJsonString(t,r){return(new yc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yc,t,r)}static $(){return["CreateTeamWithFreeTrialRequest|1 name 9|2 privacy_mode_forced 8?|3 free_trial_code 9?"]}}class Sc extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sc).fromBinary(t,r)}static fromJson(t,r){return(new Sc).fromJson(t,r)}static fromJsonString(t,r){return(new Sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sc,t,r)}static $(){return["CreateTeamWithFreeTrialResponse|1 team_id 5"]}}class qc extends T{constructor(t){super(),this.name="",this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qc).fromBinary(t,r)}static fromJson(t,r){return(new qc).fromJson(t,r)}static fromJsonString(t,r){return(new qc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qc,t,r)}static $(){return["CreateTeamWithOrgRequest|1 name 9|2 invite_code 9|3 privacy_mode_forced 8?"]}}class Bc extends T{constructor(t){super(),this.teamId=0,this.orgId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bc).fromBinary(t,r)}static fromJson(t,r){return(new Bc).fromJson(t,r)}static fromJsonString(t,r){return(new Bc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bc,t,r)}static $(){return["CreateTeamWithOrgResponse|1 team_id 5|2 org_id 3"]}}class Ic extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ic).fromBinary(t,r)}static fromJson(t,r){return(new Ic).fromJson(t,r)}static fromJsonString(t,r){return(new Ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ic,t,r)}static $(){return["GetPricingHistoryRequest"]}}class Pc extends T{constructor(t){super(),this.pricingHistory=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pc).fromBinary(t,r)}static fromJson(t,r){return(new Pc).fromJson(t,r)}static fromJsonString(t,r){return(new Pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pc,t,r)}static $(){return["GetPricingHistoryResponse|1 pricing_history #0*",bc]}}class bc extends T{constructor(t){super(),this.description="",this.id="",this.changelog="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bc).fromBinary(t,r)}static fromJson(t,r){return(new bc).fromJson(t,r)}static fromJsonString(t,r){return(new bc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bc,t,r)}static $(){return["GetPricingHistoryResponse.PricingDescription|1 description 9|2 id 9|3 changelog 9|4 created_at 3"]}}class Rc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rc).fromBinary(t,r)}static fromJson(t,r){return(new Rc).fromJson(t,r)}static fromJsonString(t,r){return(new Rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rc,t,r)}static $(){return["ListInvoiceCyclesRequest|1 team_id 5?"]}}class vc extends T{constructor(t){super(),this.startMs=n.protoInt64.zero,this.type=et.UNSPECIFIED,this.endMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vc).fromBinary(t,r)}static fromJson(t,r){return(new vc).fromJson(t,r)}static fromJsonString(t,r){return(new vc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vc,t,r)}static $(){return["InvoiceCycle|1 start_ms 3|2 type #0|3 end_ms 3",et]}}class xc extends T{constructor(t){super(),this.cycles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xc).fromBinary(t,r)}static fromJson(t,r){return(new xc).fromJson(t,r)}static fromJsonString(t,r){return(new xc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xc,t,r)}static $(){return["ListInvoiceCyclesResponse|1 cycles #0*",vc]}}class kc extends T{constructor(t){super(),this.month=0,this.year=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kc).fromBinary(t,r)}static fromJson(t,r){return(new kc).fromJson(t,r)}static fromJsonString(t,r){return(new kc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kc,t,r)}static $(){return["GetMonthlyInvoiceRequest|1 team_id 5?|2 month 5|3 year 5|4 include_usage_events 8?|5 cycle_filter_type #0?|6 start_time_ms 3?|7 use_current_cycle 8?",et]}}class Ec extends T{constructor(t){super(),this.items=[],this.usageEvents=[],this.isUsageEventsMaybeCutoff=!1,this.hasUnpaidMidMonthInvoice=!1,this.lastHardLimitCents=0,this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ec).fromBinary(t,r)}static fromJson(t,r){return(new Ec).fromJson(t,r)}static fromJsonString(t,r){return(new Ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ec,t,r)}static $(){return["GetMonthlyInvoiceResponse|1 items #0*|2 pricing_description #1|3 usage_events #2*|4 is_usage_events_maybe_cutoff 8|5 has_unpaid_mid_month_invoice 8|6 last_hard_limit_cents 5|7 period_start_ms 3|8 period_end_ms 3|9 not_applicable #3?",Cc,Tc,i.aq,Uc]}}class Cc extends T{constructor(t){super(),this.description="",this.cents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cc).fromBinary(t,r)}static fromJson(t,r){return(new Cc).fromJson(t,r)}static fromJsonString(t,r){return(new Cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cc,t,r)}static $(){return["GetMonthlyInvoiceResponse.InvoiceItem|1 description 9|2 cents 5"]}}class Tc extends T{constructor(t){super(),this.description="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tc).fromBinary(t,r)}static fromJson(t,r){return(new Tc).fromJson(t,r)}static fromJsonString(t,r){return(new Tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tc,t,r)}static $(){return["GetMonthlyInvoiceResponse.PricingDescription|1 description 9|2 id 9"]}}class Uc extends T{constructor(t){super(),this.reason=Ac.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uc).fromBinary(t,r)}static fromJson(t,r){return(new Uc).fromJson(t,r)}static fromJsonString(t,r){return(new Uc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uc,t,r)}static $(){return["GetMonthlyInvoiceResponse.NotApplicable|1 reason #0",Ac]}}var Ac=(0,a.QT)(n.proto3,C,"GetMonthlyInvoiceResponse.NotApplicable.Reason",[[0,"UNSPECIFIED"],[1,"BILLED_BY_XAI"]],1);class $c extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $c).fromBinary(t,r)}static fromJson(t,r){return(new $c).fromJson(t,r)}static fromJsonString(t,r){return(new $c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($c,t,r)}static $(){return["GetHardLimitRequest|1 team_id 5?|2 personal_scope 8?"]}}class Mc extends T{constructor(t){super(),this.hardLimit=0,this.noUsageBasedAllowed=!1,this.perUserMonthlyLimitDollars=0,this.isDynamicTeamLimit=!1,this.hasPendingSetupOnboardingCreditClaim=!1,this.isSetupPromoActive=!1,this.onDemandSpendDisabledByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mc).fromBinary(t,r)}static fromJson(t,r){return(new Mc).fromJson(t,r)}static fromJsonString(t,r){return(new Mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mc,t,r)}static $(){return["GetHardLimitResponse|1 hard_limit 5|2 no_usage_based_allowed 8|3 hard_limit_per_user 5?|4 per_user_monthly_limit_dollars 5|5 is_dynamic_team_limit 8|6 has_pending_setup_onboarding_credit_claim 8|7 is_setup_promo_active 8|8 setup_promo_amount_cents 5?|9 setup_promo_credit_validity_days 5?|10 on_demand_spend_disabled_by_organization 8|11 per_user_first_party_models_additional_budget_dollars 5?|12 per_user_first_party_models_additional_budget_unlimited 8?"]}}class Oc extends T{constructor(t){super(),this.hardLimit=0,this.noUsageBasedAllowed=!1,this.preserveHardLimitPerUser=!1,this.perUserMonthlyLimitDollars=0,this.clearPerUserMonthlyLimitDollars=!1,this.isDynamicTeamLimit=!1,this.clearConflictingPolicy=!1,this.clearPerUserFirstPartyModelsAdditionalBudgetDollars=!1,this.clearPerUserFirstPartyModelsAdditionalBudgetUnlimited=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oc).fromBinary(t,r)}static fromJson(t,r){return(new Oc).fromJson(t,r)}static fromJsonString(t,r){return(new Oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oc,t,r)}static $(){return["SetHardLimitRequest|1 team_id 5?|2 hard_limit 5|3 no_usage_based_allowed 8|4 hard_limit_per_user 5?|5 preserve_hard_limit_per_user 8|6 per_user_monthly_limit_dollars 5|7 clear_per_user_monthly_limit_dollars 8|8 is_dynamic_team_limit 8|9 clear_conflicting_policy 8|10 auto_alerts_enabled 8?|11 per_user_first_party_models_additional_budget_dollars 5?|12 clear_per_user_first_party_models_additional_budget_dollars 8|13 per_user_first_party_models_additional_budget_unlimited 8?|14 clear_per_user_first_party_models_additional_budget_unlimited 8|15 personal_scope 8?"]}}class Dc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dc).fromBinary(t,r)}static fromJson(t,r){return(new Dc).fromJson(t,r)}static fromJsonString(t,r){return(new Dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dc,t,r)}static $(){return["SetHardLimitResponse"]}}class Nc extends T{constructor(t){super(),this.notifyAdminUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nc).fromBinary(t,r)}static fromJson(t,r){return(new Nc).fromJson(t,r)}static fromJsonString(t,r){return(new Nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nc,t,r)}static $(){return["LinkedUsageAlertPolicy|1 alert_id 9?|2 threshold_bps 5?|3 notification_mode 9?|4 notify_all_admins 8?|5 notify_admin_user_ids 5*|6 notify_member 8?"]}}class Gc extends T{constructor(t){super(),this.scope=nt.UNSPECIFIED,this.type=st.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gc).fromBinary(t,r)}static fromJson(t,r){return(new Gc).fromJson(t,r)}static fromJsonString(t,r){return(new Gc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gc,t,r)}static $(){return["SpendLimitPolicy|1 scope #0|2 type #1|3 amount_dollars 5?|4 is_dynamic_team_limit 8?|5 resource_threshold_id 9?|6 linked_alert #2?|7 auto_alerts_enabled 8?",nt,st,Nc]}}class Lc extends T{constructor(t){super(),this.teamId=0,this.scope=nt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lc).fromBinary(t,r)}static fromJson(t,r){return(new Lc).fromJson(t,r)}static fromJsonString(t,r){return(new Lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lc,t,r)}static $(){return["GetSpendLimitPolicyRequest|1 team_id 5|2 scope #0|3 group_id 3?",nt]}}class Fc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fc).fromBinary(t,r)}static fromJson(t,r){return(new Fc).fromJson(t,r)}static fromJsonString(t,r){return(new Fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fc,t,r)}static $(){return["GetSpendLimitPolicyResponse|1 policy #0",Gc]}}class Kc extends T{constructor(t){super(),this.teamId=0,this.scope=nt.UNSPECIFIED,this.type=st.UNSPECIFIED,this.notifyAdminUserIds=[],this.clearConflictingPolicy=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kc).fromBinary(t,r)}static fromJson(t,r){return(new Kc).fromJson(t,r)}static fromJsonString(t,r){return(new Kc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kc,t,r)}static $(){return["SetSpendLimitPolicyRequest|1 team_id 5|2 scope #0|3 type #1|4 amount_dollars 5?|5 is_dynamic_team_limit 8?|6 alert_enabled 8?|7 alert_threshold_bps 5?|8 notification_mode 9?|9 notify_all_admins 8?|10 notify_admin_user_ids 5*|11 notify_member 8?|12 clear_conflicting_policy 8|13 auto_alerts_enabled 8?|14 group_id 3?",nt,st]}}class zc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zc).fromBinary(t,r)}static fromJson(t,r){return(new zc).fromJson(t,r)}static fromJsonString(t,r){return(new zc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zc,t,r)}static $(){return["SetSpendLimitPolicyResponse|1 policy #0",Gc]}}class jc extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jc).fromBinary(t,r)}static fromJson(t,r){return(new jc).fromJson(t,r)}static fromJsonString(t,r){return(new jc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jc,t,r)}static $(){return["GetOrgTeamBudgetsRequest|1 organization_id 9"]}}class Hc extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.currentSpendCents=0,this.teamSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hc).fromBinary(t,r)}static fromJson(t,r){return(new Hc).fromJson(t,r)}static fromJsonString(t,r){return(new Hc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hc,t,r)}static $(){return["OrgTeamBudget|1 team_id 5|2 team_name 9|3 limit_dollars 5?|4 current_spend_cents 5|5 team_slug 9|6 team_icon_url 9?"]}}class Wc extends T{constructor(t){super(),this.budgets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wc).fromBinary(t,r)}static fromJson(t,r){return(new Wc).fromJson(t,r)}static fromJsonString(t,r){return(new Wc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wc,t,r)}static $(){return["GetOrgTeamBudgetsResponse|1 budgets #0*",Hc]}}class Qc extends T{constructor(t){super(),this.organizationId="",this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qc).fromBinary(t,r)}static fromJson(t,r){return(new Qc).fromJson(t,r)}static fromJsonString(t,r){return(new Qc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qc,t,r)}static $(){return["SetOrgTeamBudgetRequest|1 organization_id 9|2 team_id 5|3 limit_dollars 5?"]}}class Vc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vc).fromBinary(t,r)}static fromJson(t,r){return(new Vc).fromJson(t,r)}static fromJsonString(t,r){return(new Vc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vc,t,r)}static $(){return["SetOrgTeamBudgetResponse"]}}class Xc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xc).fromBinary(t,r)}static fromJson(t,r){return(new Xc).fromJson(t,r)}static fromJsonString(t,r){return(new Xc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xc,t,r)}static $(){return["EnableOnDemandSpendRequest|1 team_id 5?"]}}class Yc extends T{constructor(t){super(),this.hardLimit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yc).fromBinary(t,r)}static fromJson(t,r){return(new Yc).fromJson(t,r)}static fromJsonString(t,r){return(new Yc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yc,t,r)}static $(){return["EnableOnDemandSpendResponse|1 hard_limit 5|2 hard_limit_per_user 5?"]}}class Zc extends T{constructor(t){super(),this.name="",this.id=0,this.role=it.UNSPECIFIED,this.seats=0,this.hasBilling=!1,this.requestQuotaPerSeat=0,this.privacyModeForced=!1,this.allowSso=!1,this.adminOnlyUsagePricing=!1,this.subscriptionStatus="",this.bedrockIamRole="",this.verified=!1,this.isEnterprise=!1,this.privacyModeMigrationOptedOut=!1,this.bedrockExternalId="",this.membershipType="",this.dataSharingDiscountEligible=!1,this.dashboardAnalyticsRequiresAdmin=!1,this.individualSpendLimitsBlocked=!1,this.allowDomainJoin=!1,this.domainJoinDomains=[],this.ssoEnabled=!1,this.scimRequireUserDirectory=!1,this.selfServeTieredPricingEnabled=!1,this.newMemberUsagePromoEligible=!1,this.grantedPermissions=[],this.isDirectMember=!1,this.teamSlug="",this.privateInferenceEnablement=ct.UNSPECIFIED,this.privateInferenceModeSwitchAllowed=!1,this.privateInferenceAvailable=!1,this.bedrockAssumerRoleArn="",this.privateInferenceBugReportsAllowed=!1,this.billingSource=ut.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zc).fromBinary(t,r)}static fromJson(t,r){return(new Zc).fromJson(t,r)}static fromJsonString(t,r){return(new Zc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zc,t,r)}static $(){return["Team|1 name 9|2 id 5|3 role #0|4 seats 5|5 has_billing 8|6 request_quota_per_seat 5|7 privacy_mode_forced 8|8 allow_sso 8|9 admin_only_usage_pricing 8|10 subscription_status 9|11 bedrock_iam_role 9|12 verified 8|13 is_enterprise 8|14 privacy_mode_migration_opted_out 8|15 bedrock_external_id 9|16 membership_type 9|17 purchased_seats 5?|18 billing_cycle_start 3?|19 billing_cycle_end 3?|20 pricing_strategy 9?|21 total_committed_dollars 5?|22 data_sharing_discount_eligible 8|23 dashboard_analytics_requires_admin 8|24 individual_spend_limits_blocked 8|25 allow_domain_join 8|26 domain_join_domains 9*|27 sso_enabled 8|28 customer_balance_cents 3?|29 scim_require_user_directory 8|30 self_serve_tiered_pricing_enabled 8|31 new_member_usage_promo_eligible 8|34 deleted_at_ms 3?|35 granted_permissions 9*|36 is_direct_member 8|37 team_slug 9|38 private_inference_enablement #1|39 default_member_billing_tier #2?|40 private_inference_mode_switch_allowed 8|41 private_inference_available 8|42 bedrock_assumer_role_arn 9|46 private_inference_bug_reports_allowed 8|43 icon_url 9?|44 merged_team_has_members 8?|45 billing_source #3|47 is_viewer_default_team 8?|48 can_be_viewer_default_team 8?|49 member_role #0?|50 viewer_has_teammate 8?|51 organization_network_blocklist_bound 8?",it,ct,ot,ut]}}class tl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tl).fromBinary(t,r)}static fromJson(t,r){return(new tl).fromJson(t,r)}static fromJsonString(t,r){return(new tl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tl,t,r)}static $(){return["GetTeamsRequest|1 active_only 8?"]}}class rl extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rl).fromBinary(t,r)}static fromJson(t,r){return(new rl).fromJson(t,r)}static fromJsonString(t,r){return(new rl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rl,t,r)}static $(){return["GetTeamsResponse|1 teams #0*",Zc]}}class el extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new el).fromBinary(t,r)}static fromJson(t,r){return(new el).fromJson(t,r)}static fromJsonString(t,r){return(new el).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(el,t,r)}static $(){return["ScimRequireUserDirectoryImpactedUser|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?"]}}class nl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nl).fromBinary(t,r)}static fromJson(t,r){return(new nl).fromJson(t,r)}static fromJsonString(t,r){return(new nl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nl,t,r)}static $(){return["GetTeamScimRequireUserDirectoryPreviewRequest|1 team_id 5"]}}class sl extends T{constructor(t){super(),this.impactedUserCount=0,this.impactedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sl).fromBinary(t,r)}static fromJson(t,r){return(new sl).fromJson(t,r)}static fromJsonString(t,r){return(new sl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sl,t,r)}static $(){return["GetTeamScimRequireUserDirectoryPreviewResponse|1 impacted_user_count 5|2 impacted_users #0*",el]}}class il extends T{constructor(t){super(),this.teamId=0,this.seats=0,this.yearly=!1,this.requestQuotaPerSeat=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new il).fromBinary(t,r)}static fromJson(t,r){return(new il).fromJson(t,r)}static fromJsonString(t,r){return(new il).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(il,t,r)}static $(){return["GetActivationCheckoutUrlRequest|1 team_id 5|2 seats 5|3 yearly 8|4 request_quota_per_seat 5|5 code 9?|6 radar_session_id 9?|7 include_bugbot 8?|8 billing_tier #0?",ot]}}class ol extends T{constructor(t){super(),this.checkoutUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ol).fromBinary(t,r)}static fromJson(t,r){return(new ol).fromJson(t,r)}static fromJsonString(t,r){return(new ol).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ol,t,r)}static $(){return["GetActivationCheckoutUrlResponse|1 checkout_url 9"]}}class al extends T{constructor(t){super(),this.promoTypeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new al).fromBinary(t,r)}static fromJson(t,r){return(new al).fromJson(t,r)}static fromJsonString(t,r){return(new al).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(al,t,r)}static $(){return["CheckPromotionEligibilityRequest|1 promo_type_id 9"]}}class ul extends T{constructor(t){super(),this.canActivate=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ul).fromBinary(t,r)}static fromJson(t,r){return(new ul).fromJson(t,r)}static fromJsonString(t,r){return(new ul).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ul,t,r)}static $(){return["CheckPromotionEligibilityResponse|1 can_activate 8|2 activation_status #0?",cl]}}class cl extends T{constructor(t){super(),this.isActivated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cl).fromBinary(t,r)}static fromJson(t,r){return(new cl).fromJson(t,r)}static fromJsonString(t,r){return(new cl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cl,t,r)}static $(){return["ActivationStatus|1 is_activated 8|2 activated_at 3?"]}}class ll extends T{constructor(t){super(),this.promoTypeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ll).fromBinary(t,r)}static fromJson(t,r){return(new ll).fromJson(t,r)}static fromJsonString(t,r){return(new ll).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ll,t,r)}static $(){return["ActivatePromotionRequest|1 promo_type_id 9"]}}class ml extends T{constructor(t){super(),this.type=fl.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ml).fromBinary(t,r)}static fromJson(t,r){return(new ml).fromJson(t,r)}static fromJsonString(t,r){return(new ml).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ml,t,r)}static $(){return["ActivatePromotionResponse|1 type #0|2 checkout_url 9?|3 success 8?",fl]}}var fl=(0,a.QT)(n.proto3,C,"ActivatePromotionResponse.ActivationType",[[0,"UNSPECIFIED"],[1,"CHECKOUT"],[2,"SUBSCRIPTION"]],1);class dl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dl).fromBinary(t,r)}static fromJson(t,r){return(new dl).fromJson(t,r)}static fromJsonString(t,r){return(new dl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dl,t,r)}static $(){return["GetTeamCustomerPortalUrlRequest|1 team_id 5"]}}class pl extends T{constructor(t){super(),this.portalUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pl).fromBinary(t,r)}static fromJson(t,r){return(new pl).fromJson(t,r)}static fromJsonString(t,r){return(new pl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pl,t,r)}static $(){return["GetTeamCustomerPortalUrlResponse|1 portal_url 9"]}}class hl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hl).fromBinary(t,r)}static fromJson(t,r){return(new hl).fromJson(t,r)}static fromJsonString(t,r){return(new hl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hl,t,r)}static $(){return["CancelPendingTeamSubscriptionNowRequest|1 team_id 5"]}}class gl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gl).fromBinary(t,r)}static fromJson(t,r){return(new gl).fromJson(t,r)}static fromJsonString(t,r){return(new gl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gl,t,r)}static $(){return["CancelPendingTeamSubscriptionNowResponse"]}}class _l extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _l).fromBinary(t,r)}static fromJson(t,r){return(new _l).fromJson(t,r)}static fromJsonString(t,r){return(new _l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_l,t,r)}static $(){return["CreatePendingTeamProCheckoutRequest|1 team_id 5"]}}class Jl extends T{constructor(t){super(),this.checkoutUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jl).fromBinary(t,r)}static fromJson(t,r){return(new Jl).fromJson(t,r)}static fromJsonString(t,r){return(new Jl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jl,t,r)}static $(){return["CreatePendingTeamProCheckoutResponse|1 checkout_url 9"]}}class wl extends T{constructor(t){super(),this.enabled=!1,this.thresholdCents=n.protoInt64.zero,this.topUpAmountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wl).fromBinary(t,r)}static fromJson(t,r){return(new wl).fromJson(t,r)}static fromJsonString(t,r){return(new wl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wl,t,r)}static $(){return["PrepaidAutoTopUpRule|1 enabled 8|2 threshold_cents 3|3 top_up_amount_cents 3|4 monthly_cap_cents 3?"]}}class yl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.origin="",this.amountCents=n.protoInt64.zero,this.status="",this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yl).fromBinary(t,r)}static fromJson(t,r){return(new yl).fromJson(t,r)}static fromJsonString(t,r){return(new yl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yl,t,r)}static $(){return["PrepaidTopUpEntry|1 ticket 3|2 origin 9|3 amount_cents 3|4 status 9|5 failure_code 9?|6 created_at_ms 3|7 succeeded_at_ms 3?|8 invoice_url 9?|9 invoice_pdf_url 9?"]}}class Sl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sl).fromBinary(t,r)}static fromJson(t,r){return(new Sl).fromJson(t,r)}static fromJsonString(t,r){return(new Sl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sl,t,r)}static $(){return["GetTeamPrepaidBillingRequest|1 team_id 5|2 limit 5?|3 skip_balance_cache 8?|4 skip_card_check 8?"]}}class ql extends T{constructor(t){super(),this.billingMode=lt.UNSPECIFIED,this.eligible=!1,this.availableCents=n.protoInt64.zero,this.fundedCents=n.protoInt64.zero,this.spentCents=n.protoInt64.zero,this.topUps=[],this.hasPaymentMethod=!1,this.pendingTopUps=0,this.autoTopUpChargedThisMonthCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ql).fromBinary(t,r)}static fromJson(t,r){return(new ql).fromJson(t,r)}static fromJsonString(t,r){return(new ql).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ql,t,r)}static $(){return["GetTeamPrepaidBillingResponse|1 billing_mode #0|2 eligible 8|3 available_cents 3|4 funded_cents 3|5 spent_cents 3|6 auto_top_up #1?|7 top_ups #2*|8 has_payment_method 8|9 pending_top_ups 5|10 auto_top_up_charged_this_month_cents 3|11 spent_this_month_cents 3?",lt,wl,yl]}}class Bl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bl).fromBinary(t,r)}static fromJson(t,r){return(new Bl).fromJson(t,r)}static fromJsonString(t,r){return(new Bl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bl,t,r)}static $(){return["SetTeamPrepaidAutoTopUpRequest|1 team_id 5|2 rule #0?",wl]}}class Il extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Il).fromBinary(t,r)}static fromJson(t,r){return(new Il).fromJson(t,r)}static fromJsonString(t,r){return(new Il).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Il,t,r)}static $(){return["SetTeamPrepaidAutoTopUpResponse|1 rule #0?",wl]}}class Pl extends T{constructor(t){super(),this.teamId=0,this.amountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pl).fromBinary(t,r)}static fromJson(t,r){return(new Pl).fromJson(t,r)}static fromJsonString(t,r){return(new Pl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pl,t,r)}static $(){return["CreatePrepaidTopUpRequest|1 team_id 5|2 amount_cents 3|3 payment_method_id 9?"]}}class bl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bl).fromBinary(t,r)}static fromJson(t,r){return(new bl).fromJson(t,r)}static fromJsonString(t,r){return(new bl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bl,t,r)}static $(){return["CreatePrepaidTopUpResponse|1 ticket 3|2 status 9|3 invoice_url 9?|4 failure_code 9?"]}}class Rl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rl).fromBinary(t,r)}static fromJson(t,r){return(new Rl).fromJson(t,r)}static fromJsonString(t,r){return(new Rl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rl,t,r)}static $(){return["GetUserPrepaidBillingRequest|1 limit 5?|2 xai_team_id 9?|3 skip_balance_cache 8?|4 skip_card_check 8?"]}}class vl extends T{constructor(t){super(),this.billingMode=lt.UNSPECIFIED,this.eligible=!1,this.availableCents=n.protoInt64.zero,this.fundedCents=n.protoInt64.zero,this.spentCents=n.protoInt64.zero,this.topUps=[],this.hasPaymentMethod=!1,this.pendingTopUps=0,this.autoTopUpChargedThisMonthCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vl).fromBinary(t,r)}static fromJson(t,r){return(new vl).fromJson(t,r)}static fromJsonString(t,r){return(new vl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vl,t,r)}static $(){return["GetUserPrepaidBillingResponse|1 billing_mode #0|2 eligible 8|3 available_cents 3|4 funded_cents 3|5 spent_cents 3|6 auto_top_up #1?|7 top_ups #2*|8 has_payment_method 8|9 pending_top_ups 5|10 auto_top_up_charged_this_month_cents 3|11 spent_this_month_cents 3?",lt,wl,yl]}}class xl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xl).fromBinary(t,r)}static fromJson(t,r){return(new xl).fromJson(t,r)}static fromJsonString(t,r){return(new xl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xl,t,r)}static $(){return["SetUserPrepaidAutoTopUpRequest|1 rule #0?|2 xai_team_id 9?|3 entrypoint 9?",wl]}}class kl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kl).fromBinary(t,r)}static fromJson(t,r){return(new kl).fromJson(t,r)}static fromJsonString(t,r){return(new kl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kl,t,r)}static $(){return["SetUserPrepaidAutoTopUpResponse|1 rule #0?",wl]}}class El extends T{constructor(t){super(),this.amountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new El).fromBinary(t,r)}static fromJson(t,r){return(new El).fromJson(t,r)}static fromJsonString(t,r){return(new El).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(El,t,r)}static $(){return["CreateUserPrepaidTopUpRequest|1 amount_cents 3|2 payment_method_id 9?"]}}class Cl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cl).fromBinary(t,r)}static fromJson(t,r){return(new Cl).fromJson(t,r)}static fromJsonString(t,r){return(new Cl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cl,t,r)}static $(){return["CreateUserPrepaidTopUpResponse|1 ticket 3|2 status 9|3 invoice_url 9?|4 failure_code 9?"]}}class Tl extends T{constructor(t){super(),this.purpose=mt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tl).fromBinary(t,r)}static fromJson(t,r){return(new Tl).fromJson(t,r)}static fromJsonString(t,r){return(new Tl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tl,t,r)}static $(){return["GetXaiCommerceBearerTokenRequest|1 purpose #0",mt]}}class Ul extends T{constructor(t){super(),this.token="",this.edgeBaseUrl="",this.tokenSource=ft.UNSPECIFIED,this.expiresInSeconds=0,this.assetServerBaseUrl="",this.country="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ul).fromBinary(t,r)}static fromJson(t,r){return(new Ul).fromJson(t,r)}static fromJsonString(t,r){return(new Ul).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ul,t,r)}static $(){return["XaiCommerceBearerCredential|1 token 9|2 edge_base_url 9|3 token_source #0|4 expires_in_seconds 13|5 asset_server_base_url 9|6 country 9",ft]}}class Al extends T{constructor(t){super(),this.reason=dt.UNSPECIFIED,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Al).fromBinary(t,r)}static fromJson(t,r){return(new Al).fromJson(t,r)}static fromJsonString(t,r){return(new Al).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Al,t,r)}static $(){return["XaiCommerceBearerRefusal|1 reason #0|2 message 9",dt]}}class $l extends T{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $l).fromBinary(t,r)}static fromJson(t,r){return(new $l).fromJson(t,r)}static fromJsonString(t,r){return(new $l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($l,t,r)}static $(){return["GetXaiCommerceBearerTokenResponse|1 credential #0 result|2 refusal #1 result",Ul,Al]}}class Ml extends T{constructor(t){super(),this.slackTeamId="",this.slackUserId="",this.nonce="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ml).fromBinary(t,r)}static fromJson(t,r){return(new Ml).fromJson(t,r)}static fromJsonString(t,r){return(new Ml).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ml,t,r)}static $(){return["SetSlackAuthRequest|1 slack_team_id 9|2 slack_user_id 9|3 nonce 9|4 setup_complete 8?|5 cursor_team_id 5?"]}}class Ol extends T{constructor(t){super(),this.linkedWorkspaceName="",this.otherLinkedWorkspaces=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ol).fromBinary(t,r)}static fromJson(t,r){return(new Ol).fromJson(t,r)}static fromJsonString(t,r){return(new Ol).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ol,t,r)}static $(){return["SetSlackAuthResponse|1 linked_workspace_name 9|2 other_linked_workspaces 5"]}}class Dl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dl).fromBinary(t,r)}static fromJson(t,r){return(new Dl).fromJson(t,r)}static fromJsonString(t,r){return(new Dl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dl,t,r)}static $(){return["GetSlackTeamSettingsRequest|1 team_id 5"]}}class Nl extends T{constructor(t){super(),this.slackChannel="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nl).fromBinary(t,r)}static fromJson(t,r){return(new Nl).fromJson(t,r)}static fromJsonString(t,r){return(new Nl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nl,t,r)}static $(){return["SlackChannelRepoMapping|1 slack_channel 9|2 repo 9"]}}class Gl extends T{constructor(t){super(),this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.shareSummary=!1,this.shareSummaryInExternalChannel=!1,this.channelRepoMappings=[],this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gl).fromBinary(t,r)}static fromJson(t,r){return(new Gl).fromJson(t,r)}static fromJsonString(t,r){return(new Gl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gl,t,r)}static $(){return["GetSlackTeamSettingsResponse|1 default_repo 9|2 default_branch 9|3 default_model 9|4 share_summary 8|5 share_summary_in_external_channel 8|6 channel_repo_mappings #0*|7 auto_draft_enabled 8?|8 use_github_app_for_auto_draft_prs 8?|9 branch_prefix 9|10 default_model_selection #1?|12 default_environment_public_id 9?",Nl,o.M6]}}class Ll extends T{constructor(t){super(),this.teamId=0,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.shareSummary=!1,this.shareSummaryInExternalChannel=!1,this.channelRepoMappings=[],this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ll).fromBinary(t,r)}static fromJson(t,r){return(new Ll).fromJson(t,r)}static fromJsonString(t,r){return(new Ll).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ll,t,r)}static $(){return["UpdateSlackTeamSettingsRequest|1 team_id 5|2 default_repo 9|3 default_branch 9|4 default_model 9|5 share_summary 8|6 share_summary_in_external_channel 8|7 channel_repo_mappings #0*|8 use_github_app_for_auto_draft_prs 8?|9 branch_prefix 9|10 default_model_selection #1?|12 default_environment_public_id 9?",Nl,o.M6]}}class Fl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fl).fromBinary(t,r)}static fromJson(t,r){return(new Fl).fromJson(t,r)}static fromJsonString(t,r){return(new Fl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fl,t,r)}static $(){return["UpdateSlackTeamSettingsResponse"]}}class Kl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kl).fromBinary(t,r)}static fromJson(t,r){return(new Kl).fromJson(t,r)}static fromJsonString(t,r){return(new Kl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kl,t,r)}static $(){return["GetSlackSettingsRequest"]}}class zl extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zl).fromBinary(t,r)}static fromJson(t,r){return(new zl).fromJson(t,r)}static fromJsonString(t,r){return(new zl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zl,t,r)}static $(){return["GetSlackSettingsResponse|1 available 8"]}}class jl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jl).fromBinary(t,r)}static fromJson(t,r){return(new jl).fromJson(t,r)}static fromJsonString(t,r){return(new jl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jl,t,r)}static $(){return["GetSlackInstallUrlRequest|1 team_id 5|2 repo_url 9?|3 source #0?|4 attempt_id 9?|5 grok_bot_callback_url 9?|6 site #1?|7 reconnect_slack_team_id 9?",pt,ht]}}class Hl extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hl).fromBinary(t,r)}static fromJson(t,r){return(new Hl).fromJson(t,r)}static fromJsonString(t,r){return(new Hl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hl,t,r)}static $(){return["GetSlackInstallUrlResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Wl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wl).fromBinary(t,r)}static fromJson(t,r){return(new Wl).fromJson(t,r)}static fromJsonString(t,r){return(new Wl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wl,t,r)}static $(){return["GetPublicSlackInstallUrlRequest|1 source #0?|2 attempt_id 9?",pt]}}class Ql extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ql).fromBinary(t,r)}static fromJson(t,r){return(new Ql).fromJson(t,r)}static fromJsonString(t,r){return(new Ql).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ql,t,r)}static $(){return["GetPublicSlackInstallUrlResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Vl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vl).fromBinary(t,r)}static fromJson(t,r){return(new Vl).fromJson(t,r)}static fromJsonString(t,r){return(new Vl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vl,t,r)}static $(){return["GetPublicSlackInstallUrlWithUserScopesRequest|1 source #0?|2 attempt_id 9?",pt]}}class Xl extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xl).fromBinary(t,r)}static fromJson(t,r){return(new Xl).fromJson(t,r)}static fromJsonString(t,r){return(new Xl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xl,t,r)}static $(){return["GetPublicSlackInstallUrlWithUserScopesResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Yl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yl).fromBinary(t,r)}static fromJson(t,r){return(new Yl).fromJson(t,r)}static fromJsonString(t,r){return(new Yl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yl,t,r)}static $(){return["GetSlackModelOptionsRequest"]}}class Zl extends T{constructor(t){super(),this.modelOptions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zl).fromBinary(t,r)}static fromJson(t,r){return(new Zl).fromJson(t,r)}static fromJsonString(t,r){return(new Zl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zl,t,r)}static $(){return["GetSlackModelOptionsResponse|1 model_options 9*"]}}class tm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tm).fromBinary(t,r)}static fromJson(t,r){return(new tm).fromJson(t,r)}static fromJsonString(t,r){return(new tm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tm,t,r)}static $(){return["GetTeamMembersRequest|1 team_id 5|2 include_org_admins 8?"]}}class rm extends T{constructor(t){super(),this.name="",this.email="",this.id=0,this.role=it.UNSPECIFIED,this.isRemoved=!1,this.billingTier=ot.UNSPECIFIED,this.pendingBillingTier=ot.UNSPECIFIED,this.roleIsManaged=!1,this.isOrgAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rm).fromBinary(t,r)}static fromJson(t,r){return(new rm).fromJson(t,r)}static fromJsonString(t,r){return(new rm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rm,t,r)}static $(){return["TeamMember|1 name 9|4 email 9|2 id 5|3 role #0|5 is_removed 8|6 billing_tier #1|7 pending_billing_tier #1|8 role_is_managed 8|10 is_org_admin 8|11 merged_seat_tier #2?|12 profile_picture_url 9?",it,ot,at]}}class em extends T{constructor(t){super(),this.name="",this.id=0,this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new em).fromBinary(t,r)}static fromJson(t,r){return(new em).fromJson(t,r)}static fromJsonString(t,r){return(new em).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(em,t,r)}static $(){return["TeamOrgAdmin|1 name 9|2 id 5|3 email 9"]}}class nm extends T{constructor(t){super(),this.state=gt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nm).fromBinary(t,r)}static fromJson(t,r){return(new nm).fromJson(t,r)}static fromJsonString(t,r){return(new nm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nm,t,r)}static $(){return["TeamEnterpriseGrantCapacity|1 state #0|2 quantity 5?|3 assigned 5?|4 unassigned 5?",gt]}}class sm extends T{constructor(t){super(),this.teamMembers=[],this.userId=0,this.isScimSynced=!1,this.orgAdmins=[],this.mergedSeatRail=!1,this.teamLinkedToOrganization=!1,this.inviteSeatTierEnabled=!1,this.inviteFreeSeatRefused=!1,this.xaiTeamMembershipHolds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sm).fromBinary(t,r)}static fromJson(t,r){return(new sm).fromJson(t,r)}static fromJsonString(t,r){return(new sm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sm,t,r)}static $(){return["GetTeamMembersResponse|1 team_members #0*|2 user_id 5|3 is_scim_synced 8|4 org_admins #1*|5 merged_seat_rail 8|6 team_linked_to_organization 8|7 invite_seat_tier_enabled 8|8 former_personal_owner_user_id 5?|9 invite_free_seat_refused 8|10 xai_team_membership_holds #2*|11 enterprise_grant_capacity #3?",rm,em,uo,nm]}}class im extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new im).fromBinary(t,r)}static fromJson(t,r){return(new im).fromJson(t,r)}static fromJsonString(t,r){return(new im).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(im,t,r)}static $(){return["GetTeamInviteLinkRequest|1 team_id 5|3 create_if_missing 8?|4 billing_tier #0?|5 role #1?|6 merged_seat_tier #2?|7 attribution_source 9?|8 attribution_surface 9?|9 castle_request_token 9?",ot,it,at]}}class om extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new om).fromBinary(t,r)}static fromJson(t,r){return(new om).fromJson(t,r)}static fromJsonString(t,r){return(new om).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(om,t,r)}static $(){return["GetTeamInviteLinkResponse|1 invite_link 9?"]}}class am extends T{constructor(t){super(),this.teamId=0,this.email="",this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new am).fromBinary(t,r)}static fromJson(t,r){return(new am).fromJson(t,r)}static fromJsonString(t,r){return(new am).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(am,t,r)}static $(){return["SendTeamInviteRequest|1 team_id 5|2 email 9|3 role #0|4 message 9?|5 billing_tier #1?|7 onboarding 9?|8 merged_seat_tier #2?|9 attribution_source 9?|10 attribution_surface 9?|11 castle_request_token 9?",it,ot,at]}}class um extends T{constructor(t){super(),this.validUntil=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new um).fromBinary(t,r)}static fromJson(t,r){return(new um).fromJson(t,r)}static fromJsonString(t,r){return(new um).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(um,t,r)}static $(){return["SendTeamInviteResponse|1 valid_until 3"]}}class cm extends T{constructor(t){super(),this.teamId=0,this.emails=[],this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cm).fromBinary(t,r)}static fromJson(t,r){return(new cm).fromJson(t,r)}static fromJsonString(t,r){return(new cm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cm,t,r)}static $(){return["SendTeamInvitesRequest|1 team_id 5|2 emails 9*|3 role #0|4 message 9?|5 billing_tier #1?|6 onboarding 9?|7 merged_seat_tier #2?|8 attribution_source 9?|9 attribution_surface 9?|10 castle_request_token 9?",it,ot,at]}}class lm extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lm).fromBinary(t,r)}static fromJson(t,r){return(new lm).fromJson(t,r)}static fromJsonString(t,r){return(new lm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lm,t,r)}static $(){return["SendTeamInvitesResponse|1 results #0*",mm]}}class mm extends T{constructor(t){super(),this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mm).fromBinary(t,r)}static fromJson(t,r){return(new mm).fromJson(t,r)}static fromJsonString(t,r){return(new mm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mm,t,r)}static $(){return["SendTeamInviteResult|1 email 9|2 valid_until 3?|3 error 9?"]}}class fm extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,this.provider=_t.UNSPECIFIED,this.providerAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fm).fromBinary(t,r)}static fromJson(t,r){return(new fm).fromJson(t,r)}static fromJsonString(t,r){return(new fm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fm,t,r)}static $(){return["ContactImportConnectionSummary|1 connection_id 3|2 provider #0|3 provider_account_id 9|4 provider_workspace_id 9?|5 provider_account_email 9?|6 last_synced_at_ms 3?|7 latest_sync_status #1?|8 latest_sync_total_contacts 5?|9 latest_sync_completed_at_ms 3?",_t,Jt]}}class dm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dm).fromBinary(t,r)}static fromJson(t,r){return(new dm).fromJson(t,r)}static fromJsonString(t,r){return(new dm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dm,t,r)}static $(){return["ListContactImportConnectionsRequest"]}}class pm extends T{constructor(t){super(),this.connections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pm).fromBinary(t,r)}static fromJson(t,r){return(new pm).fromJson(t,r)}static fromJsonString(t,r){return(new pm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pm,t,r)}static $(){return["ListContactImportConnectionsResponse|1 connections #0*",fm]}}class hm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hm).fromBinary(t,r)}static fromJson(t,r){return(new hm).fromJson(t,r)}static fromJsonString(t,r){return(new hm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hm,t,r)}static $(){return["GetGoogleContactImportAuthUrlRequest"]}}class gm extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gm).fromBinary(t,r)}static fromJson(t,r){return(new gm).fromJson(t,r)}static fromJsonString(t,r){return(new gm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gm,t,r)}static $(){return["GetGoogleContactImportAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class _m extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _m).fromBinary(t,r)}static fromJson(t,r){return(new _m).fromJson(t,r)}static fromJsonString(t,r){return(new _m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_m,t,r)}static $(){return["ConnectGoogleContactImportCallbackRequest|1 code 9|2 state 9"]}}class Jm extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,this.syncRunId=n.protoInt64.zero,this.totalContacts=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jm).fromBinary(t,r)}static fromJson(t,r){return(new Jm).fromJson(t,r)}static fromJsonString(t,r){return(new Jm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jm,t,r)}static $(){return["ConnectGoogleContactImportCallbackResponse|1 connection_id 3|2 sync_run_id 3|3 total_contacts 5"]}}class wm extends T{constructor(t){super(),this.contactId=n.protoInt64.zero,this.providerContactId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wm).fromBinary(t,r)}static fromJson(t,r){return(new wm).fromJson(t,r)}static fromJsonString(t,r){return(new wm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wm,t,r)}static $(){return["ContactImportContactRow|1 contact_id 3|2 provider_contact_id 9|3 display_name 9?|4 given_name 9?|5 family_name 9?|6 primary_email 9?|7 normalized_email 9?|8 photo_url 9?"]}}class ym extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ym).fromBinary(t,r)}static fromJson(t,r){return(new ym).fromJson(t,r)}static fromJsonString(t,r){return(new ym).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ym,t,r)}static $(){return["ListContactImportContactsRequest|1 connection_id 3|2 limit 5?|3 normalized_email_query 9?|4 after_contact_id 3?"]}}class Sm extends T{constructor(t){super(),this.contacts=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sm).fromBinary(t,r)}static fromJson(t,r){return(new Sm).fromJson(t,r)}static fromJsonString(t,r){return(new Sm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sm,t,r)}static $(){return["ListContactImportContactsResponse|1 contacts #0*|2 total_count 5",wm]}}class qm extends T{constructor(t){super(),this.contactId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qm).fromBinary(t,r)}static fromJson(t,r){return(new qm).fromJson(t,r)}static fromJsonString(t,r){return(new qm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qm,t,r)}static $(){return["GetContactImportAvatarRequest|1 contact_id 3"]}}class Bm extends T{constructor(t){super(),this.bytes=new Uint8Array(0),this.contentType="",this.etag="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bm).fromBinary(t,r)}static fromJson(t,r){return(new Bm).fromJson(t,r)}static fromJsonString(t,r){return(new Bm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bm,t,r)}static $(){return["GetContactImportAvatarResponse|1 bytes 12|2 content_type 9|3 etag 9"]}}class Im extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Im).fromBinary(t,r)}static fromJson(t,r){return(new Im).fromJson(t,r)}static fromJsonString(t,r){return(new Im).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Im,t,r)}static $(){return["DisconnectContactImportConnectionRequest|1 connection_id 3"]}}class Pm extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pm).fromBinary(t,r)}static fromJson(t,r){return(new Pm).fromJson(t,r)}static fromJsonString(t,r){return(new Pm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pm,t,r)}static $(){return["DisconnectContactImportConnectionResponse|1 success 8"]}}class bm extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bm).fromBinary(t,r)}static fromJson(t,r){return(new bm).fromJson(t,r)}static fromJsonString(t,r){return(new bm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bm,t,r)}static $(){return["AcceptInviteRequest|1 invite_code 9|2 castle_request_token 9?|3 invite_ref 9?|4 project_invite 9?"]}}class Rm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rm).fromBinary(t,r)}static fromJson(t,r){return(new Rm).fromJson(t,r)}static fromJsonString(t,r){return(new Rm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rm,t,r)}static $(){return["AcceptInviteResponse|1 team_id 5|2 project_bc_id 9?|3 join_request_pending 8?"]}}class vm extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vm).fromBinary(t,r)}static fromJson(t,r){return(new vm).fromJson(t,r)}static fromJsonString(t,r){return(new vm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vm,t,r)}static $(){return["GetTeamInviteMetadataRequest|1 invite_code 9"]}}class xm extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.inviterName="",this.inviterEmail="",this.inviteeEmailMatchesAuthenticatedUser=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xm).fromBinary(t,r)}static fromJson(t,r){return(new xm).fromJson(t,r)}static fromJsonString(t,r){return(new xm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xm,t,r)}static $(){return["GetTeamInviteMetadataResponse|1 team_id 5|2 team_name 9|3 inviter_name 9|4 inviter_email 9|5 invitee_email_matches_authenticated_user 8|6 invite_has_bound_recipient 8?|7 join_requires_approval 8?|8 join_request_pending 8?"]}}class km extends T{constructor(t){super(),this.teamId=0,this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new km).fromBinary(t,r)}static fromJson(t,r){return(new km).fromJson(t,r)}static fromJsonString(t,r){return(new km).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(km,t,r)}static $(){return["CreateTeamApiKeyRequest|1 team_id 5|2 name 9|3 scopes 9*|4 expires_at 3?|5 castle_request_token 9?"]}}class Em extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Em).fromBinary(t,r)}static fromJson(t,r){return(new Em).fromJson(t,r)}static fromJsonString(t,r){return(new Em).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Em,t,r)}static $(){return["CreateTeamApiKeyResponse|1 api_key 9"]}}class Cm extends T{constructor(t){super(),this.automationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cm).fromBinary(t,r)}static fromJson(t,r){return(new Cm).fromJson(t,r)}static fromJsonString(t,r){return(new Cm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cm,t,r)}static $(){return["CreateAutomationWebhookApiKeyRequest|1 automation_id 9|2 name 9?"]}}class Tm extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tm).fromBinary(t,r)}static fromJson(t,r){return(new Tm).fromJson(t,r)}static fromJsonString(t,r){return(new Tm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tm,t,r)}static $(){return["CreateAutomationWebhookApiKeyResponse|1 api_key 9"]}}class Um extends T{constructor(t){super(),this.teamId=0,this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Um).fromBinary(t,r)}static fromJson(t,r){return(new Um).fromJson(t,r)}static fromJsonString(t,r){return(new Um).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Um,t,r)}static $(){return["RevokeTeamApiKeyRequest|1 team_id 5|2 id 5"]}}class Am extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Am).fromBinary(t,r)}static fromJson(t,r){return(new Am).fromJson(t,r)}static fromJsonString(t,r){return(new Am).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Am,t,r)}static $(){return["RevokeTeamApiKeyResponse"]}}class $m extends T{constructor(t){super(),this.id=0,this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $m).fromBinary(t,r)}static fromJson(t,r){return(new $m).fromJson(t,r)}static fromJsonString(t,r){return(new $m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($m,t,r)}static $(){return["ApiKey|1 id 5|2 masked_key 9|3 name 9|4 created_at 3|5 service_account_name 9?|6 scopes 9*|7 expires_at 3?|8 creator #0|9 last_use #1",Jp,yp]}}class Mm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mm).fromBinary(t,r)}static fromJson(t,r){return(new Mm).fromJson(t,r)}static fromJsonString(t,r){return(new Mm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mm,t,r)}static $(){return["ListTeamApiKeysRequest|1 team_id 5"]}}class Om extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Om).fromBinary(t,r)}static fromJson(t,r){return(new Om).fromJson(t,r)}static fromJsonString(t,r){return(new Om).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Om,t,r)}static $(){return["ListTeamApiKeysResponse|1 api_keys #0*",$m]}}class Dm extends T{constructor(t){super(),this.apiKeyId="",this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.disabled=!1,this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dm).fromBinary(t,r)}static fromJson(t,r){return(new Dm).fromJson(t,r)}static fromJsonString(t,r){return(new Dm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dm,t,r)}static $(){return["GrokApiKey|1 api_key_id 9|2 masked_key 9|3 name 9|4 created_at 3|5 expires_at 3?|6 disabled 8|7 acls 9*|8 requests_per_minute 5?|9 requests_per_second 5?|10 tokens_per_minute 3?|11 owner #0|12 modified_at 3?",Nm]}}class Nm extends T{constructor(t){super(),this.name="",this.email="",this.isViewer=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nm).fromBinary(t,r)}static fromJson(t,r){return(new Nm).fromJson(t,r)}static fromJsonString(t,r){return(new Nm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nm,t,r)}static $(){return["GrokKeyOwner|1 name 9|2 email 9|3 is_viewer 8"]}}class Gm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gm).fromBinary(t,r)}static fromJson(t,r){return(new Gm).fromJson(t,r)}static fromJsonString(t,r){return(new Gm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gm,t,r)}static $(){return["GetPersonalGrokApiKeyTeamRequest"]}}class Lm extends T{constructor(t){super(),this.teamId=0,this.paymentMethodRequired=!1,this.addCreditsAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lm).fromBinary(t,r)}static fromJson(t,r){return(new Lm).fromJson(t,r)}static fromJsonString(t,r){return(new Lm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lm,t,r)}static $(){return["GetPersonalGrokApiKeyTeamResponse|1 team_id 5|2 payment_method_required 8|3 add_credits_available 8"]}}class Fm extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fm).fromBinary(t,r)}static fromJson(t,r){return(new Fm).fromJson(t,r)}static fromJsonString(t,r){return(new Fm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fm,t,r)}static $(){return["ListGrokApiKeysRequest|1 team_id 5|2 page_size 5?|3 page_token 9"]}}class Km extends T{constructor(t){super(),this.apiKeys=[],this.propagationReadsEnabled=!1,this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Km).fromBinary(t,r)}static fromJson(t,r){return(new Km).fromJson(t,r)}static fromJsonString(t,r){return(new Km).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Km,t,r)}static $(){return["ListGrokApiKeysResponse|1 api_keys #0*|2 team_linked 8?|3 user_linked 8?|4 propagation_reads_enabled 8|5 next_page_token 9",Dm]}}class zm extends T{constructor(t){super(),this.teamId=0,this.name="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zm).fromBinary(t,r)}static fromJson(t,r){return(new zm).fromJson(t,r)}static fromJsonString(t,r){return(new zm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zm,t,r)}static $(){return["CreateGrokApiKeyRequest|1 team_id 5|2 name 9|3 expires_at 3?|4 acls 9*|5 requests_per_minute 5?|6 requests_per_second 5?|7 tokens_per_minute 3?"]}}class jm extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jm).fromBinary(t,r)}static fromJson(t,r){return(new jm).fromJson(t,r)}static fromJsonString(t,r){return(new jm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jm,t,r)}static $(){return["CreateGrokApiKeyResponse|1 api_key 9|2 api_key_id 9|3 requests_per_minute 5?|4 requests_per_second 5?|5 tokens_per_minute 3?"]}}class Hm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hm).fromBinary(t,r)}static fromJson(t,r){return(new Hm).fromJson(t,r)}static fromJsonString(t,r){return(new Hm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hm,t,r)}static $(){return["DeleteGrokApiKeyRequest|1 team_id 5|2 api_key_id 9"]}}class Wm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wm).fromBinary(t,r)}static fromJson(t,r){return(new Wm).fromJson(t,r)}static fromJsonString(t,r){return(new Wm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wm,t,r)}static $(){return["DeleteGrokApiKeyResponse"]}}class Qm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.name="",this.updateFields=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qm).fromBinary(t,r)}static fromJson(t,r){return(new Qm).fromJson(t,r)}static fromJsonString(t,r){return(new Qm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qm,t,r)}static $(){return["UpdateGrokApiKeyRequest|1 team_id 5|2 api_key_id 9|3 name 9|4 update_fields 9*|5 requests_per_minute 5?|6 requests_per_second 5?|7 tokens_per_minute 3?|8 expires_at 3?|9 disabled 8?"]}}class Vm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vm).fromBinary(t,r)}static fromJson(t,r){return(new Vm).fromJson(t,r)}static fromJsonString(t,r){return(new Vm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vm,t,r)}static $(){return["UpdateGrokApiKeyResponse"]}}class Xm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xm).fromBinary(t,r)}static fromJson(t,r){return(new Xm).fromJson(t,r)}static fromJsonString(t,r){return(new Xm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xm,t,r)}static $(){return["SetGrokApiKeyAclsRequest|1 team_id 5|2 api_key_id 9|3 acls 9*"]}}class Ym extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ym).fromBinary(t,r)}static fromJson(t,r){return(new Ym).fromJson(t,r)}static fromJsonString(t,r){return(new Ym).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ym,t,r)}static $(){return["SetGrokApiKeyAclsResponse"]}}class Zm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zm).fromBinary(t,r)}static fromJson(t,r){return(new Zm).fromJson(t,r)}static fromJsonString(t,r){return(new Zm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zm,t,r)}static $(){return["RotateGrokApiKeyRequest|1 team_id 5|2 api_key_id 9|3 old_secret_grace_seconds 5?"]}}class tf extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tf).fromBinary(t,r)}static fromJson(t,r){return(new tf).fromJson(t,r)}static fromJsonString(t,r){return(new tf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tf,t,r)}static $(){return["RotateGrokApiKeyResponse|1 api_key 9|2 api_key_id 9"]}}class rf extends T{constructor(t){super(),this.outcome=wt.UNSPECIFIED,this.reason="",this.cursorOnlyEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rf).fromBinary(t,r)}static fromJson(t,r){return(new rf).fromJson(t,r)}static fromJsonString(t,r){return(new rf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rf,t,r)}static $(){return["GrokAdminCallStatus|1 outcome #0|2 reason 9|3 cursor_only_enterprise 8",wt]}}class ef extends T{constructor(t){super(),this.enableFileUploads=!1,this.enableImageUploads=!1,this.enableWebSearch=!1,this.enableXSearch=!1,this.enableVoiceMode=!1,this.enableImagine=!1,this.enableImagineChat=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ef).fromBinary(t,r)}static fromJson(t,r){return(new ef).fromJson(t,r)}static fromJsonString(t,r){return(new ef).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ef,t,r)}static $(){return["GrokAdminFeatureControls|1 enable_file_uploads 8|2 enable_image_uploads 8|3 enable_web_search 8|4 enable_x_search 8|5 enable_voice_mode 8|6 enable_imagine 8|7 enable_imagine_chat 8|8 enable_grok_chat 8?|9 enable_dictation 8?|10 enable_bots 8?"]}}class nf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nf).fromBinary(t,r)}static fromJson(t,r){return(new nf).fromJson(t,r)}static fromJsonString(t,r){return(new nf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nf,t,r)}static $(){return["GetGrokAdminFeatureControlsRequest|1 team_id 5"]}}class sf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sf).fromBinary(t,r)}static fromJson(t,r){return(new sf).fromJson(t,r)}static fromJsonString(t,r){return(new sf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sf,t,r)}static $(){return["GetGrokAdminFeatureControlsResponse|1 status #0|2 controls #1",rf,ef]}}class of extends T{constructor(t){super(),this.teamId=0,this.field=yt.UNSPECIFIED,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new of).fromBinary(t,r)}static fromJson(t,r){return(new of).fromJson(t,r)}static fromJsonString(t,r){return(new of).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(of,t,r)}static $(){return["UpdateGrokAdminFeatureControlsRequest|1 team_id 5|2 field #0|3 enabled 8",yt]}}class af extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new af).fromBinary(t,r)}static fromJson(t,r){return(new af).fromJson(t,r)}static fromJsonString(t,r){return(new af).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(af,t,r)}static $(){return["UpdateGrokAdminFeatureControlsResponse|1 status #0|2 controls #1",rf,ef]}}class uf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uf).fromBinary(t,r)}static fromJson(t,r){return(new uf).fromJson(t,r)}static fromJsonString(t,r){return(new uf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uf,t,r)}static $(){return["GetGrokUserDataControlsRequest"]}}class cf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cf).fromBinary(t,r)}static fromJson(t,r){return(new cf).fromJson(t,r)}static fromJsonString(t,r){return(new cf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cf,t,r)}static $(){return["UpdateGrokUserDataControlsRequest|1 exclude_from_training 8?|2 enable_memory 8?"]}}class lf extends T{constructor(t){super(),this.status=St.UNSPECIFIED,this.excludeFromTrainingLocked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lf).fromBinary(t,r)}static fromJson(t,r){return(new lf).fromJson(t,r)}static fromJsonString(t,r){return(new lf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lf,t,r)}static $(){return["GetGrokUserDataControlsResponse|1 status #0|2 exclude_from_training 8?|3 enable_memory 8?|4 exclude_from_training_locked 8",St]}}class mf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mf).fromBinary(t,r)}static fromJson(t,r){return(new mf).fromJson(t,r)}static fromJsonString(t,r){return(new mf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mf,t,r)}static $(){return["UpdateGrokUserDataControlsResponse|1 exclude_from_training 8?|2 enable_memory 8?"]}}class ff extends T{constructor(t){super(),this.apiKeyIds=[],this.requestIds=[],this.modelNames=[],this.kinds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ff).fromBinary(t,r)}static fromJson(t,r){return(new ff).fromJson(t,r)}static fromJsonString(t,r){return(new ff).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ff,t,r)}static $(){return["GrokRequestLogFilter|1 api_key_ids 9*|2 time_from_ms 3?|3 time_to_ms 3?|4 request_ids 9*|5 model_names 9*|6 kinds #0*",qt]}}class df extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,this.cursor="",this.timeAscending=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new df).fromBinary(t,r)}static fromJson(t,r){return(new df).fromJson(t,r)}static fromJsonString(t,r){return(new df).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(df,t,r)}static $(){return["ListGrokRequestLogsRequest|1 team_id 5|2 filter #0|3 page_size 5|4 cursor 9|5 time_ascending 8",ff]}}class pf extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.entries=[],this.nextCursor="",this.totalCount=n.protoInt64.zero,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pf).fromBinary(t,r)}static fromJson(t,r){return(new pf).fromJson(t,r)}static fromJsonString(t,r){return(new pf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pf,t,r)}static $(){return["ListGrokRequestLogsResponse|1 team_linked 8|2 user_linked 8|3 entries #0*|4 next_cursor 9|5 total_count 3|6 zero_data_retention 8",hf]}}class hf extends T{constructor(t){super(),this.requestId="",this.apiKeyId="",this.timestampMs=n.protoInt64.zero,this.modelName="",this.kind=qt.UNSPECIFIED,this.bodyLogged=!1,this.conversationId="",this.previousResponseId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hf).fromBinary(t,r)}static fromJson(t,r){return(new hf).fromJson(t,r)}static fromJsonString(t,r){return(new hf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hf,t,r)}static $(){return["GrokRequestLog|1 request_id 9|2 api_key_id 9|3 timestamp_ms 3|4 model_name 9|5 kind #0|6 body_logged 8|7 conversation_id 9|8 previous_response_id 9",qt]}}class gf extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gf).fromBinary(t,r)}static fromJson(t,r){return(new gf).fromJson(t,r)}static fromJsonString(t,r){return(new gf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gf,t,r)}static $(){return["ListGrokRequestLogBodiesRequest|1 team_id 5|2 filter #0|3 page_size 5",ff]}}class _f extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _f).fromBinary(t,r)}static fromJson(t,r){return(new _f).fromJson(t,r)}static fromJsonString(t,r){return(new _f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_f,t,r)}static $(){return["ListGrokRequestLogBodiesResponse|1 team_linked 8|2 user_linked 8|3 entries #0*",Jf]}}class Jf extends T{constructor(t){super(),this.requestJson="",this.responseJson="",this.partialHistory=!1,this.missingBody=wf.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jf).fromBinary(t,r)}static fromJson(t,r){return(new Jf).fromJson(t,r)}static fromJsonString(t,r){return(new Jf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jf,t,r)}static $(){return["GrokRequestLogEntry|1 meta #0|2 request_json 9|3 response_json 9|4 partial_history 8|5 missing_body #1",hf,wf]}}var wf=(0,a.QT)(n.proto3,C,"GrokRequestLogEntry.MissingBody",[[0,"UNSPECIFIED"],[1,"NOT_LOGGED"],[2,"UNREADABLE"]],1);class yf extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,this.pageToken="",this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yf).fromBinary(t,r)}static fromJson(t,r){return(new yf).fromJson(t,r)}static fromJsonString(t,r){return(new yf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yf,t,r)}static $(){return["ListGrokVoiceConversationsRequest|1 team_id 5|2 page_size 5|3 page_token 9|4 time_from_ms 3?|5 time_to_ms 3?|6 min_duration_seconds 13?|7 max_duration_seconds 13?|8 conversation_id 9"]}}class Sf extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.conversations=[],this.nextPageToken="",this.prevPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sf).fromBinary(t,r)}static fromJson(t,r){return(new Sf).fromJson(t,r)}static fromJsonString(t,r){return(new Sf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sf,t,r)}static $(){return["ListGrokVoiceConversationsResponse|1 team_linked 8|2 user_linked 8|3 conversations #0*|4 next_page_token 9|5 prev_page_token 9",qf]}}class qf extends T{constructor(t){super(),this.conversationId="",this.startTimeMs=n.protoInt64.zero,this.endTimeMs=n.protoInt64.zero,this.callerPhoneNumber="",this.destinationPhoneNumber="",this.agentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qf).fromBinary(t,r)}static fromJson(t,r){return(new qf).fromJson(t,r)}static fromJsonString(t,r){return(new qf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qf,t,r)}static $(){return["GrokVoiceConversation|1 conversation_id 9|2 start_time_ms 3|3 end_time_ms 3|4 caller_phone_number 9|5 destination_phone_number 9|6 agent_ids 9*"]}}class Bf extends T{constructor(t){super(),this.conversations=Bt.UNSPECIFIED,this.projects=It.UNSPECIFIED,this.skills=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bf).fromBinary(t,r)}static fromJson(t,r){return(new Bf).fromJson(t,r)}static fromJsonString(t,r){return(new Bf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bf,t,r)}static $(){return["GrokAdminSharingCeiling|1 conversations #0|2 projects #1|3 skills #2",Bt,It,Pt]}}class If extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new If).fromBinary(t,r)}static fromJson(t,r){return(new If).fromJson(t,r)}static fromJsonString(t,r){return(new If).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(If,t,r)}static $(){return["GetGrokAdminTeamSettingsRequest|1 team_id 5"]}}class Pf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pf).fromBinary(t,r)}static fromJson(t,r){return(new Pf).fromJson(t,r)}static fromJsonString(t,r){return(new Pf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pf,t,r)}static $(){return["GetGrokAdminTeamSettingsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 organization_ceiling #4",rf,Bt,It,Pt,Bf]}}class bf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bf).fromBinary(t,r)}static fromJson(t,r){return(new bf).fromJson(t,r)}static fromJsonString(t,r){return(new bf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bf,t,r)}static $(){return["UpdateGrokAdminTeamSettingsRequest|1 team_id 5|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8?|4 conversation_sharing #0?|5 project_sharing #1?|6 skill_sharing #2?",Bt,It,Pt]}}class Rf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rf).fromBinary(t,r)}static fromJson(t,r){return(new Rf).fromJson(t,r)}static fromJsonString(t,r){return(new Rf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rf,t,r)}static $(){return["UpdateGrokAdminTeamSettingsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 organization_ceiling #4",rf,Bt,It,Pt,Bf]}}class vf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vf).fromBinary(t,r)}static fromJson(t,r){return(new vf).fromJson(t,r)}static fromJsonString(t,r){return(new vf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vf,t,r)}static $(){return["GetGrokAdminOrganizationControlsRequest|1 team_id 5"]}}class xf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,this.disableDictation=!1,this.disableBots=!1,this.disablePrivateChats=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xf).fromBinary(t,r)}static fromJson(t,r){return(new xf).fromJson(t,r)}static fromJsonString(t,r){return(new xf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xf,t,r)}static $(){return["GetGrokAdminOrganizationControlsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 disable_dictation 8|8 disable_bots 8|9 disable_private_chats 8",rf,Bt,It,Pt]}}class kf extends T{constructor(t){super(),this.teamId=0,this.retention=bt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kf).fromBinary(t,r)}static fromJson(t,r){return(new kf).fromJson(t,r)}static fromJsonString(t,r){return(new kf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kf,t,r)}static $(){return["UpdateGrokAdminOrganizationControlsRequest|1 team_id 5|2 retention #0|3 conversations_retention_period_days 5?|4 conversation_sharing #1?|5 project_sharing #2?|6 skill_sharing #3?|7 disable_dictation 8?|8 disable_bots 8?|9 disable_private_chats 8?",bt,Bt,It,Pt]}}class Ef extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,this.disableDictation=!1,this.disableBots=!1,this.disablePrivateChats=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ef).fromBinary(t,r)}static fromJson(t,r){return(new Ef).fromJson(t,r)}static fromJsonString(t,r){return(new Ef).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ef,t,r)}static $(){return["UpdateGrokAdminOrganizationControlsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 disable_dictation 8|8 disable_bots 8|9 disable_private_chats 8",rf,Bt,It,Pt]}}class Cf extends T{constructor(t){super(),this.guardrailId="",this.guardrailName="",this.guardrailContent="",this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cf).fromBinary(t,r)}static fromJson(t,r){return(new Cf).fromJson(t,r)}static fromJsonString(t,r){return(new Cf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cf,t,r)}static $(){return["GrokAdminGuardrail|1 guardrail_id 9|2 guardrail_name 9|3 guardrail_description 9?|4 guardrail_content 9|5 is_active 8"]}}class Tf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tf).fromBinary(t,r)}static fromJson(t,r){return(new Tf).fromJson(t,r)}static fromJsonString(t,r){return(new Tf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tf,t,r)}static $(){return["ListGrokAdminGuardrailsRequest|1 team_id 5"]}}class Uf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uf).fromBinary(t,r)}static fromJson(t,r){return(new Uf).fromJson(t,r)}static fromJsonString(t,r){return(new Uf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uf,t,r)}static $(){return["ListGrokAdminGuardrailsResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class Af extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Af).fromBinary(t,r)}static fromJson(t,r){return(new Af).fromJson(t,r)}static fromJsonString(t,r){return(new Af).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Af,t,r)}static $(){return["GetGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class $f extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $f).fromBinary(t,r)}static fromJson(t,r){return(new $f).fromJson(t,r)}static fromJsonString(t,r){return(new $f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($f,t,r)}static $(){return["GetGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Mf extends T{constructor(t){super(),this.teamId=0,this.guardrailName="",this.guardrailDescription="",this.guardrailContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mf).fromBinary(t,r)}static fromJson(t,r){return(new Mf).fromJson(t,r)}static fromJsonString(t,r){return(new Mf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mf,t,r)}static $(){return["CreateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_name 9|3 guardrail_description 9|4 guardrail_content 9"]}}class Of extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Of).fromBinary(t,r)}static fromJson(t,r){return(new Of).fromJson(t,r)}static fromJsonString(t,r){return(new Of).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Of,t,r)}static $(){return["CreateGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Df extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",this.guardrailName="",this.guardrailDescription="",this.guardrailContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Df).fromBinary(t,r)}static fromJson(t,r){return(new Df).fromJson(t,r)}static fromJsonString(t,r){return(new Df).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Df,t,r)}static $(){return["UpdateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9|3 guardrail_name 9|4 guardrail_description 9|5 guardrail_content 9"]}}class Nf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nf).fromBinary(t,r)}static fromJson(t,r){return(new Nf).fromJson(t,r)}static fromJsonString(t,r){return(new Nf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nf,t,r)}static $(){return["UpdateGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Gf extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gf).fromBinary(t,r)}static fromJson(t,r){return(new Gf).fromJson(t,r)}static fromJsonString(t,r){return(new Gf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gf,t,r)}static $(){return["RemoveGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class Lf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lf).fromBinary(t,r)}static fromJson(t,r){return(new Lf).fromJson(t,r)}static fromJsonString(t,r){return(new Lf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lf,t,r)}static $(){return["RemoveGrokAdminGuardrailResponse|1 status #0",rf]}}class Ff extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ff).fromBinary(t,r)}static fromJson(t,r){return(new Ff).fromJson(t,r)}static fromJsonString(t,r){return(new Ff).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ff,t,r)}static $(){return["SetGrokAdminGuardrailActiveRequest|1 team_id 5|2 guardrail_id 9"]}}class Kf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kf).fromBinary(t,r)}static fromJson(t,r){return(new Kf).fromJson(t,r)}static fromJsonString(t,r){return(new Kf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kf,t,r)}static $(){return["SetGrokAdminGuardrailActiveResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class zf extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zf).fromBinary(t,r)}static fromJson(t,r){return(new zf).fromJson(t,r)}static fromJsonString(t,r){return(new zf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zf,t,r)}static $(){return["DeactivateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class jf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jf).fromBinary(t,r)}static fromJson(t,r){return(new jf).fromJson(t,r)}static fromJsonString(t,r){return(new jf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jf,t,r)}static $(){return["DeactivateGrokAdminGuardrailResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class Hf extends T{constructor(t){super(),this.hasBlocklist=!1,this.entryCount=n.protoInt64.zero,this.fileName="",this.version=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hf).fromBinary(t,r)}static fromJson(t,r){return(new Hf).fromJson(t,r)}static fromJsonString(t,r){return(new Hf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hf,t,r)}static $(){return["GrokAdminBlockedUrlInfo|1 has_blocklist 8|2 entry_count 3|3 uploaded_at 3?|4 file_name 9|5 version 5"]}}class Wf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wf).fromBinary(t,r)}static fromJson(t,r){return(new Wf).fromJson(t,r)}static fromJsonString(t,r){return(new Wf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wf,t,r)}static $(){return["GetGrokAdminBlockedUrlsRequest|1 team_id 5"]}}class Qf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qf).fromBinary(t,r)}static fromJson(t,r){return(new Qf).fromJson(t,r)}static fromJsonString(t,r){return(new Qf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qf,t,r)}static $(){return["GetGrokAdminBlockedUrlsResponse|1 status #0|2 info #1",rf,Hf]}}class Vf extends T{constructor(t){super(),this.teamId=0,this.fileName="",this.content=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vf).fromBinary(t,r)}static fromJson(t,r){return(new Vf).fromJson(t,r)}static fromJsonString(t,r){return(new Vf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vf,t,r)}static $(){return["UploadGrokAdminBlockedUrlsRequest|1 team_id 5|2 file_name 9|3 content 12"]}}class Xf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xf).fromBinary(t,r)}static fromJson(t,r){return(new Xf).fromJson(t,r)}static fromJsonString(t,r){return(new Xf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xf,t,r)}static $(){return["UploadGrokAdminBlockedUrlsResponse|1 status #0|2 info #1",rf,Hf]}}class Yf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yf).fromBinary(t,r)}static fromJson(t,r){return(new Yf).fromJson(t,r)}static fromJsonString(t,r){return(new Yf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yf,t,r)}static $(){return["DeleteGrokAdminBlockedUrlsRequest|1 team_id 5"]}}class Zf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zf).fromBinary(t,r)}static fromJson(t,r){return(new Zf).fromJson(t,r)}static fromJsonString(t,r){return(new Zf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zf,t,r)}static $(){return["DeleteGrokAdminBlockedUrlsResponse|1 status #0",rf]}}class td extends T{constructor(t){super(),this.id="",this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new td).fromBinary(t,r)}static fromJson(t,r){return(new td).fromJson(t,r)}static fromJsonString(t,r){return(new td).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(td,t,r)}static $(){return["GrokAdminOnboardingPrompt|1 id 9|2 prompt_text 9|3 source 9?|4 connector_id 9?"]}}class rd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rd).fromBinary(t,r)}static fromJson(t,r){return(new rd).fromJson(t,r)}static fromJsonString(t,r){return(new rd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rd,t,r)}static $(){return["ListGrokAdminOnboardingPromptsRequest|1 team_id 5"]}}class ed extends T{constructor(t){super(),this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ed).fromBinary(t,r)}static fromJson(t,r){return(new ed).fromJson(t,r)}static fromJsonString(t,r){return(new ed).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ed,t,r)}static $(){return["ListGrokAdminOnboardingPromptsResponse|1 status #0|2 prompts #1*",rf,td]}}class nd extends T{constructor(t){super(),this.teamId=0,this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nd).fromBinary(t,r)}static fromJson(t,r){return(new nd).fromJson(t,r)}static fromJsonString(t,r){return(new nd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nd,t,r)}static $(){return["CreateGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_text 9|3 source 9?|4 connector_id 9?"]}}class sd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sd).fromBinary(t,r)}static fromJson(t,r){return(new sd).fromJson(t,r)}static fromJsonString(t,r){return(new sd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sd,t,r)}static $(){return["CreateGrokAdminOnboardingPromptResponse|1 status #0|2 prompt #1",rf,td]}}class id extends T{constructor(t){super(),this.teamId=0,this.promptId="",this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new id).fromBinary(t,r)}static fromJson(t,r){return(new id).fromJson(t,r)}static fromJsonString(t,r){return(new id).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(id,t,r)}static $(){return["UpdateGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_id 9|3 prompt_text 9|4 source 9?|5 connector_id 9?"]}}class od extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new od).fromBinary(t,r)}static fromJson(t,r){return(new od).fromJson(t,r)}static fromJsonString(t,r){return(new od).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(od,t,r)}static $(){return["UpdateGrokAdminOnboardingPromptResponse|1 status #0|2 prompt #1",rf,td]}}class ad extends T{constructor(t){super(),this.teamId=0,this.promptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ad).fromBinary(t,r)}static fromJson(t,r){return(new ad).fromJson(t,r)}static fromJsonString(t,r){return(new ad).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ad,t,r)}static $(){return["DeleteGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_id 9"]}}class ud extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ud).fromBinary(t,r)}static fromJson(t,r){return(new ud).fromJson(t,r)}static fromJsonString(t,r){return(new ud).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ud,t,r)}static $(){return["DeleteGrokAdminOnboardingPromptResponse|1 status #0",rf]}}class cd extends T{constructor(t){super(),this.apiKeyId="",this.maskedKey="",this.name="",this.acls=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.ipRanges=[],this.ipRangesUnreadable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cd).fromBinary(t,r)}static fromJson(t,r){return(new cd).fromJson(t,r)}static fromJsonString(t,r){return(new cd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cd,t,r)}static $(){return["XaiManagementApiKey|1 api_key_id 9|2 masked_key 9|3 name 9|4 acls 9*|5 created_at 3|6 updated_at 3|7 ip_ranges 9*|8 ip_ranges_unreadable 8|9 owner #0",Nm]}}class ld extends T{constructor(t){super(),this.acl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ld).fromBinary(t,r)}static fromJson(t,r){return(new ld).fromJson(t,r)}static fromJsonString(t,r){return(new ld).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ld,t,r)}static $(){return["XaiManagementApiKeyEndpointAcl|1 acl 9|2 description 9?"]}}class md extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new md).fromBinary(t,r)}static fromJson(t,r){return(new md).fromJson(t,r)}static fromJsonString(t,r){return(new md).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(md,t,r)}static $(){return["ListXaiManagementApiKeysRequest|1 team_id 5"]}}class fd extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fd).fromBinary(t,r)}static fromJson(t,r){return(new fd).fromJson(t,r)}static fromJsonString(t,r){return(new fd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fd,t,r)}static $(){return["ListXaiManagementApiKeysResponse|1 api_keys #0*|2 team_linked 8?",cd]}}class dd extends T{constructor(t){super(),this.teamId=0,this.name="",this.acls=[],this.ipRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dd).fromBinary(t,r)}static fromJson(t,r){return(new dd).fromJson(t,r)}static fromJsonString(t,r){return(new dd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dd,t,r)}static $(){return["CreateXaiManagementApiKeyRequest|1 team_id 5|2 name 9|3 acls 9*|4 ip_ranges 9*"]}}class pd extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",this.acls=[],this.ipRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pd).fromBinary(t,r)}static fromJson(t,r){return(new pd).fromJson(t,r)}static fromJsonString(t,r){return(new pd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pd,t,r)}static $(){return["CreateXaiManagementApiKeyResponse|1 api_key 9|2 api_key_id 9|3 acls 9*|4 ip_ranges 9*"]}}class hd extends T{constructor(t){super(),this.cidrs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hd).fromBinary(t,r)}static fromJson(t,r){return(new hd).fromJson(t,r)}static fromJsonString(t,r){return(new hd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hd,t,r)}static $(){return["XaiManagementApiKeyIpRanges|1 cidrs 9*"]}}class gd extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.name="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gd).fromBinary(t,r)}static fromJson(t,r){return(new gd).fromJson(t,r)}static fromJsonString(t,r){return(new gd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gd,t,r)}static $(){return["UpdateXaiManagementApiKeyRequest|1 team_id 5|2 api_key_id 9|3 name 9|4 acls 9*|5 ip_ranges #0",hd]}}class _d extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _d).fromBinary(t,r)}static fromJson(t,r){return(new _d).fromJson(t,r)}static fromJsonString(t,r){return(new _d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_d,t,r)}static $(){return["UpdateXaiManagementApiKeyResponse"]}}class Jd extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jd).fromBinary(t,r)}static fromJson(t,r){return(new Jd).fromJson(t,r)}static fromJsonString(t,r){return(new Jd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jd,t,r)}static $(){return["DeleteXaiManagementApiKeyRequest|1 team_id 5|2 api_key_id 9"]}}class wd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wd).fromBinary(t,r)}static fromJson(t,r){return(new wd).fromJson(t,r)}static fromJsonString(t,r){return(new wd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wd,t,r)}static $(){return["DeleteXaiManagementApiKeyResponse"]}}class yd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yd).fromBinary(t,r)}static fromJson(t,r){return(new yd).fromJson(t,r)}static fromJsonString(t,r){return(new yd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yd,t,r)}static $(){return["ListXaiManagementApiKeyEndpointAclsRequest|1 team_id 5"]}}class Sd extends T{constructor(t){super(),this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sd).fromBinary(t,r)}static fromJson(t,r){return(new Sd).fromJson(t,r)}static fromJsonString(t,r){return(new Sd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sd,t,r)}static $(){return["ListXaiManagementApiKeyEndpointAclsResponse|1 acls #0*",ld]}}class qd extends T{constructor(t){super(),this.id="",this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qd).fromBinary(t,r)}static fromJson(t,r){return(new qd).fromJson(t,r)}static fromJsonString(t,r){return(new qd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qd,t,r)}static $(){return["OrganizationApiKey|1 id 9|2 masked_key 9|3 name 9|4 created_at 3|5 scopes 9*|6 expires_at 3?|7 creator #0|8 last_use #1",Jp,yp]}}class Bd extends T{constructor(t){super(),this.organizationId="",this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bd).fromBinary(t,r)}static fromJson(t,r){return(new Bd).fromJson(t,r)}static fromJsonString(t,r){return(new Bd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bd,t,r)}static $(){return["CreateOrganizationApiKeyRequest|1 organization_id 9|2 name 9|3 scopes 9*|4 expires_at 3?"]}}class Id extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Id).fromBinary(t,r)}static fromJson(t,r){return(new Id).fromJson(t,r)}static fromJsonString(t,r){return(new Id).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Id,t,r)}static $(){return["CreateOrganizationApiKeyResponse|1 api_key 9|2 api_key_id 9"]}}class Pd extends T{constructor(t){super(),this.organizationId="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pd).fromBinary(t,r)}static fromJson(t,r){return(new Pd).fromJson(t,r)}static fromJsonString(t,r){return(new Pd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pd,t,r)}static $(){return["RevokeOrganizationApiKeyRequest|1 organization_id 9|2 api_key_id 9"]}}class bd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bd).fromBinary(t,r)}static fromJson(t,r){return(new bd).fromJson(t,r)}static fromJsonString(t,r){return(new bd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bd,t,r)}static $(){return["RevokeOrganizationApiKeyResponse"]}}class Rd extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rd).fromBinary(t,r)}static fromJson(t,r){return(new Rd).fromJson(t,r)}static fromJsonString(t,r){return(new Rd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rd,t,r)}static $(){return["ListOrganizationApiKeysRequest|1 organization_id 9"]}}class vd extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vd).fromBinary(t,r)}static fromJson(t,r){return(new vd).fromJson(t,r)}static fromJsonString(t,r){return(new vd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vd,t,r)}static $(){return["ListOrganizationApiKeysResponse|1 api_keys #0*",qd]}}class xd extends T{constructor(t){super(),this.teamId=0,this.name="",this.initialRepoScope=[],this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xd).fromBinary(t,r)}static fromJson(t,r){return(new xd).fromJson(t,r)}static fromJsonString(t,r){return(new xd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xd,t,r)}static $(){return["CreateTeamServiceAccountRequest|1 team_id 5|2 name 9|3 description 9?|4 initial_repo_scope 9*|5 initial_repo_scope_enabled 8?|6 permission_ids 9*|7 castle_request_token 9?"]}}class kd extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kd).fromBinary(t,r)}static fromJson(t,r){return(new kd).fromJson(t,r)}static fromJsonString(t,r){return(new kd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kd,t,r)}static $(){return["CreateTeamServiceAccountResponse|1 service_account #0|2 api_key 9",Td]}}class Ed extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ed).fromBinary(t,r)}static fromJson(t,r){return(new Ed).fromJson(t,r)}static fromJsonString(t,r){return(new Ed).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ed,t,r)}static $(){return["ListTeamServiceAccountsRequest|1 team_id 5|2 include_archived 8?|3 include_creators 8?|4 page_size 5?|5 page_token 9|6 query 9?"]}}class Cd extends T{constructor(t){super(),this.serviceAccounts=[],this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cd).fromBinary(t,r)}static fromJson(t,r){return(new Cd).fromJson(t,r)}static fromJsonString(t,r){return(new Cd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cd,t,r)}static $(){return["ListTeamServiceAccountsResponse|1 service_accounts #0*|2 next_page_token 9",Td]}}class Td extends T{constructor(t){super(),this.id="",this.serviceType="",this.name="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.defaultScopes=[],this.apiKeys=[],this.serviceTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Td).fromBinary(t,r)}static fromJson(t,r){return(new Td).fromJson(t,r)}static fromJsonString(t,r){return(new Td).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Td,t,r)}static $(){return["ServiceAccountInfo|1 id 9|2 service_type 9|3 name 9|4 description 9?|5 created_by_user_id 5?|6 owning_team_id 5?|7 owning_user_id 5?|8 usage_limit_cents 5?|9 created_at 3|10 updated_at 3|11 default_scopes 9*|12 api_keys #0*|13 archived_at 3?|14 current_period_spend_cents 5?|15 suspended_at 3?|16 service_tokens #1*|17 creator #2|18 last_use #3",Ud,Xp,Jp,yp]}}class Ud extends T{constructor(t){super(),this.apiKeyId=0,this.maskedApiKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ud).fromBinary(t,r)}static fromJson(t,r){return(new Ud).fromJson(t,r)}static fromJsonString(t,r){return(new Ud).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ud,t,r)}static $(){return["ServiceAccountKeyInfo|1 api_key_id 5|2 masked_api_key 9|3 scopes 9*|4 created_at 3|5 repo_scope 9*|6 repo_scope_enabled 8|7 creator #0|8 last_use #1",Jp,yp]}}class Ad extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ad).fromBinary(t,r)}static fromJson(t,r){return(new Ad).fromJson(t,r)}static fromJsonString(t,r){return(new Ad).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ad,t,r)}static $(){return["DeleteTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class $d extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $d).fromBinary(t,r)}static fromJson(t,r){return(new $d).fromJson(t,r)}static fromJsonString(t,r){return(new $d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($d,t,r)}static $(){return["DeleteTeamServiceAccountResponse"]}}class Md extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Md).fromBinary(t,r)}static fromJson(t,r){return(new Md).fromJson(t,r)}static fromJsonString(t,r){return(new Md).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Md,t,r)}static $(){return["ArchiveTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Od extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Od).fromBinary(t,r)}static fromJson(t,r){return(new Od).fromJson(t,r)}static fromJsonString(t,r){return(new Od).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Od,t,r)}static $(){return["ArchiveTeamServiceAccountResponse"]}}class Dd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dd).fromBinary(t,r)}static fromJson(t,r){return(new Dd).fromJson(t,r)}static fromJsonString(t,r){return(new Dd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dd,t,r)}static $(){return["UpdateTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9|3 name 9|4 description 9?"]}}class Nd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nd).fromBinary(t,r)}static fromJson(t,r){return(new Nd).fromJson(t,r)}static fromJsonString(t,r){return(new Nd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nd,t,r)}static $(){return["UpdateTeamServiceAccountResponse"]}}class Gd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gd).fromBinary(t,r)}static fromJson(t,r){return(new Gd).fromJson(t,r)}static fromJsonString(t,r){return(new Gd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gd,t,r)}static $(){return["RotateServiceAccountApiKeyRequest|1 team_id 5|2 service_account_id 9|3 old_api_key_id 5?|4 permission_ids 9*|5 old_service_token_public_id 9?|6 castle_request_token 9?"]}}class Ld extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ld).fromBinary(t,r)}static fromJson(t,r){return(new Ld).fromJson(t,r)}static fromJsonString(t,r){return(new Ld).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ld,t,r)}static $(){return["RotateServiceAccountApiKeyResponse|1 api_key 9|2 key_info #0|3 service_token #1",Ud,Xp]}}class Fd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fd).fromBinary(t,r)}static fromJson(t,r){return(new Fd).fromJson(t,r)}static fromJsonString(t,r){return(new Fd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fd,t,r)}static $(){return["GetTeamRepositoriesForServiceAccountScopeRequest|1 team_id 5"]}}class Kd extends T{constructor(t){super(),this.owner="",this.name="",this.htmlUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kd).fromBinary(t,r)}static fromJson(t,r){return(new Kd).fromJson(t,r)}static fromJsonString(t,r){return(new Kd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kd,t,r)}static $(){return["ServiceAccountScopeRepository|1 owner 9|2 name 9|3 html_url 9"]}}class zd extends T{constructor(t){super(),this.repositories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zd).fromBinary(t,r)}static fromJson(t,r){return(new zd).fromJson(t,r)}static fromJsonString(t,r){return(new zd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zd,t,r)}static $(){return["GetTeamRepositoriesForServiceAccountScopeResponse|1 repositories #0*",Kd]}}class jd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.apiKeyId=0,this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jd).fromBinary(t,r)}static fromJson(t,r){return(new jd).fromJson(t,r)}static fromJsonString(t,r){return(new jd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jd,t,r)}static $(){return["UpdateServiceAccountRepoScopeRequest|1 team_id 5|2 service_account_id 9|3 api_key_id 5|4 repo_scope 9*|5 repo_scope_enabled 8|6 service_token_public_id 9?"]}}class Hd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hd).fromBinary(t,r)}static fromJson(t,r){return(new Hd).fromJson(t,r)}static fromJsonString(t,r){return(new Hd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hd,t,r)}static $(){return["UpdateServiceAccountRepoScopeResponse|1 api_key #0|2 service_token #1",Ud,Xp]}}class Wd extends T{constructor(t){super(),this.challengeId="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wd).fromBinary(t,r)}static fromJson(t,r){return(new Wd).fromJson(t,r)}static fromJsonString(t,r){return(new Wd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wd,t,r)}static $(){return["StartStepUpRequest|1 challenge_id 9|2 browser_binding 9|3 surface_origin 9"]}}class Qd extends T{constructor(t){super(),this.status=Vd.UNSPECIFIED,this.maskedEmail="",this.actionDescription="",this.retryAfterSeconds=0,this.action="",this.linkTtlSeconds=0,this.statusPollSeconds=0,this.confirmAnywhere=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qd).fromBinary(t,r)}static fromJson(t,r){return(new Qd).fromJson(t,r)}static fromJsonString(t,r){return(new Qd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qd,t,r)}static $(){return["StartStepUpResponse|1 status #0|2 masked_email 9|3 action_description 9|4 retry_after_seconds 5|6 action 9|7 link_ttl_seconds 5|8 status_poll_seconds 5|9 confirm_anywhere 8",Vd]}}var Vd=(0,a.QT)(n.proto3,C,"StartStepUpResponse.Status",[[0,"UNSPECIFIED"],[1,"SENT"],[2,"COOLDOWN"],[3,"RATE_LIMITED"],[4,"EXPIRED"],[5,"NO_EMAIL"]],1);class Xd extends T{constructor(t){super(),this.challengeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xd).fromBinary(t,r)}static fromJson(t,r){return(new Xd).fromJson(t,r)}static fromJsonString(t,r){return(new Xd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xd,t,r)}static $(){return["GetStepUpStatusRequest|1 challenge_id 9"]}}class Yd extends T{constructor(t){super(),this.status=Zd.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yd).fromBinary(t,r)}static fromJson(t,r){return(new Yd).fromJson(t,r)}static fromJsonString(t,r){return(new Yd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yd,t,r)}static $(){return["GetStepUpStatusResponse|1 status #0",Zd]}}var Zd=(0,a.QT)(n.proto3,C,"GetStepUpStatusResponse.Status",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"CONFIRMED"],[3,"EXPIRED"],[4,"COMPLETED"]],1);class tp extends T{constructor(t){super(),this.token="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tp).fromBinary(t,r)}static fromJson(t,r){return(new tp).fromJson(t,r)}static fromJsonString(t,r){return(new tp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tp,t,r)}static $(){return["DescribeStepUpLinkRequest|1 token 9|2 browser_binding 9|3 surface_origin 9"]}}class rp extends T{constructor(t){super(),this.refusal=Rt.UNSPECIFIED,this.action="",this.actionDescription="",this.requestContext="",this.requestedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rp).fromBinary(t,r)}static fromJson(t,r){return(new rp).fromJson(t,r)}static fromJsonString(t,r){return(new rp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rp,t,r)}static $(){return["DescribeStepUpLinkResponse|1 refusal #0|2 action 9|3 action_description 9|4 request_context 9|5 requested_at_ms 3",Rt]}}class ep extends T{constructor(t){super(),this.token="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ep).fromBinary(t,r)}static fromJson(t,r){return(new ep).fromJson(t,r)}static fromJsonString(t,r){return(new ep).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ep,t,r)}static $(){return["ConfirmStepUpLinkRequest|1 token 9|2 browser_binding 9|3 surface_origin 9"]}}class np extends T{constructor(t){super(),this.refusal=Rt.UNSPECIFIED,this.action="",this.actionDescription="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new np).fromBinary(t,r)}static fromJson(t,r){return(new np).fromJson(t,r)}static fromJsonString(t,r){return(new np).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(np,t,r)}static $(){return["ConfirmStepUpLinkResponse|1 refusal #0|2 action 9|3 action_description 9",Rt]}}class sp extends T{constructor(t){super(),this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sp).fromBinary(t,r)}static fromJson(t,r){return(new sp).fromJson(t,r)}static fromJsonString(t,r){return(new sp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sp,t,r)}static $(){return["CreateUserApiKeyRequest|1 name 9|2 scopes 9*|3 expires_at 3?|4 castle_request_token 9?"]}}class ip extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ip).fromBinary(t,r)}static fromJson(t,r){return(new ip).fromJson(t,r)}static fromJsonString(t,r){return(new ip).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ip,t,r)}static $(){return["CreateUserApiKeyResponse|1 api_key 9"]}}class op extends T{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new op).fromBinary(t,r)}static fromJson(t,r){return(new op).fromJson(t,r)}static fromJsonString(t,r){return(new op).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(op,t,r)}static $(){return["RevokeUserApiKeyRequest|1 id 5"]}}class ap extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ap).fromBinary(t,r)}static fromJson(t,r){return(new ap).fromJson(t,r)}static fromJsonString(t,r){return(new ap).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ap,t,r)}static $(){return["RevokeUserApiKeyResponse"]}}class up extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new up).fromBinary(t,r)}static fromJson(t,r){return(new up).fromJson(t,r)}static fromJsonString(t,r){return(new up).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(up,t,r)}static $(){return["ListUserApiKeysRequest"]}}class cp extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cp).fromBinary(t,r)}static fromJson(t,r){return(new cp).fromJson(t,r)}static fromJsonString(t,r){return(new cp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cp,t,r)}static $(){return["ListUserApiKeysResponse|1 api_keys #0*",$m]}}class lp extends T{constructor(t){super(),this.userId=0,this.key={case:void 0},this.name="",this.maskedKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lp).fromBinary(t,r)}static fromJson(t,r){return(new lp).fromJson(t,r)}static fromJsonString(t,r){return(new lp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lp,t,r)}static $(){return["MemberPersonalApiKey|1 user_id 5|2 legacy_id 5 key|3 service_token_public_id 9 key|4 name 9|5 masked_key 9|6 scopes 9*|7 created_at 3|8 expires_at 3?|9 last_used_at 3?|10 last_use #0?",yp]}}class mp extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mp).fromBinary(t,r)}static fromJson(t,r){return(new mp).fromJson(t,r)}static fromJsonString(t,r){return(new mp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mp,t,r)}static $(){return["ListMemberPersonalApiKeysRequest|1 team_id 5|2 user_id 5?|3 page_size 5?|4 page_token 9"]}}class fp extends T{constructor(t){super(),this.keys=[],this.truncated=!1,this.nextPageToken="",this.holders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fp).fromBinary(t,r)}static fromJson(t,r){return(new fp).fromJson(t,r)}static fromJsonString(t,r){return(new fp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fp,t,r)}static $(){return["ListMemberPersonalApiKeysResponse|1 keys #0*|2 truncated 8|3 next_page_token 9|4 holders #1*",lp,dp]}}class dp extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dp).fromBinary(t,r)}static fromJson(t,r){return(new dp).fromJson(t,r)}static fromJsonString(t,r){return(new dp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dp,t,r)}static $(){return["MemberPersonalApiKeyHolder|1 user_id 5|2 name 9|3 email 9"]}}class pp extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.key={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pp).fromBinary(t,r)}static fromJson(t,r){return(new pp).fromJson(t,r)}static fromJsonString(t,r){return(new pp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pp,t,r)}static $(){return["RevokeMemberPersonalApiKeysRequest|1 team_id 5|2 user_id 5|3 legacy_id 5 key|4 service_token_public_id 9 key"]}}class hp extends T{constructor(t){super(),this.revokedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hp).fromBinary(t,r)}static fromJson(t,r){return(new hp).fromJson(t,r)}static fromJsonString(t,r){return(new hp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hp,t,r)}static $(){return["RevokeMemberPersonalApiKeysResponse|1 revoked_count 5"]}}class gp extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gp).fromBinary(t,r)}static fromJson(t,r){return(new gp).fromJson(t,r)}static fromJsonString(t,r){return(new gp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gp,t,r)}static $(){return["ApiKeyInventoryOwner|1 user_id 5 owner|2 team_id 5 owner|3 organization_id 9 owner"]}}class _p extends T{constructor(t){super(),this.kind=vt.UNSPECIFIED,this.id={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _p).fromBinary(t,r)}static fromJson(t,r){return(new _p).fromJson(t,r)}static fromJsonString(t,r){return(new _p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_p,t,r)}static $(){return["ApiKeyInventoryKeyRef|1 kind #0|2 legacy_id 5 id|3 organization_key_id 9 id|4 service_token_public_id 9 id|5 owner #1|6 service_account_id 9?",vt,gp]}}class Jp extends T{constructor(t){super(),this.kind=wp.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jp).fromBinary(t,r)}static fromJson(t,r){return(new Jp).fromJson(t,r)}static fromJsonString(t,r){return(new Jp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jp,t,r)}static $(){return["ApiKeyCreator|1 kind #0|2 user_id 5?|3 name 9?|4 email 9?",wp]}}var wp=(0,a.QT)(n.proto3,C,"ApiKeyCreator.Kind",[[0,"UNSPECIFIED"],[1,"USER"],[2,"SYSTEM"],[3,"NOT_RECORDED"]],1);class yp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yp).fromBinary(t,r)}static fromJson(t,r){return(new yp).fromJson(t,r)}static fromJsonString(t,r){return(new yp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yp,t,r)}static $(){return["ApiKeyLastUse|1 at 3?|2 recorded_since 3?"]}}class Sp extends T{constructor(t){super(),this.name="",this.maskedKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sp).fromBinary(t,r)}static fromJson(t,r){return(new Sp).fromJson(t,r)}static fromJsonString(t,r){return(new Sp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sp,t,r)}static $(){return["ApiKeyInventoryKey|1 ref #0|2 name 9|3 masked_key 9|4 scopes 9*|5 created_at 3|6 expires_at 3?|7 disabled_at 3?|8 created_by #1|9 last_use #2|10 service_account_name 9?",_p,Jp,yp]}}class qp extends T{constructor(t){super(),this.serviceAccountId="",this.serviceType="",this.name="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qp).fromBinary(t,r)}static fromJson(t,r){return(new qp).fromJson(t,r)}static fromJsonString(t,r){return(new qp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qp,t,r)}static $(){return["ApiKeyInventoryServiceAccount|1 service_account_id 9|2 owner #0|3 service_type 9|4 name 9|5 created_at 3|6 archived_at 3?|7 suspended_at 3?|8 created_by #1|9 last_use #2",gp,Jp,yp]}}class Bp extends T{constructor(t){super(),this.row={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bp).fromBinary(t,r)}static fromJson(t,r){return(new Bp).fromJson(t,r)}static fromJsonString(t,r){return(new Bp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bp,t,r)}static $(){return["ApiKeyInventoryRow|1 key #0 row|2 service_account #1 row",Sp,qp]}}class Ip extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ip).fromBinary(t,r)}static fromJson(t,r){return(new Ip).fromJson(t,r)}static fromJsonString(t,r){return(new Ip).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ip,t,r)}static $(){return["ApiKeyInventoryServiceAccountList|1 team_id 5|2 service_account_id 9"]}}class Pp extends T{constructor(t){super(),this.list={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pp).fromBinary(t,r)}static fromJson(t,r){return(new Pp).fromJson(t,r)}static fromJsonString(t,r){return(new Pp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pp,t,r)}static $(){return["ApiKeyInventoryList|1 personal 8 list|2 team_id 5 list|3 organization_id 9 list|4 members_team_id 5 list|5 service_account #0 list|6 all_owners 8 list",Ip]}}class bp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bp).fromBinary(t,r)}static fromJson(t,r){return(new bp).fromJson(t,r)}static fromJsonString(t,r){return(new bp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bp,t,r)}static $(){return["ApiKeyInventoryPageRequest|1 page_size 5?|2 cursor 9?"]}}class Rp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rp).fromBinary(t,r)}static fromJson(t,r){return(new Rp).fromJson(t,r)}static fromJsonString(t,r){return(new Rp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rp,t,r)}static $(){return["ApiKeyInventoryPageInfo|1 next_cursor 9?"]}}class vp extends T{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vp).fromBinary(t,r)}static fromJson(t,r){return(new vp).fromJson(t,r)}static fromJsonString(t,r){return(new vp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vp,t,r)}static $(){return["SearchApiKeysRequest|1 list #0|2 query 9",Pp]}}class xp extends T{constructor(t){super(),this.rows=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xp).fromBinary(t,r)}static fromJson(t,r){return(new xp).fromJson(t,r)}static fromJsonString(t,r){return(new xp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xp,t,r)}static $(){return["SearchApiKeysResponse|1 rows #0*|2 truncated 8",Bp]}}class kp extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kp).fromBinary(t,r)}static fromJson(t,r){return(new kp).fromJson(t,r)}static fromJsonString(t,r){return(new kp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kp,t,r)}static $(){return["ListTeamCredentialsFromFormerMembersRequest|1 team_id 5|2 page_size 5?|3 page_token 9"]}}class Ep extends T{constructor(t){super(),this.rows=[],this.creators=[],this.nextPageToken="",this.creatorsIncomplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ep).fromBinary(t,r)}static fromJson(t,r){return(new Ep).fromJson(t,r)}static fromJsonString(t,r){return(new Ep).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ep,t,r)}static $(){return["ListTeamCredentialsFromFormerMembersResponse|1 rows #0*|2 creators #1*|4 next_page_token 9|5 creators_incomplete 8",Bp,Cp]}}class Cp extends T{constructor(t){super(),this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cp).fromBinary(t,r)}static fromJson(t,r){return(new Cp).fromJson(t,r)}static fromJsonString(t,r){return(new Cp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cp,t,r)}static $(){return["FormerTeamMember|1 user_id 5|2 removed_at 3?"]}}class Tp extends T{constructor(t){super(),this.query="",this.kinds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tp).fromBinary(t,r)}static fromJson(t,r){return(new Tp).fromJson(t,r)}static fromJsonString(t,r){return(new Tp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tp,t,r)}static $(){return["StaffSearchApiKeysRequest|1 query 9|2 kinds #0*|3 owner #1",vt,gp]}}class Up extends T{constructor(t){super(),this.rows=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Up).fromBinary(t,r)}static fromJson(t,r){return(new Up).fromJson(t,r)}static fromJsonString(t,r){return(new Up).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Up,t,r)}static $(){return["StaffSearchApiKeysResponse|1 rows #0*|2 truncated 8",Bp]}}class Ap extends T{constructor(t){super(),this.reason=xt.UNSPECIFIED,this.ticketRef="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ap).fromBinary(t,r)}static fromJson(t,r){return(new Ap).fromJson(t,r)}static fromJsonString(t,r){return(new Ap).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ap,t,r)}static $(){return["StaffWriteContext|1 reason #0|2 ticket_ref 9",xt]}}class $p extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $p).fromBinary(t,r)}static fromJson(t,r){return(new $p).fromJson(t,r)}static fromJsonString(t,r){return(new $p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($p,t,r)}static $(){return["StaffRevokeApiKeyRequest|1 context #0|2 key #1",Ap,_p]}}class Mp extends T{constructor(t){super(),this.changed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mp).fromBinary(t,r)}static fromJson(t,r){return(new Mp).fromJson(t,r)}static fromJsonString(t,r){return(new Mp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mp,t,r)}static $(){return["StaffRevokeApiKeyResponse|1 changed 8"]}}class Op extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Op).fromBinary(t,r)}static fromJson(t,r){return(new Op).fromJson(t,r)}static fromJsonString(t,r){return(new Op).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Op,t,r)}static $(){return["StaffServiceAccountActionRequest|1 context #0|2 team_id 5|3 service_account_id 9",Ap]}}class Dp extends T{constructor(t){super(),this.changed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dp).fromBinary(t,r)}static fromJson(t,r){return(new Dp).fromJson(t,r)}static fromJsonString(t,r){return(new Dp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dp,t,r)}static $(){return["StaffServiceAccountActionResponse|1 changed 8"]}}class Np extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Np).fromBinary(t,r)}static fromJson(t,r){return(new Np).fromJson(t,r)}static fromJsonString(t,r){return(new Np).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Np,t,r)}static $(){return["StaffListOwnerApiKeysRequest|1 owner #0|2 page #1",gp,bp]}}class Gp extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gp).fromBinary(t,r)}static fromJson(t,r){return(new Gp).fromJson(t,r)}static fromJsonString(t,r){return(new Gp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gp,t,r)}static $(){return["StaffListServiceAccountApiKeysRequest|1 team_id 5|2 service_account_id 9|3 page #0",bp]}}class Lp extends T{constructor(t){super(),this.rows=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lp).fromBinary(t,r)}static fromJson(t,r){return(new Lp).fromJson(t,r)}static fromJsonString(t,r){return(new Lp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lp,t,r)}static $(){return["StaffListApiKeysResponse|1 rows #0*|2 page_info #1",Bp,Rp]}}class Fp extends T{constructor(t){super(),this.sessionId="",this.type=m.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fp).fromBinary(t,r)}static fromJson(t,r){return(new Fp).fromJson(t,r)}static fromJsonString(t,r){return(new Fp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fp,t,r)}static $(){return["AdminMemberSessionTarget|1 session_id 9|2 type #0",m]}}class Kp extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kp).fromBinary(t,r)}static fromJson(t,r){return(new Kp).fromJson(t,r)}static fromJsonString(t,r){return(new Kp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kp,t,r)}static $(){return["ListTeamMemberSessionsRequest|1 team_id 5|2 user_id 5"]}}class zp extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zp).fromBinary(t,r)}static fromJson(t,r){return(new zp).fromJson(t,r)}static fromJsonString(t,r){return(new zp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zp,t,r)}static $(){return["RevokeTeamMemberSessionRequest|1 team_id 5|2 user_id 5|3 session #0 target|4 all_sessions 8 target",Fp]}}class jp extends T{constructor(t){super(),this.organizationId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jp).fromBinary(t,r)}static fromJson(t,r){return(new jp).fromJson(t,r)}static fromJsonString(t,r){return(new jp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jp,t,r)}static $(){return["ListOrganizationMemberSessionsRequest|1 organization_id 9|2 user_id 5"]}}class Hp extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hp).fromBinary(t,r)}static fromJson(t,r){return(new Hp).fromJson(t,r)}static fromJsonString(t,r){return(new Hp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hp,t,r)}static $(){return["RevokeOrganizationMemberSessionRequest|1 organization_id 9|2 user_id 5|3 session #0 target|4 all_sessions 8 target",Fp]}}class Wp extends T{constructor(t){super(),this.sessions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wp).fromBinary(t,r)}static fromJson(t,r){return(new Wp).fromJson(t,r)}static fromJsonString(t,r){return(new Wp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wp,t,r)}static $(){return["ListMemberSessionsResponse|1 sessions #0*",l]}}class Qp extends T{constructor(t){super(),this.revokedCount=0,this.revokedCurrentSession=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qp).fromBinary(t,r)}static fromJson(t,r){return(new Qp).fromJson(t,r)}static fromJsonString(t,r){return(new Qp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qp,t,r)}static $(){return["RevokeMemberSessionResponse|1 revoked_count 5|2 revoked_current_session 8"]}}class Vp extends T{constructor(t){super(),this.userId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vp).fromBinary(t,r)}static fromJson(t,r){return(new Vp).fromJson(t,r)}static fromJsonString(t,r){return(new Vp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vp,t,r)}static $(){return["ServiceTokenCreator|1 user_id 9|2 name 9?"]}}class Xp extends T{constructor(t){super(),this.publicId="",this.ownerType=kt.UNSPECIFIED,this.ownerId="",this.name="",this.maskedKey="",this.permissionIds=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.serviceAccountDisabled=!1,this.writeBlockedReason="",this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xp).fromBinary(t,r)}static fromJson(t,r){return(new Xp).fromJson(t,r)}static fromJsonString(t,r){return(new Xp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xp,t,r)}static $(){return["ServiceToken|1 public_id 9|2 owner_type #0|3 owner_id 9|4 name 9|5 masked_key 9|6 permission_ids 9*|7 created_at 3|8 updated_at 3|9 expires_at 3?|10 revoked_at 3?|11 created_by #1|12 service_account_id 9?|13 service_account_name 9?|14 service_account_disabled 8|15 creator #2|16 write_blocked_reason 9|17 repo_scope 9*|18 repo_scope_enabled 8|19 last_use #3",kt,Vp,Jp,yp]}}class Yp extends T{constructor(t){super(),this.owner={case:void 0},this.name="",this.permissionIds=[],this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yp).fromBinary(t,r)}static fromJson(t,r){return(new Yp).fromJson(t,r)}static fromJsonString(t,r){return(new Yp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yp,t,r)}static $(){return["CreateServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 name 9|5 permission_ids 9*|6 expires_at 3?|7 castle_request_token 9?|8 apps #0*",Zp]}}class Zp extends T{constructor(t){super(),this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zp).fromBinary(t,r)}static fromJson(t,r){return(new Zp).fromJson(t,r)}static fromJsonString(t,r){return(new Zp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zp,t,r)}static $(){return["DashboardAppRef|1 slug 9|2 apex 9"]}}class th extends T{constructor(t){super(),this.secret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new th).fromBinary(t,r)}static fromJson(t,r){return(new th).fromJson(t,r)}static fromJsonString(t,r){return(new th).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(th,t,r)}static $(){return["CreateServiceTokenResponse|1 secret 9|2 service_token #0",Xp]}}class rh extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rh).fromBinary(t,r)}static fromJson(t,r){return(new rh).fromJson(t,r)}static fromJsonString(t,r){return(new rh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rh,t,r)}static $(){return["ListServiceTokensRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 app #0",Zp]}}class eh extends T{constructor(t){super(),this.serviceTokens=[],this.fineGrainedKeysEnabled=!1,this.teamCatalogPermissionsEnabled=!1,this.appKeysEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eh).fromBinary(t,r)}static fromJson(t,r){return(new eh).fromJson(t,r)}static fromJsonString(t,r){return(new eh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eh,t,r)}static $(){return["ListServiceTokensResponse|1 service_tokens #0*|2 fine_grained_keys_enabled 8|3 team_catalog_permissions_enabled 8|4 app_keys_enabled 8",Xp]}}class nh extends T{constructor(t){super(),this.teamId=0,this.owner=Et.UNSPECIFIED,this.pageSize=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nh).fromBinary(t,r)}static fromJson(t,r){return(new nh).fromJson(t,r)}static fromJsonString(t,r){return(new nh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nh,t,r)}static $(){return["ListCursorApiKeysRequest|1 team_id 5|2 owner #0|3 page_size 5|4 page_token 9",Et]}}class sh extends T{constructor(t){super(),this.key={case:void 0},this.owner=Et.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sh).fromBinary(t,r)}static fromJson(t,r){return(new sh).fromJson(t,r)}static fromJsonString(t,r){return(new sh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sh,t,r)}static $(){return["CursorApiKey|1 api_key #0 key|2 service_token #1 key|3 owner #2",$m,Xp,Et]}}class ih extends T{constructor(t){super(),this.keys=[],this.nextPageToken="",this.listsTeamKeys=!1,this.personalFineGrainedKeysEnabled=!1,this.teamFineGrainedKeysEnabled=!1,this.teamCatalogPermissionsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ih).fromBinary(t,r)}static fromJson(t,r){return(new ih).fromJson(t,r)}static fromJsonString(t,r){return(new ih).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ih,t,r)}static $(){return["ListCursorApiKeysResponse|1 keys #0*|2 next_page_token 9|3 lists_team_keys 8|4 personal_fine_grained_keys_enabled 8|5 team_fine_grained_keys_enabled 8|6 team_catalog_permissions_enabled 8",sh]}}class oh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oh).fromBinary(t,r)}static fromJson(t,r){return(new oh).fromJson(t,r)}static fromJsonString(t,r){return(new oh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oh,t,r)}static $(){return["UpdateServiceTokenPermissionsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 permission_ids 9*|6 castle_request_token 9?"]}}class ah extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ah).fromBinary(t,r)}static fromJson(t,r){return(new ah).fromJson(t,r)}static fromJsonString(t,r){return(new ah).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ah,t,r)}static $(){return["UpdateServiceTokenPermissionsResponse|1 service_token #0",Xp]}}class uh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uh).fromBinary(t,r)}static fromJson(t,r){return(new uh).fromJson(t,r)}static fromJsonString(t,r){return(new uh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uh,t,r)}static $(){return["RevokeServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9"]}}class ch extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ch).fromBinary(t,r)}static fromJson(t,r){return(new ch).fromJson(t,r)}static fromJsonString(t,r){return(new ch).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ch,t,r)}static $(){return["RevokeServiceTokenResponse"]}}class lh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lh).fromBinary(t,r)}static fromJson(t,r){return(new lh).fromJson(t,r)}static fromJsonString(t,r){return(new lh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lh,t,r)}static $(){return["RotateServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 castle_request_token 9?"]}}class mh extends T{constructor(t){super(),this.secret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mh).fromBinary(t,r)}static fromJson(t,r){return(new mh).fromJson(t,r)}static fromJsonString(t,r){return(new mh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mh,t,r)}static $(){return["RotateServiceTokenResponse|1 secret 9|2 service_token #0",Xp]}}class fh extends T{constructor(t){super(),this.kid="",this.alg="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fh).fromBinary(t,r)}static fromJson(t,r){return(new fh).fromJson(t,r)}static fromJsonString(t,r){return(new fh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fh,t,r)}static $(){return["TrustedIssuerPublicKey|1 kid 9|2 alg 9|3 created_at 3?"]}}class dh extends T{constructor(t){super(),this.publicId="",this.name="",this.clientKey="",this.status=Ct.UNSPECIFIED,this.scopes=[],this.redirectUris=[],this.activeKeyCount=0,this.keys=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dh).fromBinary(t,r)}static fromJson(t,r){return(new dh).fromJson(t,r)}static fromJsonString(t,r){return(new dh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dh,t,r)}static $(){return["TrustedIssuer|1 public_id 9|2 name 9|3 client_key 9|4 status #0|5 scopes 9*|6 redirect_uris 9*|7 active_key_count 5|8 keys #1*|9 created_at 3|10 updated_at 3",Ct,fh]}}class ph extends T{constructor(t){super(),this.owner={case:void 0},this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ph).fromBinary(t,r)}static fromJson(t,r){return(new ph).fromJson(t,r)}static fromJsonString(t,r){return(new ph).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ph,t,r)}static $(){return["ListTrustedIssuersRequest|1 team_id 5 owner|2 organization_id 9 owner|3 page_size 5?|4 page_token 9"]}}class hh extends T{constructor(t){super(),this.issuers=[],this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hh).fromBinary(t,r)}static fromJson(t,r){return(new hh).fromJson(t,r)}static fromJsonString(t,r){return(new hh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hh,t,r)}static $(){return["ListTrustedIssuersResponse|1 issuers #0*|2 next_page_token 9",dh]}}class gh extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gh).fromBinary(t,r)}static fromJson(t,r){return(new gh).fromJson(t,r)}static fromJsonString(t,r){return(new gh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gh,t,r)}static $(){return["GetAuthApplicationsOwnerGateRequest|1 team_id 5 owner|2 organization_id 9 owner"]}}class _h extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _h).fromBinary(t,r)}static fromJson(t,r){return(new _h).fromJson(t,r)}static fromJsonString(t,r){return(new _h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_h,t,r)}static $(){return["GetAuthApplicationsOwnerGateResponse|1 enabled 8"]}}class Jh extends T{constructor(t){super(),this.owner={case:void 0},this.name="",this.scopes=[],this.redirectUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jh).fromBinary(t,r)}static fromJson(t,r){return(new Jh).fromJson(t,r)}static fromJsonString(t,r){return(new Jh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jh,t,r)}static $(){return["CreateTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 name 9|4 scopes 9*|5 redirect_uris 9*|6 castle_request_token 9?"]}}class wh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wh).fromBinary(t,r)}static fromJson(t,r){return(new wh).fromJson(t,r)}static fromJsonString(t,r){return(new wh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wh,t,r)}static $(){return["CreateTrustedIssuerResponse|1 issuer #0",dh]}}class yh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.scopes=[],this.redirectUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yh).fromBinary(t,r)}static fromJson(t,r){return(new yh).fromJson(t,r)}static fromJsonString(t,r){return(new yh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yh,t,r)}static $(){return["UpdateTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 scopes 9*|5 redirect_uris 9*|6 castle_request_token 9?|7 name 9?"]}}class Sh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sh).fromBinary(t,r)}static fromJson(t,r){return(new Sh).fromJson(t,r)}static fromJsonString(t,r){return(new Sh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sh,t,r)}static $(){return["UpdateTrustedIssuerResponse|1 issuer #0",dh]}}class qh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qh).fromBinary(t,r)}static fromJson(t,r){return(new qh).fromJson(t,r)}static fromJsonString(t,r){return(new qh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qh,t,r)}static $(){return["SetTrustedIssuerEnabledRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 enabled 8|5 castle_request_token 9?"]}}class Bh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bh).fromBinary(t,r)}static fromJson(t,r){return(new Bh).fromJson(t,r)}static fromJsonString(t,r){return(new Bh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bh,t,r)}static $(){return["SetTrustedIssuerEnabledResponse|1 issuer #0",dh]}}class Ih extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ih).fromBinary(t,r)}static fromJson(t,r){return(new Ih).fromJson(t,r)}static fromJsonString(t,r){return(new Ih).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ih,t,r)}static $(){return["RevokeTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9"]}}class Ph extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ph).fromBinary(t,r)}static fromJson(t,r){return(new Ph).fromJson(t,r)}static fromJsonString(t,r){return(new Ph).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ph,t,r)}static $(){return["RevokeTrustedIssuerResponse"]}}class bh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.publicJwkJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bh).fromBinary(t,r)}static fromJson(t,r){return(new bh).fromJson(t,r)}static fromJsonString(t,r){return(new bh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bh,t,r)}static $(){return["RegisterTrustedIssuerPublicKeyRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 public_jwk_json 9|5 castle_request_token 9?"]}}class Rh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rh).fromBinary(t,r)}static fromJson(t,r){return(new Rh).fromJson(t,r)}static fromJsonString(t,r){return(new Rh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rh,t,r)}static $(){return["RegisterTrustedIssuerPublicKeyResponse|1 issuer #0",dh]}}class vh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.kid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vh).fromBinary(t,r)}static fromJson(t,r){return(new vh).fromJson(t,r)}static fromJsonString(t,r){return(new vh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vh,t,r)}static $(){return["RevokeTrustedIssuerPublicKeyRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 kid 9"]}}class xh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xh).fromBinary(t,r)}static fromJson(t,r){return(new xh).fromJson(t,r)}static fromJsonString(t,r){return(new xh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xh,t,r)}static $(){return["RevokeTrustedIssuerPublicKeyResponse|1 issuer #0",dh]}}class kh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kh).fromBinary(t,r)}static fromJson(t,r){return(new kh).fromJson(t,r)}static fromJsonString(t,r){return(new kh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kh,t,r)}static $(){return["RevokeTrustedIssuerGrantsRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9"]}}class Eh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eh).fromBinary(t,r)}static fromJson(t,r){return(new Eh).fromJson(t,r)}static fromJsonString(t,r){return(new Eh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eh,t,r)}static $(){return["RevokeTrustedIssuerGrantsResponse"]}}class Ch extends T{constructor(t){super(),this.publicId="",this.teamId=0,this.name="",this.clientId="",this.redirectUris=[],this.scopes=[],this.enabled=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ch).fromBinary(t,r)}static fromJson(t,r){return(new Ch).fromJson(t,r)}static fromJsonString(t,r){return(new Ch).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ch,t,r)}static $(){return["OAuthApplication|1 public_id 9|2 team_id 5|3 name 9|4 client_id 9|5 logo_url 9?|6 redirect_uris 9*|7 scopes 9*|8 enabled 8|9 ip_allowlist #0?|10 created_at 3|11 updated_at 3|12 previous_secret_expires_at 3?",ru]}}class Th extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Th).fromBinary(t,r)}static fromJson(t,r){return(new Th).fromJson(t,r)}static fromJsonString(t,r){return(new Th).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Th,t,r)}static $(){return["ListOAuthApplicationsRequest|1 team_id 5"]}}class Uh extends T{constructor(t){super(),this.applications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uh).fromBinary(t,r)}static fromJson(t,r){return(new Uh).fromJson(t,r)}static fromJsonString(t,r){return(new Uh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uh,t,r)}static $(){return["ListOAuthApplicationsResponse|1 applications #0*",Ch]}}class Ah extends T{constructor(t){super(),this.teamId=0,this.name="",this.redirectUris=[],this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ah).fromBinary(t,r)}static fromJson(t,r){return(new Ah).fromJson(t,r)}static fromJsonString(t,r){return(new Ah).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ah,t,r)}static $(){return["CreateOAuthApplicationRequest|1 team_id 5|2 name 9|3 logo_url 9?|4 redirect_uris 9*|5 scopes 9*|6 ip_allowlist #0?|7 castle_request_token 9?",ru]}}class $h extends T{constructor(t){super(),this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $h).fromBinary(t,r)}static fromJson(t,r){return(new $h).fromJson(t,r)}static fromJsonString(t,r){return(new $h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($h,t,r)}static $(){return["CreateOAuthApplicationResponse|1 application #0|2 client_secret 9",Ch]}}class Mh extends T{constructor(t){super(),this.teamId=0,this.publicId="",this.name="",this.redirectUris=[],this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mh).fromBinary(t,r)}static fromJson(t,r){return(new Mh).fromJson(t,r)}static fromJsonString(t,r){return(new Mh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mh,t,r)}static $(){return["UpdateOAuthApplicationRequest|1 team_id 5|2 public_id 9|3 name 9|4 logo_url 9?|5 redirect_uris 9*|6 scopes 9*|7 ip_allowlist #0?|8 castle_request_token 9?",ru]}}class Oh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oh).fromBinary(t,r)}static fromJson(t,r){return(new Oh).fromJson(t,r)}static fromJsonString(t,r){return(new Oh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oh,t,r)}static $(){return["UpdateOAuthApplicationResponse|1 application #0",Ch]}}class Dh extends T{constructor(t){super(),this.teamId=0,this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dh).fromBinary(t,r)}static fromJson(t,r){return(new Dh).fromJson(t,r)}static fromJsonString(t,r){return(new Dh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dh,t,r)}static $(){return["RotateOAuthApplicationSecretRequest|1 team_id 5|2 public_id 9|3 overlap_seconds 3?|4 castle_request_token 9?"]}}class Nh extends T{constructor(t){super(),this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nh).fromBinary(t,r)}static fromJson(t,r){return(new Nh).fromJson(t,r)}static fromJsonString(t,r){return(new Nh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nh,t,r)}static $(){return["RotateOAuthApplicationSecretResponse|1 application #0|2 client_secret 9",Ch]}}class Gh extends T{constructor(t){super(),this.teamId=0,this.publicId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gh).fromBinary(t,r)}static fromJson(t,r){return(new Gh).fromJson(t,r)}static fromJsonString(t,r){return(new Gh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gh,t,r)}static $(){return["SetOAuthApplicationEnabledRequest|1 team_id 5|2 public_id 9|3 enabled 8"]}}class Lh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lh).fromBinary(t,r)}static fromJson(t,r){return(new Lh).fromJson(t,r)}static fromJsonString(t,r){return(new Lh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lh,t,r)}static $(){return["SetOAuthApplicationEnabledResponse|1 application #0",Ch]}}class Fh extends T{constructor(t){super(),this.teamId=0,this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fh).fromBinary(t,r)}static fromJson(t,r){return(new Fh).fromJson(t,r)}static fromJsonString(t,r){return(new Fh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fh,t,r)}static $(){return["DeleteOAuthApplicationRequest|1 team_id 5|2 public_id 9"]}}class Kh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kh).fromBinary(t,r)}static fromJson(t,r){return(new Kh).fromJson(t,r)}static fromJsonString(t,r){return(new Kh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kh,t,r)}static $(){return["DeleteOAuthApplicationResponse"]}}class zh extends T{constructor(t){super(),this.teamId=0,this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zh).fromBinary(t,r)}static fromJson(t,r){return(new zh).fromJson(t,r)}static fromJsonString(t,r){return(new zh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zh,t,r)}static $(){return["UploadOAuthApplicationLogoRequest|1 team_id 5|2 content_type 9|3 bytes 12"]}}class jh extends T{constructor(t){super(),this.logoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jh).fromBinary(t,r)}static fromJson(t,r){return(new jh).fromJson(t,r)}static fromJsonString(t,r){return(new jh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jh,t,r)}static $(){return["UploadOAuthApplicationLogoResponse|1 logo_url 9"]}}class Hh extends T{constructor(t){super(),this.id="",this.label="",this.description="",this.resourceType=Tt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hh).fromBinary(t,r)}static fromJson(t,r){return(new Hh).fromJson(t,r)}static fromJsonString(t,r){return(new Hh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hh,t,r)}static $(){return["OAuthAuthorizationScope|1 id 9|2 label 9|3 description 9|4 resource_type #0",Tt]}}class Wh extends T{constructor(t){super(),this.type=Tt.UNSPECIFIED,this.id=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wh).fromBinary(t,r)}static fromJson(t,r){return(new Wh).fromJson(t,r)}static fromJsonString(t,r){return(new Wh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wh,t,r)}static $(){return["OAuthGrantResource|1 type #0|2 id 3|3 name 9|4 disabled_reason 9?",Tt]}}class Qh extends T{constructor(t){super(),this.clientId="",this.redirectUri="",this.scopes=[],this.state="",this.codeChallenge="",this.codeChallengeMethod="",this.responseType="",this.validateOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qh).fromBinary(t,r)}static fromJson(t,r){return(new Qh).fromJson(t,r)}static fromJsonString(t,r){return(new Qh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qh,t,r)}static $(){return["GetOAuthAuthorizationRequestRequest|1 client_id 9|2 redirect_uri 9|3 scopes 9*|4 state 9|5 code_challenge 9|6 code_challenge_method 9|7 response_type 9|8 validate_only 8"]}}class Vh extends T{constructor(t){super(),this.authorizationRequestId="",this.applicationName="",this.scopes=[],this.teamId=0,this.redirectUri="",this.state="",this.teamName="",this.publisherTeamId=0,this.publisherTeamName="",this.availableResources=[],this.authority=!1,this.grokBotConnect=!1,this.grokBots=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vh).fromBinary(t,r)}static fromJson(t,r){return(new Vh).fromJson(t,r)}static fromJsonString(t,r){return(new Vh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vh,t,r)}static $(){return["GetOAuthAuthorizationRequestResponse|1 authorization_request_id 9|2 application_name 9|3 logo_url 9?|4 scopes #0*|5 team_id 5|6 redirect_uri 9|7 state 9|8 team_name 9|9 error 9?|10 publisher_team_id 5|11 publisher_team_name 9|12 available_resources #1*|13 authority 8|14 grant_max_expires_at 3?|15 grok_bot_connect 8|16 grok_bots #2*",Hh,Wh,Xh]}}class Xh extends T{constructor(t){super(),this.botId="",this.name="",this.source=Ut.UNSPECIFIED,this.avatarShape="",this.avatarColor="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xh).fromBinary(t,r)}static fromJson(t,r){return(new Xh).fromJson(t,r)}static fromJsonString(t,r){return(new Xh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xh,t,r)}static $(){return["OAuthGrokBotCandidate|1 bot_id 9|2 name 9|3 avatar_url 9?|4 source #0|5 team_name 9?|6 avatar_shape 9|7 avatar_color 9|8 description 9",Ut]}}class Yh extends T{constructor(t){super(),this.authorizationRequestId="",this.selectedResources=[],this.grokBotIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yh).fromBinary(t,r)}static fromJson(t,r){return(new Yh).fromJson(t,r)}static fromJsonString(t,r){return(new Yh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yh,t,r)}static $(){return["ApproveOAuthAuthorizationRequestRequest|1 authorization_request_id 9|2 castle_request_token 9?|3 selected_resources #0*|4 grant_expires_at 3?|5 grok_bot_ids 9*",Wh]}}class Zh extends T{constructor(t){super(),this.redirectUri="",this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zh).fromBinary(t,r)}static fromJson(t,r){return(new Zh).fromJson(t,r)}static fromJsonString(t,r){return(new Zh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zh,t,r)}static $(){return["ApproveOAuthAuthorizationRequestResponse|1 redirect_uri 9|2 code 9|3 state 9"]}}class tg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tg).fromBinary(t,r)}static fromJson(t,r){return(new tg).fromJson(t,r)}static fromJsonString(t,r){return(new tg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tg,t,r)}static $(){return["ListAuthorizedApplicationsRequest"]}}class rg extends T{constructor(t){super(),this.publicId="",this.name="",this.publisherName="",this.scopes=[],this.resources=[],this.grantedAt=n.protoInt64.zero,this.expiresAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rg).fromBinary(t,r)}static fromJson(t,r){return(new rg).fromJson(t,r)}static fromJsonString(t,r){return(new rg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rg,t,r)}static $(){return["AuthorizedApplication|1 public_id 9|2 name 9|3 publisher_name 9|4 scopes #0*|5 resources #1*|6 granted_at 3|7 expires_at 3",Hh,Wh]}}class eg extends T{constructor(t){super(),this.applications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eg).fromBinary(t,r)}static fromJson(t,r){return(new eg).fromJson(t,r)}static fromJsonString(t,r){return(new eg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eg,t,r)}static $(){return["ListAuthorizedApplicationsResponse|1 applications #0*",rg]}}class ng extends T{constructor(t){super(),this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ng).fromBinary(t,r)}static fromJson(t,r){return(new ng).fromJson(t,r)}static fromJsonString(t,r){return(new ng).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ng,t,r)}static $(){return["RevokeAuthorizedApplicationRequest|1 public_id 9"]}}class sg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sg).fromBinary(t,r)}static fromJson(t,r){return(new sg).fromJson(t,r)}static fromJsonString(t,r){return(new sg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sg,t,r)}static $(){return["RevokeAuthorizedApplicationResponse"]}}class ig extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ig).fromBinary(t,r)}static fromJson(t,r){return(new ig).fromJson(t,r)}static fromJsonString(t,r){return(new ig).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ig,t,r)}static $(){return["CreateTeamRequest|1 name 9|2 privacy_mode_forced 8?|3 allow_domain_join 8?|4 source 9?"]}}class og extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new og).fromBinary(t,r)}static fromJson(t,r){return(new og).fromJson(t,r)}static fromJsonString(t,r){return(new og).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(og,t,r)}static $(){return["CreateTeamResponse|1 team_id 5"]}}class ag extends T{constructor(t){super(),this.includePendingInviteCode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ag).fromBinary(t,r)}static fromJson(t,r){return(new ag).fromJson(t,r)}static fromJsonString(t,r){return(new ag).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ag,t,r)}static $(){return["GetJoinableTeamsByDomainRequest|1 include_pending_invite_code 8"]}}class ug extends T{constructor(t){super(),this.id=0,this.name="",this.memberCount=0,this.memberNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ug).fromBinary(t,r)}static fromJson(t,r){return(new ug).fromJson(t,r)}static fromJsonString(t,r){return(new ug).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ug,t,r)}static $(){return["JoinableTeam|1 id 5|2 name 9|3 member_count 5|4 member_names 9*"]}}class cg extends T{constructor(t){super(),this.teams=[],this.emailDomain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cg).fromBinary(t,r)}static fromJson(t,r){return(new cg).fromJson(t,r)}static fromJsonString(t,r){return(new cg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cg,t,r)}static $(){return["GetJoinableTeamsByDomainResponse|1 teams #0*|2 email_domain 9|3 pending_invite_code 9?",ug]}}class lg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lg).fromBinary(t,r)}static fromJson(t,r){return(new lg).fromJson(t,r)}static fromJsonString(t,r){return(new lg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lg,t,r)}static $(){return["JoinTeamByDomainRequest|1 team_id 5"]}}class mg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mg).fromBinary(t,r)}static fromJson(t,r){return(new mg).fromJson(t,r)}static fromJsonString(t,r){return(new mg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mg,t,r)}static $(){return["JoinTeamByDomainResponse|1 success 8"]}}class fg extends T{constructor(t){super(),this.teamId=0,this.allowDomainJoin=!1,this.enabledDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fg).fromBinary(t,r)}static fromJson(t,r){return(new fg).fromJson(t,r)}static fromJsonString(t,r){return(new fg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fg,t,r)}static $(){return["UpdateTeamDomainJoinSettingRequest|1 team_id 5|2 allow_domain_join 8|3 enabled_domains 9*|4 enforce_invite_domain_on_accept 8?"]}}class dg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dg).fromBinary(t,r)}static fromJson(t,r){return(new dg).fromJson(t,r)}static fromJsonString(t,r){return(new dg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dg,t,r)}static $(){return["UpdateTeamDomainJoinSettingResponse"]}}class pg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pg).fromBinary(t,r)}static fromJson(t,r){return(new pg).fromJson(t,r)}static fromJsonString(t,r){return(new pg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pg,t,r)}static $(){return["GetTeamMemberDomainsRequest|1 team_id 5"]}}class hg extends T{constructor(t){super(),this.domain="",this.memberCount=0,this.isEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hg).fromBinary(t,r)}static fromJson(t,r){return(new hg).fromJson(t,r)}static fromJsonString(t,r){return(new hg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hg,t,r)}static $(){return["TeamMemberDomain|1 domain 9|2 member_count 5|3 is_enabled 8"]}}class gg extends T{constructor(t){super(),this.domains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gg).fromBinary(t,r)}static fromJson(t,r){return(new gg).fromJson(t,r)}static fromJsonString(t,r){return(new gg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gg,t,r)}static $(){return["GetTeamMemberDomainsResponse|1 domains #0*",hg]}}class _g extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _g).fromBinary(t,r)}static fromJson(t,r){return(new _g).fromJson(t,r)}static fromJsonString(t,r){return(new _g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_g,t,r)}static $(){return["GetTeamIdForReactivationRequest"]}}class Jg extends T{constructor(t){super(),this.isEligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jg).fromBinary(t,r)}static fromJson(t,r){return(new Jg).fromJson(t,r)}static fromJsonString(t,r){return(new Jg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jg,t,r)}static $(){return["GetTeamIdForReactivationResponse|1 team_id 5?|2 is_eligible 8"]}}class wg extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wg).fromBinary(t,r)}static fromJson(t,r){return(new wg).fromJson(t,r)}static fromJsonString(t,r){return(new wg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wg,t,r)}static $(){return["UpdateRoleRequest|1 team_id 5|2 user_id 5|3 role #0|4 castle_request_token 9?",it]}}class yg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yg).fromBinary(t,r)}static fromJson(t,r){return(new yg).fromJson(t,r)}static fromJsonString(t,r){return(new yg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yg,t,r)}static $(){return["UpdateRoleResponse"]}}class Sg extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sg).fromBinary(t,r)}static fromJson(t,r){return(new Sg).fromJson(t,r)}static fromJsonString(t,r){return(new Sg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sg,t,r)}static $(){return["RemoveMemberRequest|1 team_id 5|2 user_id 5|3 castle_request_token 9?"]}}class qg extends T{constructor(t){super(),this.hasBillingCycleUsage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qg).fromBinary(t,r)}static fromJson(t,r){return(new qg).fromJson(t,r)}static fromJsonString(t,r){return(new qg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qg,t,r)}static $(){return["RemoveMemberResponse|1 has_billing_cycle_usage 8"]}}class Bg extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bg).fromBinary(t,r)}static fromJson(t,r){return(new Bg).fromJson(t,r)}static fromJsonString(t,r){return(new Bg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bg,t,r)}static $(){return["GetMemberRemovalInsightsRequest|1 team_id 5|2 user_id 5"]}}class Ig extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ig).fromBinary(t,r)}static fromJson(t,r){return(new Ig).fromJson(t,r)}static fromJsonString(t,r){return(new Ig).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ig,t,r)}static $(){return["GetMemberRemovalInsightsResponse|1 last_active_at 3?|2 accepted_generated_lines_last_30_days 5?"]}}class Pg extends T{constructor(t){super(),this.teamId=0,this.newSeats=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pg).fromBinary(t,r)}static fromJson(t,r){return(new Pg).fromJson(t,r)}static fromJsonString(t,r){return(new Pg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pg,t,r)}static $(){return["ChangeSeatRequest|1 team_id 5|2 new_seats 5"]}}class bg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bg).fromBinary(t,r)}static fromJson(t,r){return(new bg).fromJson(t,r)}static fromJsonString(t,r){return(new bg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bg,t,r)}static $(){return["ChangeSeatResponse|1 success 8"]}}class Rg extends T{constructor(t){super(),this.teamId=0,this.newNumSeats=0,this.newRequestQuotaPerSeat=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rg).fromBinary(t,r)}static fromJson(t,r){return(new Rg).fromJson(t,r)}static fromJsonString(t,r){return(new Rg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rg,t,r)}static $(){return["ChangeTeamSubscriptionRequest|1 team_id 5|2 new_num_seats 5|3 new_request_quota_per_seat 5"]}}class vg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vg).fromBinary(t,r)}static fromJson(t,r){return(new vg).fromJson(t,r)}static fromJsonString(t,r){return(new vg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vg,t,r)}static $(){return["ChangeTeamSubscriptionResponse|1 success 8"]}}class xg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xg).fromBinary(t,r)}static fromJson(t,r){return(new xg).fromJson(t,r)}static fromJsonString(t,r){return(new xg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xg,t,r)}static $(){return["GetSignUpTypeRequest"]}}class kg extends T{constructor(t){super(),this.signUpType=Eg.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kg).fromBinary(t,r)}static fromJson(t,r){return(new kg).fromJson(t,r)}static fromJsonString(t,r){return(new kg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kg,t,r)}static $(){return["GetSignUpTypeResponse|1 sign_up_type #0",Eg]}}var Eg=(0,a.QT)(n.proto3,C,"GetSignUpTypeResponse.SignUpType",[[0,"UNSPECIFIED"],[1,"AUTH_0"],[2,"GOOGLE"],[3,"GITHUB"],[4,"WORKOS"],[5,"GROK"],[6,"X"]],1);class Cg extends T{constructor(t){super(),this.platform=Tg.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cg).fromBinary(t,r)}static fromJson(t,r){return(new Cg).fromJson(t,r)}static fromJsonString(t,r){return(new Cg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cg,t,r)}static $(){return["GetDownloadLinkRequest|1 platform #0",Tg]}}var Tg=(0,a.QT)(n.proto3,C,"GetDownloadLinkRequest.Platform",[[0,"UNSPECIFIED"],[1,"MAC_APPLE_SILICON"],[2,"MAC_INTEL"],[3,"MAC_UNIVERSAL"],[4,"WINDOWS"],[5,"LINUX"]],1);class Ug extends T{constructor(t){super(),this.cachedDownloadLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ug).fromBinary(t,r)}static fromJson(t,r){return(new Ug).fromJson(t,r)}static fromJsonString(t,r){return(new Ug).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ug,t,r)}static $(){return["GetDownloadLinkResponse|1 cached_download_link 9"]}}class Ag extends T{constructor(t){super(),this.currentVersion="",this.channel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ag).fromBinary(t,r)}static fromJson(t,r){return(new Ag).fromJson(t,r)}static fromJsonString(t,r){return(new Ag).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ag,t,r)}static $(){return["GetCliDownloadUrlRequest|1 current_version 9|2 channel 9"]}}class $g extends T{constructor(t){super(),this.url="",this.version="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $g).fromBinary(t,r)}static fromJson(t,r){return(new $g).fromJson(t,r)}static fromJsonString(t,r){return(new $g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($g,t,r)}static $(){return["GetCliDownloadUrlResponse|1 url 9|2 version 9"]}}class Mg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mg).fromBinary(t,r)}static fromJson(t,r){return(new Mg).fromJson(t,r)}static fromJsonString(t,r){return(new Mg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mg,t,r)}static $(){return["GetSsoConfigurationLinksRequest|1 team_id 5"]}}class Og extends T{constructor(t){super(),this.ssoUrl="",this.domainVerificationUrl="",this.ssoStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Og).fromBinary(t,r)}static fromJson(t,r){return(new Og).fromJson(t,r)}static fromJsonString(t,r){return(new Og).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Og,t,r)}static $(){return["GetSsoConfigurationLinksResponse|1 sso_url 9|2 domain_verification_url 9|3 sso_status 9"]}}class Dg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dg).fromBinary(t,r)}static fromJson(t,r){return(new Dg).fromJson(t,r)}static fromJsonString(t,r){return(new Dg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dg,t,r)}static $(){return["GetScimConfigurationLinksRequest|1 team_id 5"]}}class Ng extends T{constructor(t){super(),this.scimUrl="",this.scimStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ng).fromBinary(t,r)}static fromJson(t,r){return(new Ng).fromJson(t,r)}static fromJsonString(t,r){return(new Ng).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ng,t,r)}static $(){return["GetScimConfigurationLinksResponse|1 scim_url 9|2 scim_status 9"]}}class Gg extends T{constructor(t){super(),this.scimUrl="",this.scimStatuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gg).fromBinary(t,r)}static fromJson(t,r){return(new Gg).fromJson(t,r)}static fromJsonString(t,r){return(new Gg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gg,t,r)}static $(){return["GetOrganizationScimConfigurationLinksResponse|1 scim_url 9|2 scim_statuses 9*"]}}class Lg extends T{constructor(t){super(),this.teamId=0,this.adminOnlyUsagePricing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lg).fromBinary(t,r)}static fromJson(t,r){return(new Lg).fromJson(t,r)}static fromJsonString(t,r){return(new Lg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lg,t,r)}static $(){return["SetAdminOnlyUsagePricingRequest|1 team_id 5|2 admin_only_usage_pricing 8"]}}class Fg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fg).fromBinary(t,r)}static fromJson(t,r){return(new Fg).fromJson(t,r)}static fromJsonString(t,r){return(new Fg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fg,t,r)}static $(){return["SetAdminOnlyUsagePricingResponse"]}}class Kg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kg).fromBinary(t,r)}static fromJson(t,r){return(new Kg).fromJson(t,r)}static fromJsonString(t,r){return(new Kg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kg,t,r)}static $(){return["GetYearlyUpgradeEligibilityRequest|1 team_id 5"]}}class zg extends T{constructor(t){super(),this.eligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zg).fromBinary(t,r)}static fromJson(t,r){return(new zg).fromJson(t,r)}static fromJsonString(t,r){return(new zg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zg,t,r)}static $(){return["GetYearlyUpgradeEligibilityResponse|1 eligible 8"]}}class jg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jg).fromBinary(t,r)}static fromJson(t,r){return(new jg).fromJson(t,r)}static fromJsonString(t,r){return(new jg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jg,t,r)}static $(){return["UpgradeToYearlyRequest|1 team_id 5"]}}class Hg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hg).fromBinary(t,r)}static fromJson(t,r){return(new Hg).fromJson(t,r)}static fromJsonString(t,r){return(new Hg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hg,t,r)}static $(){return["UpgradeToYearlyResponse"]}}class Wg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wg).fromBinary(t,r)}static fromJson(t,r){return(new Wg).fromJson(t,r)}static fromJsonString(t,r){return(new Wg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wg,t,r)}static $(){return["GetEnterpriseCTAEligibilityRequest|1 team_id 5"]}}class Qg extends T{constructor(t){super(),this.eligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qg).fromBinary(t,r)}static fromJson(t,r){return(new Qg).fromJson(t,r)}static fromJsonString(t,r){return(new Qg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qg,t,r)}static $(){return["GetEnterpriseCTAEligibilityResponse|1 eligible 8"]}}class Vg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vg).fromBinary(t,r)}static fromJson(t,r){return(new Vg).fromJson(t,r)}static fromJsonString(t,r){return(new Vg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vg,t,r)}static $(){return["GetUsageBasedPremiumRequestsRequest|1 team_id 5"]}}class Xg extends T{constructor(t){super(),this.usageBasedPremiumRequests=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xg).fromBinary(t,r)}static fromJson(t,r){return(new Xg).fromJson(t,r)}static fromJsonString(t,r){return(new Xg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xg,t,r)}static $(){return["GetUsageBasedPremiumRequestsResponse|1 usage_based_premium_requests 8"]}}class Yg extends T{constructor(t){super(),this.teamId=0,this.usageBasedPremiumRequests=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yg).fromBinary(t,r)}static fromJson(t,r){return(new Yg).fromJson(t,r)}static fromJsonString(t,r){return(new Yg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yg,t,r)}static $(){return["SetUsageBasedPremiumRequestsRequest|1 team_id 5|2 usage_based_premium_requests 8"]}}class Zg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zg).fromBinary(t,r)}static fromJson(t,r){return(new Zg).fromJson(t,r)}static fromJsonString(t,r){return(new Zg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zg,t,r)}static $(){return["SetUsageBasedPremiumRequestsResponse"]}}class t_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new t_).fromBinary(t,r)}static fromJson(t,r){return(new t_).fromJson(t,r)}static fromJsonString(t,r){return(new t_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(t_,t,r)}static $(){return["GetReferralsRequest"]}}class r_ extends T{constructor(t){super(),this.numReferrals=0,this.referralCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new r_).fromBinary(t,r)}static fromJson(t,r){return(new r_).fromJson(t,r)}static fromJsonString(t,r){return(new r_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(r_,t,r)}static $(){return["GetReferralsResponse|1 num_referrals 5|2 referral_code 9"]}}class e_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new e_).fromBinary(t,r)}static fromJson(t,r){return(new e_).fromJson(t,r)}static fromJsonString(t,r){return(new e_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(e_,t,r)}static $(){return["GetReferralCodesRequest"]}}class n_ extends T{constructor(t){super(),this.referralCodes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new n_).fromBinary(t,r)}static fromJson(t,r){return(new n_).fromJson(t,r)}static fromJsonString(t,r){return(new n_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(n_,t,r)}static $(){return["GetReferralCodesResponse|1 referral_codes #0*",g_]}}class s_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new s_).fromBinary(t,r)}static fromJson(t,r){return(new s_).fromJson(t,r)}static fromJsonString(t,r){return(new s_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(s_,t,r)}static $(){return["CreateP2PReferralLinkRequest"]}}class i_ extends T{constructor(t){super(),this.code="",this.urlPath="",this.title="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new i_).fromBinary(t,r)}static fromJson(t,r){return(new i_).fromJson(t,r)}static fromJsonString(t,r){return(new i_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(i_,t,r)}static $(){return["CreateP2PReferralLinkResponse|1 code 9|2 url_path 9|3 title 9|4 description 9"]}}class o_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o_).fromBinary(t,r)}static fromJson(t,r){return(new o_).fromJson(t,r)}static fromJsonString(t,r){return(new o_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o_,t,r)}static $(){return["GetP2PReferralStatusRequest"]}}class a_ extends T{constructor(t){super(),this.isEligible=!1,this.successfulReferrals=0,this.pendingReferrals=0,this.remainingCap=0,this.totalCreditCentsEarned=n.protoInt64.zero,this.cycleCreditCentsEarned=n.protoInt64.zero,this.title="",this.description="",this.invitedReferrals=0,this.invitedRewardEarned=0,this.invitedSignedUp=0,this.invitedNotEligible=0,this.invitedClawedBack=0,this.capWindowLabel="",this.referrerCreditCents=0,this.refereeCreditCents=0,this.currency="",this.referrerMode="",this.refereeMode="",this.remainingRedemptionCap=0,this.rewardedReferrals=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a_).fromBinary(t,r)}static fromJson(t,r){return(new a_).fromJson(t,r)}static fromJsonString(t,r){return(new a_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a_,t,r)}static $(){return["GetP2PReferralStatusResponse|1 is_eligible 8|2 code 9?|3 url_path 9?|4 successful_referrals 5|5 pending_referrals 5|6 remaining_cap 5|7 total_credit_cents_earned 3|22 cycle_credit_cents_earned 3|8 title 9|9 description 9|10 cycle_start_ms 3?|11 invited_referrals 5|12 invited_reward_earned 5|13 invited_signed_up 5|14 invited_not_eligible 5|15 invited_clawed_back 5|16 cap_window_label 9|17 referrer_credit_cents 5|18 referee_credit_cents 5|19 currency 9|20 referrer_mode 9|21 referee_mode 9|23 remaining_redemption_cap 5|24 rewarded_referrals 5"]}}class u_ extends T{constructor(t){super(),this.emails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u_).fromBinary(t,r)}static fromJson(t,r){return(new u_).fromJson(t,r)}static fromJsonString(t,r){return(new u_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u_,t,r)}static $(){return["SendP2PReferralInvitesRequest|1 emails 9*"]}}class c_ extends T{constructor(t){super(),this.sentEmails=[],this.failures=[],this.code="",this.urlPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c_).fromBinary(t,r)}static fromJson(t,r){return(new c_).fromJson(t,r)}static fromJsonString(t,r){return(new c_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c_,t,r)}static $(){return["SendP2PReferralInvitesResponse|1 sent_emails 9*|2 failures #0*|3 code 9|4 url_path 9",l_]}}class l_ extends T{constructor(t){super(),this.email="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l_).fromBinary(t,r)}static fromJson(t,r){return(new l_).fromJson(t,r)}static fromJsonString(t,r){return(new l_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l_,t,r)}static $(){return["SendP2PReferralInvitesFailure|1 email 9|2 reason 9"]}}class m_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m_).fromBinary(t,r)}static fromJson(t,r){return(new m_).fromJson(t,r)}static fromJsonString(t,r){return(new m_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m_,t,r)}static $(){return["GetP2PReferralHistoryRequest"]}}class f_ extends T{constructor(t){super(),this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f_).fromBinary(t,r)}static fromJson(t,r){return(new f_).fromJson(t,r)}static fromJsonString(t,r){return(new f_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f_,t,r)}static $(){return["GetP2PReferralHistoryResponse|1 entries #0*",d_]}}class d_ extends T{constructor(t){super(),this.refereeLabel="",this.displayStatus="",this.creditCentsEarned=n.protoInt64.zero,this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d_).fromBinary(t,r)}static fromJson(t,r){return(new d_).fromJson(t,r)}static fromJsonString(t,r){return(new d_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d_,t,r)}static $(){return["P2PReferralHistoryEntry|1 referee_label 9|2 display_status 9|3 credit_cents_earned 3|4 created_at_ms 3"]}}class p_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p_).fromBinary(t,r)}static fromJson(t,r){return(new p_).fromJson(t,r)}static fromJsonString(t,r){return(new p_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p_,t,r)}static $(){return["CheckReferralAllowlistRequest"]}}class h_ extends T{constructor(t){super(),this.isInAllowlist=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h_).fromBinary(t,r)}static fromJson(t,r){return(new h_).fromJson(t,r)}static fromJsonString(t,r){return(new h_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h_,t,r)}static $(){return["CheckReferralAllowlistResponse|1 is_in_allowlist 8"]}}class g_ extends T{constructor(t){super(),this.code="",this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g_).fromBinary(t,r)}static fromJson(t,r){return(new g_).fromJson(t,r)}static fromJsonString(t,r){return(new g_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g_,t,r)}static $(){return["ReferralCodeEntry|1 code 9|2 created_at_ms 3|3 redeemed_at_ms 3?|4 redeemer_name 9?"]}}class __ extends T{constructor(t){super(),this.referralCode="",this.authId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new __).fromBinary(t,r)}static fromJson(t,r){return(new __).fromJson(t,r)}static fromJsonString(t,r){return(new __).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(__,t,r)}static $(){return["CheckReferralCodeRequest|1 referral_code 9|2 auth_id 9"]}}class J_ extends T{constructor(t){super(),this.isValid=!1,this.userIsEligible=!1,this.maxRedemptions=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J_).fromBinary(t,r)}static fromJson(t,r){return(new J_).fromJson(t,r)}static fromJsonString(t,r){return(new J_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J_,t,r)}static $(){return["CheckReferralCodeResponse|1 is_valid 8|2 user_is_eligible 8|3 max_redemptions 8|4 metadata #0?",w_]}}class w_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w_).fromBinary(t,r)}static fromJson(t,r){return(new w_).fromJson(t,r)}static fromJsonString(t,r){return(new w_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w_,t,r)}static $(){return["Metadata|1 title 9?|2 description 9?|3 discount_type 9?"]}}class y_ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y_).fromBinary(t,r)}static fromJson(t,r){return(new y_).fromJson(t,r)}static fromJsonString(t,r){return(new y_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y_,t,r)}static $(){return["GetTeamReposRequest|1 team_id 5"]}}class S_ extends T{constructor(t){super(),this.repos=[],this.teamRepoType="",this.allowedRepos=[],this.disableLocalExecAllowlistEnforcement=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S_).fromBinary(t,r)}static fromJson(t,r){return(new S_).fromJson(t,r)}static fromJsonString(t,r){return(new S_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S_,t,r)}static $(){return["GetTeamReposResponse|1 repos #0*|2 team_repo_type 9|3 allowed_repos #0*|4 disable_local_exec_allowlist_enforcement 8",q_]}}class q_ extends T{constructor(t){super(),this.id=0,this.url="",this.patterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q_).fromBinary(t,r)}static fromJson(t,r){return(new q_).fromJson(t,r)}static fromJsonString(t,r){return(new q_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q_,t,r)}static $(){return["GetTeamReposResponse.Repo|1 id 5|2 url 9|3 patterns #0*",B_]}}class B_ extends T{constructor(t){super(),this.id=0,this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B_).fromBinary(t,r)}static fromJson(t,r){return(new B_).fromJson(t,r)}static fromJsonString(t,r){return(new B_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B_,t,r)}static $(){return["GetTeamReposResponse.Pattern|1 id 5|2 pattern 9"]}}class I_ extends T{constructor(t){super(),this.teamId=0,this.repoUrl="",this.repoType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I_).fromBinary(t,r)}static fromJson(t,r){return(new I_).fromJson(t,r)}static fromJsonString(t,r){return(new I_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I_,t,r)}static $(){return["CreateTeamRepoRequest|1 team_id 5|2 repo_url 9|3 repo_type 9"]}}class P_ extends T{constructor(t){super(),this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P_).fromBinary(t,r)}static fromJson(t,r){return(new P_).fromJson(t,r)}static fromJsonString(t,r){return(new P_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P_,t,r)}static $(){return["CreateTeamRepoResponse|1 repo_id 5"]}}class b_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b_).fromBinary(t,r)}static fromJson(t,r){return(new b_).fromJson(t,r)}static fromJsonString(t,r){return(new b_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b_,t,r)}static $(){return["DeleteTeamRepoRequest|1 team_id 5|2 repo_id 5"]}}class R_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R_).fromBinary(t,r)}static fromJson(t,r){return(new R_).fromJson(t,r)}static fromJsonString(t,r){return(new R_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R_,t,r)}static $(){return["DeleteTeamRepoResponse"]}}class v_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v_).fromBinary(t,r)}static fromJson(t,r){return(new v_).fromJson(t,r)}static fromJsonString(t,r){return(new v_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v_,t,r)}static $(){return["AddRepoPatternRequest|1 team_id 5|2 repo_id 5|3 pattern 9"]}}class x_ extends T{constructor(t){super(),this.patternId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x_).fromBinary(t,r)}static fromJson(t,r){return(new x_).fromJson(t,r)}static fromJsonString(t,r){return(new x_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x_,t,r)}static $(){return["AddRepoPatternResponse|1 pattern_id 5"]}}class k_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,this.patternId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k_).fromBinary(t,r)}static fromJson(t,r){return(new k_).fromJson(t,r)}static fromJsonString(t,r){return(new k_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k_,t,r)}static $(){return["RemoveRepoPatternRequest|1 team_id 5|2 repo_id 5|3 pattern_id 5"]}}class E_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E_).fromBinary(t,r)}static fromJson(t,r){return(new E_).fromJson(t,r)}static fromJsonString(t,r){return(new E_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E_,t,r)}static $(){return["RemoveRepoPatternResponse"]}}class C_ extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.teamId=0,this.teamName="",this.gitOrgOwner="",this.gitProvider=At.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C_).fromBinary(t,r)}static fromJson(t,r){return(new C_).fromJson(t,r)}static fromJsonString(t,r){return(new C_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C_,t,r)}static $(){return["ProtectedGitScope|1 id 3|2 team_id 5|3 team_name 9|4 git_org_owner 9|5 git_provider #0|6 git_enterprise_uuid 9?|7 created_at 3|8 updated_at 3",At]}}class T_ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T_).fromBinary(t,r)}static fromJson(t,r){return(new T_).fromJson(t,r)}static fromJsonString(t,r){return(new T_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T_,t,r)}static $(){return["GetProtectedGitScopesRequest|1 team_id 5"]}}class U_ extends T{constructor(t){super(),this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U_).fromBinary(t,r)}static fromJson(t,r){return(new U_).fromJson(t,r)}static fromJsonString(t,r){return(new U_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U_,t,r)}static $(){return["GetProtectedGitScopesResponse|1 scopes #0*",C_]}}class A_ extends T{constructor(t){super(),this.teamId=0,this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A_).fromBinary(t,r)}static fromJson(t,r){return(new A_).fromJson(t,r)}static fromJsonString(t,r){return(new A_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A_,t,r)}static $(){return["CreateProtectedGitScopeRequest|1 team_id 5|2 repo_url 9"]}}class $_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $_).fromBinary(t,r)}static fromJson(t,r){return(new $_).fromJson(t,r)}static fromJsonString(t,r){return(new $_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($_,t,r)}static $(){return["CreateProtectedGitScopeResponse|1 scope #0",C_]}}class M_ extends T{constructor(t){super(),this.teamId=0,this.scopeId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M_).fromBinary(t,r)}static fromJson(t,r){return(new M_).fromJson(t,r)}static fromJsonString(t,r){return(new M_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M_,t,r)}static $(){return["DeleteProtectedGitScopeRequest|1 team_id 5|2 scope_id 3"]}}class O_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O_).fromBinary(t,r)}static fromJson(t,r){return(new O_).fromJson(t,r)}static fromJsonString(t,r){return(new O_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O_,t,r)}static $(){return["DeleteProtectedGitScopeResponse"]}}class D_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D_).fromBinary(t,r)}static fromJson(t,r){return(new D_).fromJson(t,r)}static fromJsonString(t,r){return(new D_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D_,t,r)}static $(){return["GetTeamAdminSettingsRequest|1 team_id 5?|2 supports_host_mcp_bridge_exemption 8?"]}}class N_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N_).fromBinary(t,r)}static fromJson(t,r){return(new N_).fromJson(t,r)}static fromJsonString(t,r){return(new N_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N_,t,r)}static $(){return["GetTeamOriginDisabledRequest|1 team_id 5?"]}}class G_ extends T{constructor(t){super(),this.originDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G_).fromBinary(t,r)}static fromJson(t,r){return(new G_).fromJson(t,r)}static fromJsonString(t,r){return(new G_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G_,t,r)}static $(){return["GetTeamOriginDisabledResponse|1 origin_disabled 8"]}}class L_ extends T{constructor(t){super(),this.displayName="",this.kind=$t.UNSPECIFIED,this.host="",this.memberCount=0,this.pluginId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L_).fromBinary(t,r)}static fromJson(t,r){return(new L_).fromJson(t,r)}static fromJsonString(t,r){return(new L_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L_,t,r)}static $(){return["UnlistedMemberServer|1 display_name 9|2 kind #0|3 host 9|4 member_count 5|5 plugin_id 9",$t]}}class F_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F_).fromBinary(t,r)}static fromJson(t,r){return(new F_).fromJson(t,r)}static fromJsonString(t,r){return(new F_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F_,t,r)}static $(){return["ListUnlistedMemberServersRequest|1 team_id 5?"]}}class K_ extends T{constructor(t){super(),this.servers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K_).fromBinary(t,r)}static fromJson(t,r){return(new K_).fromJson(t,r)}static fromJsonString(t,r){return(new K_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K_,t,r)}static $(){return["ListUnlistedMemberServersResponse|1 servers #0*",L_]}}class z_ extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z_).fromBinary(t,r)}static fromJson(t,r){return(new z_).fromJson(t,r)}static fromJsonString(t,r){return(new z_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z_,t,r)}static $(){return["AdminCommandDenylist|1 rules 9*"]}}class j_ extends T{constructor(t){super(),this.enabled=!1,this.allowed=[],this.blocked=[],this.disableMcpAutoRun=!1,this.deleteFileProtection=!1,this.enableRunEverything=!1,this.mcpToolAllowlist=[],this.browserProtection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j_).fromBinary(t,r)}static fromJson(t,r){return(new j_).fromJson(t,r)}static fromJsonString(t,r){return(new j_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j_,t,r)}static $(){return["AutoRunControls|1 enabled 8|2 allowed 9*|3 blocked 9*|4 disable_mcp_auto_run 8|5 delete_file_protection 8|6 enable_run_everything 8|7 mcp_tool_allowlist 9*|8 sandboxing_controls #0|9 browser_protection 8|10 enable_smart_auto 8?|11 enable_allowlist_mode 8?|12 admin_command_denylist #1|13 admin_command_denylist_replaces_team 8?",SJ,z_]}}class H_ extends T{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H_).fromBinary(t,r)}static fromJson(t,r){return(new H_).fromJson(t,r)}static fromJsonString(t,r){return(new H_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H_,t,r)}static $(){return["AutoReviewInstructions|1 allow_instructions 9*|2 block_instructions 9*"]}}class W_ extends T{constructor(t){super(),this.hierarchicalEnabled=!1,this.ignoreSymlinks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W_).fromBinary(t,r)}static fromJson(t,r){return(new W_).fromJson(t,r)}static fromJsonString(t,r){return(new W_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W_,t,r)}static $(){return["CursorIgnoreControls|1 hierarchical_enabled 8|2 ignore_symlinks 8"]}}class Q_ extends T{constructor(t){super(),this.networkAllowlist=[],this.toolAllowlist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q_).fromBinary(t,r)}static fromJson(t,r){return(new Q_).fromJson(t,r)}static fromJsonString(t,r){return(new Q_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q_,t,r)}static $(){return["AllowedMCPServer|1 command 9?|2 server_url 9?|3 name 9?|4 network_allowlist 9*|5 tool_allowlist 9*|6 network_mode 9?|7 tool_allowlist_mode 9?|8 builtin_server 9?|9 is_derived 8?|10 rule_id 9?"]}}class V_ extends T{constructor(t){super(),this.allowedMcpServers=[],this.deniedMcpServers=[],this.builtinMcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V_).fromBinary(t,r)}static fromJson(t,r){return(new V_).fromJson(t,r)}static fromJsonString(t,r){return(new V_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V_,t,r)}static $(){return["AllowedMCPConfiguration|1 disable_all 8?|2 allowed_mcp_servers #0*|3 require_mcp_servers_in_team_network_allowlist 8?|4 allow_user_override_mcp_servers 8?|10 denied_mcp_servers #0*|11 enable_cursor_cloud_mcp 8?|12 builtin_mcp_servers #0*|13 off_mcp_server_rules #1",Q_,X_]}}class X_ extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X_).fromBinary(t,r)}static fromJson(t,r){return(new X_).fromJson(t,r)}static fromJsonString(t,r){return(new X_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X_,t,r)}static $(){return["OffMcpServerRules|1 rules #0*",Q_]}}class Y_ extends T{constructor(t){super(),this.mode=Mt.UNSPECIFIED,this.allowedPluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y_).fromBinary(t,r)}static fromJson(t,r){return(new Y_).fromJson(t,r)}static fromJsonString(t,r){return(new Y_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y_,t,r)}static $(){return["FirstPartyPluginConfiguration|1 mode #0|2 allowed_plugin_ids 9*",Mt]}}class Z_ extends T{constructor(t){super(),this.prReviewOpenDestination=Dt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z_).fromBinary(t,r)}static fromJson(t,r){return(new Z_).fromJson(t,r)}static fromJsonString(t,r){return(new Z_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z_,t,r)}static $(){return["PullRequestPreferences|1 pr_review_open_destination #0",Dt]}}class tJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tJ).fromBinary(t,r)}static fromJson(t,r){return(new tJ).fromJson(t,r)}static fromJsonString(t,r){return(new tJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tJ,t,r)}static $(){return["GetRepoSourcePreferenceRequest|1 team_id 5?"]}}class rJ extends T{constructor(t){super(),this.userPreference=zt.UNSPECIFIED,this.teamPreference=zt.UNSPECIFIED,this.effectivePreference=zt.UNSPECIFIED,this.canConfigure=!1,this.originReposEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rJ).fromBinary(t,r)}static fromJson(t,r){return(new rJ).fromJson(t,r)}static fromJsonString(t,r){return(new rJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rJ,t,r)}static $(){return["GetRepoSourcePreferenceResponse|1 user_preference #0|2 team_preference #0|3 effective_preference #0|4 can_configure 8|5 origin_repos_enabled 8",zt]}}class eJ extends T{constructor(t){super(),this.preference=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eJ).fromBinary(t,r)}static fromJson(t,r){return(new eJ).fromJson(t,r)}static fromJsonString(t,r){return(new eJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eJ,t,r)}static $(){return["UpdateUserRepoSourcePreferenceRequest|1 preference #0",zt]}}class nJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nJ).fromBinary(t,r)}static fromJson(t,r){return(new nJ).fromJson(t,r)}static fromJsonString(t,r){return(new nJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nJ,t,r)}static $(){return["UpdateUserRepoSourcePreferenceResponse"]}}class sJ extends T{constructor(t){super(),this.teamId=0,this.preference=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sJ).fromBinary(t,r)}static fromJson(t,r){return(new sJ).fromJson(t,r)}static fromJsonString(t,r){return(new sJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sJ,t,r)}static $(){return["UpdateTeamRepoSourcePreferenceRequest|1 team_id 5|2 preference #0",zt]}}class iJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iJ).fromBinary(t,r)}static fromJson(t,r){return(new iJ).fromJson(t,r)}static fromJsonString(t,r){return(new iJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iJ,t,r)}static $(){return["UpdateTeamRepoSourcePreferenceResponse"]}}class oJ extends T{constructor(t){super(),this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oJ).fromBinary(t,r)}static fromJson(t,r){return(new oJ).fromJson(t,r)}static fromJsonString(t,r){return(new oJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oJ,t,r)}static $(){return["ResolvePrCreationForgeRequest|1 repo_url 9|2 team_id 5?"]}}class aJ extends T{constructor(t){super(),this.forge=uJ.UNSPECIFIED,this.repoUrl="",this.switched=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aJ).fromBinary(t,r)}static fromJson(t,r){return(new aJ).fromJson(t,r)}static fromJsonString(t,r){return(new aJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aJ,t,r)}static $(){return["ResolvePrCreationForgeResponse|1 forge #0|2 repo_url 9|3 switched 8",uJ]}}var uJ=(0,a.QT)(n.proto3,C,"ResolvePrCreationForgeResponse.PrCreationForge",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"ORIGIN"]],1);class cJ extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.teamFollowupEnabled=!1,this.autoCreatePr=Ot.UNSPECIFIED,this.prReviewOpenDestination=Dt.UNSPECIFIED,this.githubArtifactPosting=Nt.UNSPECIFIED,this.egressProtectionMode=Lt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cJ).fromBinary(t,r)}static fromJson(t,r){return(new cJ).fromJson(t,r)}static fromJsonString(t,r){return(new cJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cJ,t,r)}static $(){return["BackgroundAgentSettings|1 allowlist 9*|2 allowlist_config #0|3 team_followup_enabled 8|4 auto_create_pr #1|5 pr_review_open_destination #2|6 require_private_workers 8?|7 github_artifact_posting #3|8 team_followup_enabled_v2 #4?|9 enable_long_running_agent_mode 8?|10 egress_protection_mode #5|11 lock_egress_protection_mode 8?|12 enable_cloud_agent_testing 8?|13 restrict_team_secrets_to_admins 8?|14 enable_automations 8?|15 allow_vm_sharing 8?|16 allow_private_workers 8?|17 public_artifact_sharing #6?|18 ci_failure_followup_enabled 8?|19 data_retention #7|20 restrict_team_environment_writes_to_admins 8?|21 allow_remote_control 8?|22 allow_private_worker_github_token_mint 8?|23 allow_private_worker_secret_sync 8?|24 disable_cloud_agents_in_sand 8?|25 automation_default_visibility #8?|26 auto_allow_project_placements 8?|27 personal_secrets_policy #9?|28 default_private_worker_pool 9?|29 grok_bot_customer_hosted 8?|30 grok_bot_customer_hosted_pool 9?|31 reject_static_pool_credentials 8?|32 slack_reply_mode #10?|33 route_scm_tokens_through_http_rules 8?|34 vnc_enabled 8?",Tr,Ot,Dt,Nt,Ft,Lt,Gt,pJ,jt,Ht,Kt]}}class lJ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lJ).fromBinary(t,r)}static fromJson(t,r){return(new lJ).fromJson(t,r)}static fromJsonString(t,r){return(new lJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lJ,t,r)}static $(){return["GetCloudAgentStartupScriptRequest|1 team_id 5"]}}class mJ extends T{constructor(t){super(),this.available=!1,this.name="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mJ).fromBinary(t,r)}static fromJson(t,r){return(new mJ).fromJson(t,r)}static fromJsonString(t,r){return(new mJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mJ,t,r)}static $(){return["GetCloudAgentStartupScriptResponse|1 available 8|2 name 9|3 body 9"]}}class fJ extends T{constructor(t){super(),this.teamId=0,this.name="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fJ).fromBinary(t,r)}static fromJson(t,r){return(new fJ).fromJson(t,r)}static fromJsonString(t,r){return(new fJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fJ,t,r)}static $(){return["UpdateCloudAgentStartupScriptRequest|1 team_id 5|2 name 9|3 body 9"]}}class dJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dJ).fromBinary(t,r)}static fromJson(t,r){return(new dJ).fromJson(t,r)}static fromJsonString(t,r){return(new dJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dJ,t,r)}static $(){return["UpdateCloudAgentStartupScriptResponse"]}}class pJ extends T{constructor(t){super(),this.kind={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pJ).fromBinary(t,r)}static fromJson(t,r){return(new pJ).fromJson(t,r)}static fromJsonString(t,r){return(new pJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pJ,t,r)}static $(){return["DataRetentionPolicy|1 indefinite #0 kind|2 limited #1 kind",hJ,gJ]}}class hJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hJ).fromBinary(t,r)}static fromJson(t,r){return(new hJ).fromJson(t,r)}static fromJsonString(t,r){return(new hJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hJ,t,r)}static $(){return["DataRetentionPolicy.Indefinite"]}}class gJ extends T{constructor(t){super(),this.hours=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gJ).fromBinary(t,r)}static fromJson(t,r){return(new gJ).fromJson(t,r)}static fromJsonString(t,r){return(new gJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gJ,t,r)}static $(){return["DataRetentionPolicy.Limited|1 hours 13"]}}class _J extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.disableHeadless=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _J).fromBinary(t,r)}static fromJson(t,r){return(new _J).fromJson(t,r)}static fromJsonString(t,r){return(new _J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_J,t,r)}static $(){return["CliSettings|1 allowlist 9*|2 allowlist_config #0|3 disable_headless 8",Tr]}}class JJ extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JJ).fromBinary(t,r)}static fromJson(t,r){return(new JJ).fromJson(t,r)}static fromJsonString(t,r){return(new JJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JJ,t,r)}static $(){return["BrowserAccessControl|1 allowlist 9*|2 allowlist_config #0",Tr]}}class wJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wJ).fromBinary(t,r)}static fromJson(t,r){return(new wJ).fromJson(t,r)}static fromJsonString(t,r){return(new wJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wJ,t,r)}static $(){return["BrowserSettings|1 access_control #0",JJ]}}class yJ extends T{constructor(t){super(),this.enabled=!1,this.allowedTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yJ).fromBinary(t,r)}static fromJson(t,r){return(new yJ).fromJson(t,r)}static fromJsonString(t,r){return(new yJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yJ,t,r)}static $(){return["MCPControls|1 enabled 8|2 allowed_tools 9*"]}}class SJ extends T{constructor(t){super(),this.sandboxing=Wt.UNSPECIFIED,this.sandboxNetworking=Qt.UNSPECIFIED,this.sandboxGit=Vt.UNSPECIFIED,this.sandboxReadBoundary=Xt.UNSPECIFIED,this.sandboxReadAllowlistPaths=[],this.sandboxingEnforcedAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SJ).fromBinary(t,r)}static fromJson(t,r){return(new SJ).fromJson(t,r)}static fromJsonString(t,r){return(new SJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SJ,t,r)}static $(){return["AutoRunSandboxingControls|1 sandboxing #0|2 sandbox_networking #1|3 sandbox_git #2|4 sandbox_read_boundary #3|5 sandbox_read_allowlist_paths 9*|6 allow_user_override_sandbox_read_allowlist 8?|7 sandboxing_enforced_available 8",Wt,Qt,Vt,Xt]}}class qJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qJ).fromBinary(t,r)}static fromJson(t,r){return(new qJ).fromJson(t,r)}static fromJsonString(t,r){return(new qJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qJ,t,r)}static $(){return["PromptDeeplinkControls|1 enabled 8"]}}class BJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BJ).fromBinary(t,r)}static fromJson(t,r){return(new BJ).fromJson(t,r)}static fromJsonString(t,r){return(new BJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BJ,t,r)}static $(){return["CommandDeeplinkControls|1 enabled 8"]}}class IJ extends T{constructor(t){super(),this.enabled=!1,this.allowPublicDeeplinks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IJ).fromBinary(t,r)}static fromJson(t,r){return(new IJ).fromJson(t,r)}static fromJsonString(t,r){return(new IJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IJ,t,r)}static $(){return["DeeplinkControls|1 enabled 8|2 allow_public_deeplinks 8"]}}class PJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PJ).fromBinary(t,r)}static fromJson(t,r){return(new PJ).fromJson(t,r)}static fromJsonString(t,r){return(new PJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PJ,t,r)}static $(){return["GithubIntegrationSettings|1 hidden 8"]}}class bJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bJ).fromBinary(t,r)}static fromJson(t,r){return(new bJ).fromJson(t,r)}static fromJsonString(t,r){return(new bJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bJ,t,r)}static $(){return["GitlabIntegrationSettings|1 hidden 8"]}}class RJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RJ).fromBinary(t,r)}static fromJson(t,r){return(new RJ).fromJson(t,r)}static fromJsonString(t,r){return(new RJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RJ,t,r)}static $(){return["BitbucketIntegrationSettings|1 hidden 8"]}}class vJ extends T{constructor(t){super(),this.hidden=!1,this.inboundInstallPolicyManagedByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vJ).fromBinary(t,r)}static fromJson(t,r){return(new vJ).fromJson(t,r)}static fromJsonString(t,r){return(new vJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vJ,t,r)}static $(){return["SlackIntegrationSettings|1 hidden 8|3 inbound_install_policy #0?|4 inbound_install_policy_managed_by_organization 8",kJ]}}class xJ extends T{constructor(t){super(),this.slackTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xJ).fromBinary(t,r)}static fromJson(t,r){return(new xJ).fromJson(t,r)}static fromJsonString(t,r){return(new xJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xJ,t,r)}static $(){return["SlackManagedWorkspaces|1 slack_team_ids 9*"]}}class kJ extends T{constructor(t){super(),this.mode=Yt.UNSPECIFIED,this.allowed=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kJ).fromBinary(t,r)}static fromJson(t,r){return(new kJ).fromJson(t,r)}static fromJsonString(t,r){return(new kJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kJ,t,r)}static $(){return["SlackInboundInstallPolicy|1 mode #0|2 allowed #1*",Yt,EJ]}}class EJ extends T{constructor(t){super(),this.principal={case:void 0},this.slackWorkspaceIds=[],this.surfaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EJ).fromBinary(t,r)}static fromJson(t,r){return(new EJ).fromJson(t,r)}static fromJsonString(t,r){return(new EJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EJ,t,r)}static $(){return["SlackInboundInstallAllowedPrincipal|1 team_id 5 principal|2 organization_id 3 principal|5 anyone 8 principal|3 slack_workspace_ids 9*|4 surfaces 9*"]}}class CJ extends T{constructor(t){super(),this.sharedDriveIds=[],this.mode=Zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CJ).fromBinary(t,r)}static fromJson(t,r){return(new CJ).fromJson(t,r)}static fromJsonString(t,r){return(new CJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CJ,t,r)}static $(){return["GoogleDriveBlockedSharedDrives|1 shared_drive_ids 9*|2 mode #0",Zt]}}class TJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TJ).fromBinary(t,r)}static fromJson(t,r){return(new TJ).fromJson(t,r)}static fromJsonString(t,r){return(new TJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TJ,t,r)}static $(){return["LinearIntegrationSettings|1 hidden 8"]}}class UJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UJ).fromBinary(t,r)}static fromJson(t,r){return(new UJ).fromJson(t,r)}static fromJsonString(t,r){return(new UJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UJ,t,r)}static $(){return["JiraIntegrationSettings|1 hidden 8"]}}class AJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AJ).fromBinary(t,r)}static fromJson(t,r){return(new AJ).fromJson(t,r)}static fromJsonString(t,r){return(new AJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AJ,t,r)}static $(){return["WorkspaceTrustControls|1 enabled 8"]}}class $J extends T{constructor(t){super(),this.enabled=!1,this.allowedVisibilities=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $J).fromBinary(t,r)}static fromJson(t,r){return(new $J).fromJson(t,r)}static fromJsonString(t,r){return(new $J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($J,t,r)}static $(){return["SharedConversationSettings|1 enabled 8|2 allowed_visibilities #0*|3 allow_public_indexing 8?",Re]}}class MJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MJ).fromBinary(t,r)}static fromJson(t,r){return(new MJ).fromJson(t,r)}static fromJsonString(t,r){return(new MJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MJ,t,r)}static $(){return["SharedCanvasSettings|1 enabled 8"]}}class OJ extends T{constructor(t){super(),this.publicVisibilityAllowed=!1,this.policy="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OJ).fromBinary(t,r)}static fromJson(t,r){return(new OJ).fromJson(t,r)}static fromJsonString(t,r){return(new OJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OJ,t,r)}static $(){return["PublicProfileSettings|1 public_visibility_allowed 8|2 policy 9"]}}class DJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DJ).fromBinary(t,r)}static fromJson(t,r){return(new DJ).fromJson(t,r)}static fromJsonString(t,r){return(new DJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DJ,t,r)}static $(){return["CursorBlameSettings|1 enabled 8"]}}class NJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NJ).fromBinary(t,r)}static fromJson(t,r){return(new NJ).fromJson(t,r)}static fromJsonString(t,r){return(new NJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NJ,t,r)}static $(){return["ProjectsSettings|1 enabled 8?"]}}class GJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GJ).fromBinary(t,r)}static fromJson(t,r){return(new GJ).fromJson(t,r)}static fromJsonString(t,r){return(new GJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GJ,t,r)}static $(){return["AppsSettings|1 enabled 8?|2 allow_public_apps 8?|3 security #0?|4 allow_api_key_access 8?",LJ]}}class LJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LJ).fromBinary(t,r)}static fromJson(t,r){return(new LJ).fromJson(t,r)}static fromJsonString(t,r){return(new LJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LJ,t,r)}static $(){return["AppsSecuritySettings|1 review_enabled 8?|2 custom_review_rules 8?|3 acknowledged_disable_review 8?|4 allow_review_overrides 8?"]}}class FJ extends T{constructor(t){super(),this.allowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FJ).fromBinary(t,r)}static fromJson(t,r){return(new FJ).fromJson(t,r)}static fromJsonString(t,r){return(new FJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FJ,t,r)}static $(){return["UserAgentStoreSkillsSyncSettings|1 allowed 8"]}}class KJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KJ).fromBinary(t,r)}static fromJson(t,r){return(new KJ).fromJson(t,r)}static fromJsonString(t,r){return(new KJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KJ,t,r)}static $(){return["GetEffectiveUserAgentStoreSkillsSettingsRequest"]}}class zJ extends T{constructor(t){super(),this.enabled=!1,this.disabledByTeamAdmin=!1,this.disabledByPrivacyMode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zJ).fromBinary(t,r)}static fromJson(t,r){return(new zJ).fromJson(t,r)}static fromJsonString(t,r){return(new zJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zJ,t,r)}static $(){return["GetEffectiveUserAgentStoreSkillsSettingsResponse|1 enabled 8|2 disabled_by_team_admin 8|3 disabled_by_privacy_mode 8"]}}class jJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jJ).fromBinary(t,r)}static fromJson(t,r){return(new jJ).fromJson(t,r)}static fromJsonString(t,r){return(new jJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jJ,t,r)}static $(){return["UpdateUserAgentStoreSkillsSettingsRequest|1 enabled 8"]}}class HJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HJ).fromBinary(t,r)}static fromJson(t,r){return(new HJ).fromJson(t,r)}static fromJsonString(t,r){return(new HJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HJ,t,r)}static $(){return["UpdateUserAgentStoreSkillsSettingsResponse"]}}class WJ extends T{constructor(t){super(),this.verificationEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WJ).fromBinary(t,r)}static fromJson(t,r){return(new WJ).fromJson(t,r)}static fromJsonString(t,r){return(new WJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WJ,t,r)}static $(){return["ExtensionSigningSettings|1 verification_enabled 8"]}}class QJ extends T{constructor(t){super(),this.cooldownHours=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QJ).fromBinary(t,r)}static fromJson(t,r){return(new QJ).fromJson(t,r)}static fromJsonString(t,r){return(new QJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QJ,t,r)}static $(){return["ExtensionInstallCooldownSettings|1 cooldown_hours 5"]}}class VJ extends T{constructor(t){super(),this.vsixInstallBlocked=!1,this.vsixInstallBypassExtensionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VJ).fromBinary(t,r)}static fromJson(t,r){return(new VJ).fromJson(t,r)}static fromJsonString(t,r){return(new VJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VJ,t,r)}static $(){return["ExtensionSideloadSettings|1 vsix_install_blocked 8|2 vsix_install_bypass_extension_ids 9*"]}}class XJ extends T{constructor(t){super(),this.disableAttribution=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XJ).fromBinary(t,r)}static fromJson(t,r){return(new XJ).fromJson(t,r)}static fromJsonString(t,r){return(new XJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XJ,t,r)}static $(){return["AttributionControls|1 disable_attribution 8"]}}class YJ extends T{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YJ).fromBinary(t,r)}static fromJson(t,r){return(new YJ).fromJson(t,r)}static fromJsonString(t,r){return(new YJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YJ,t,r)}static $(){return["TeamAdminModelRef|1 model_id 9|2 parameters #0*",ZJ]}}class ZJ extends T{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZJ).fromBinary(t,r)}static fromJson(t,r){return(new ZJ).fromJson(t,r)}static fromJsonString(t,r){return(new ZJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZJ,t,r)}static $(){return["TeamAdminModelRef.ModelParameterValue|1 id 9|2 value 9"]}}class tw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tw).fromBinary(t,r)}static fromJson(t,r){return(new tw).fromJson(t,r)}static fromJsonString(t,r){return(new tw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tw,t,r)}static $(){return["TeamAdminNewChatModelResetRule|1 source_model #0|2 target_model #0",YJ]}}class rw extends T{constructor(t){super(),this.enabled=!1,this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rw).fromBinary(t,r)}static fromJson(t,r){return(new rw).fromJson(t,r)}static fromJsonString(t,r){return(new rw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rw,t,r)}static $(){return["TeamAdminNewChatModelResetSettings|1 enabled 8|2 rules #0*",tw]}}class ew extends T{constructor(t){super(),this.permissionCeiling=tr.UNSPECIFIED,this.commandAllowlist=[],this.otherCommands=rr.UNSPECIFIED,this.commandBlocklist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ew).fromBinary(t,r)}static fromJson(t,r){return(new ew).fromJson(t,r)}static fromJsonString(t,r){return(new ew).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ew,t,r)}static $(){return["LocalToolControls|1 permission_ceiling #0|2 command_allowlist 9*|3 other_commands #1|4 file_read_write_allowed 8?|5 other_local_actions_allowed 8?|6 command_blocklist 9*",tr,rr]}}class nw extends T{constructor(t){super(),this.egressMode=er.UNSPECIFIED,this.allowlist=[],this.locked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nw).fromBinary(t,r)}static fromJson(t,r){return(new nw).fromJson(t,r)}static fromJsonString(t,r){return(new nw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nw,t,r)}static $(){return["SandNetworkControls|1 egress_mode #0|2 allowlist 9*|3 locked 8|4 apply_allowlist_to_mcp 8?|5 blocked_domains #1",er,sw]}}class sw extends T{constructor(t){super(),this.domains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sw).fromBinary(t,r)}static fromJson(t,r){return(new sw).fromJson(t,r)}static fromJsonString(t,r){return(new sw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sw,t,r)}static $(){return["SandNetworkBlockedDomains|1 domains 9*"]}}class iw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iw).fromBinary(t,r)}static fromJson(t,r){return(new iw).fromJson(t,r)}static fromJsonString(t,r){return(new iw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iw,t,r)}static $(){return["SandActionAuditSettings|1 enabled 8?"]}}class ow extends T{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],this.connectorWriteTrustedUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ow).fromBinary(t,r)}static fromJson(t,r){return(new ow).fromJson(t,r)}static fromJsonString(t,r){return(new ow).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ow,t,r)}static $(){return["SandAutoReviewControls|1 enforce_enabled 8?|2 allow_instructions 9*|3 block_instructions 9*|4 update_instructions 8?|5 rules_in_effect #0|6 connector_writes_need_approval 8?|7 connector_write_trusted_urls 9*",aw]}}class aw extends T{constructor(t){super(),this.source=uw.UNSPECIFIED,this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aw).fromBinary(t,r)}static fromJson(t,r){return(new aw).fromJson(t,r)}static fromJsonString(t,r){return(new aw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aw,t,r)}static $(){return["SandAutoReviewRulesInEffect|1 source #0|2 allow_instructions 9*|3 block_instructions 9*",uw]}}var uw=(0,a.QT)(n.proto3,C,"SandAutoReviewRulesInEffect.Source",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"TEAM_ADDS"],[3,"TEAM_REPLACES"]],1);class cw extends T{constructor(t){super(),this.mode=nr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cw).fromBinary(t,r)}static fromJson(t,r){return(new cw).fromJson(t,r)}static fromJsonString(t,r){return(new cw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cw,t,r)}static $(){return["SandLocalEgressControls|1 allowed 8?|2 mode #0",nr]}}class lw extends T{constructor(t){super(),this.resourceType="",this.minPeriodDays=0,this.maxPeriodDays=0,this.leadDays=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lw).fromBinary(t,r)}static fromJson(t,r){return(new lw).fromJson(t,r)}static fromJsonString(t,r){return(new lw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lw,t,r)}static $(){return["TeamDataRetentionPolicy|1 resource_type 9|2 period_days 5?|3 min_period_days 5|4 max_period_days 5|5 lead_days 5"]}}class mw extends T{constructor(t){super(),this.teamId=0,this.resourceType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mw).fromBinary(t,r)}static fromJson(t,r){return(new mw).fromJson(t,r)}static fromJsonString(t,r){return(new mw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mw,t,r)}static $(){return["GetTeamDataRetentionPolicyRequest|1 team_id 5|2 resource_type 9"]}}class fw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fw).fromBinary(t,r)}static fromJson(t,r){return(new fw).fromJson(t,r)}static fromJsonString(t,r){return(new fw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fw,t,r)}static $(){return["GetTeamDataRetentionPolicyResponse|1 policy #0",lw]}}class dw extends T{constructor(t){super(),this.teamId=0,this.resourceType="",this.acknowledged=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dw).fromBinary(t,r)}static fromJson(t,r){return(new dw).fromJson(t,r)}static fromJsonString(t,r){return(new dw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dw,t,r)}static $(){return["UpdateTeamDataRetentionPolicyRequest|1 team_id 5|2 resource_type 9|3 period_days 5?|4 acknowledged 8"]}}class pw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pw).fromBinary(t,r)}static fromJson(t,r){return(new pw).fromJson(t,r)}static fromJsonString(t,r){return(new pw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pw,t,r)}static $(){return["UpdateTeamDataRetentionPolicyResponse|1 policy #0",lw]}}class hw extends T{constructor(t){super(),this.allowedUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hw).fromBinary(t,r)}static fromJson(t,r){return(new hw).fromJson(t,r)}static fromJsonString(t,r){return(new hw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hw,t,r)}static $(){return["GlassSettings|1 allowed_user_ids 5*|2 allow_all_team_members 8?"]}}class gw extends T{constructor(t){super(),this.allowedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gw).fromBinary(t,r)}static fromJson(t,r){return(new gw).fromJson(t,r)}static fromJsonString(t,r){return(new gw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gw,t,r)}static $(){return["ModelAllowlistParameterRestriction|1 allowed_values 9*"]}}class _w extends T{constructor(t){super(),this.grantedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _w).fromBinary(t,r)}static fromJson(t,r){return(new _w).fromJson(t,r)}static fromJsonString(t,r){return(new _w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_w,t,r)}static $(){return["ModelAllowlistParameterGrant|1 granted_values 9*"]}}class Jw extends T{constructor(t){super(),this.enabled=!1,this.parameterRestrictions={},this.parameterGrants={},this.defaultParameterValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jw).fromBinary(t,r)}static fromJson(t,r){return(new Jw).fromJson(t,r)}static fromJsonString(t,r){return(new Jw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jw,t,r)}static $(){return["ModelAllowlistModelEntry|1 enabled 8|2 parameter_restrictions 9,#0|3 parameter_grants 9,#1|4 default_parameter_values #2*",gw,_w,ZJ]}}class ww extends T{constructor(t){super(),this.enabled=!1,this.models={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ww).fromBinary(t,r)}static fromJson(t,r){return(new ww).fromJson(t,r)}static fromJsonString(t,r){return(new ww).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ww,t,r)}static $(){return["ModelAllowlistProviderEntry|1 enabled 8|2 models 9,#0",Jw]}}class yw extends T{constructor(t){super(),this.enabled=!1,this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yw).fromBinary(t,r)}static fromJson(t,r){return(new yw).fromJson(t,r)}static fromJsonString(t,r){return(new yw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yw,t,r)}static $(){return["ModelAllowlistByokEntry|1 enabled 8|2 models 9*"]}}class Sw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sw).fromBinary(t,r)}static fromJson(t,r){return(new Sw).fromJson(t,r)}static fromJsonString(t,r){return(new Sw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sw,t,r)}static $(){return["ModelAllowlistByok|1 openai #0?|2 anthropic #0?|3 google #0?|4 azure #0?|5 bedrock #0?",yw]}}class qw extends T{constructor(t){super(),this.newProviderDefault=Bw.UNSPECIFIED,this.newModelDefault=Bw.UNSPECIFIED,this.providers={},this.firstPartyPendingModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qw).fromBinary(t,r)}static fromJson(t,r){return(new qw).fromJson(t,r)}static fromJsonString(t,r){return(new qw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qw,t,r)}static $(){return["ModelAllowlist|1 new_provider_default #0|2 new_model_default #0|3 providers 9,#1|4 byok #2?|5 new_model_default_enabled_at 3?|6 new_first_party_model_default #3?|7 can_set_first_party_default_manually 8?|8 new_first_party_model_default_enabled_at 3?|9 first_party_pending_models #4*",Bw,ww,Sw,Iw,Pw]}}var Bw=(0,a.QT)(n.proto3,C,"ModelAllowlist.DefaultBehavior",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"]],1),Iw=(0,a.QT)(n.proto3,C,"ModelAllowlist.FirstPartyModelDefault",[[0,"UNSPECIFIED"],[1,"IMMEDIATELY"],[2,"AFTER_7_DAYS"],[3,"MANUALLY"]],1);class Pw extends T{constructor(t){super(),this.mcid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pw).fromBinary(t,r)}static fromJson(t,r){return(new Pw).fromJson(t,r)}static fromJsonString(t,r){return(new Pw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pw,t,r)}static $(){return["FirstPartyPendingModel|1 mcid 9|2 enables_at 3?"]}}class bw extends T{constructor(t){super(),this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bw).fromBinary(t,r)}static fromJson(t,r){return(new bw).fromJson(t,r)}static fromJsonString(t,r){return(new bw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bw,t,r)}static $(){return["LlmGatewayTeamCredentialStatus|1 configured 8"]}}class Rw extends T{constructor(t){super(),this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rw).fromBinary(t,r)}static fromJson(t,r){return(new Rw).fromJson(t,r)}static fromJsonString(t,r){return(new Rw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rw,t,r)}static $(){return["TeamLlmGatewayCredentialStatus|1 configured 8|2 credential_version 5?|3 updated_at_epoch_millis 3?"]}}class vw extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vw).fromBinary(t,r)}static fromJson(t,r){return(new vw).fromJson(t,r)}static fromJsonString(t,r){return(new vw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vw,t,r)}static $(){return["GetTeamLlmGatewayCredentialStatusRequest|1 team_id 5"]}}class xw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xw).fromBinary(t,r)}static fromJson(t,r){return(new xw).fromJson(t,r)}static fromJsonString(t,r){return(new xw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xw,t,r)}static $(){return["GetTeamLlmGatewayCredentialStatusResponse|1 status #0",Rw]}}class kw extends T{constructor(t){super(),this.teamId=0,this.credential="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kw).fromBinary(t,r)}static fromJson(t,r){return(new kw).fromJson(t,r)}static fromJsonString(t,r){return(new kw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kw,t,r)}static $(){return["SetTeamLlmGatewayCredentialRequest|1 team_id 5|2 credential 9"]}}class Ew extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ew).fromBinary(t,r)}static fromJson(t,r){return(new Ew).fromJson(t,r)}static fromJsonString(t,r){return(new Ew).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ew,t,r)}static $(){return["SetTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class Cw extends T{constructor(t){super(),this.teamId=0,this.credential="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cw).fromBinary(t,r)}static fromJson(t,r){return(new Cw).fromJson(t,r)}static fromJsonString(t,r){return(new Cw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cw,t,r)}static $(){return["ReplaceTeamLlmGatewayCredentialRequest|1 team_id 5|2 credential 9"]}}class Tw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tw).fromBinary(t,r)}static fromJson(t,r){return(new Tw).fromJson(t,r)}static fromJsonString(t,r){return(new Tw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tw,t,r)}static $(){return["ReplaceTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class Uw extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uw).fromBinary(t,r)}static fromJson(t,r){return(new Uw).fromJson(t,r)}static fromJsonString(t,r){return(new Uw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uw,t,r)}static $(){return["ClearTeamLlmGatewayCredentialRequest|1 team_id 5"]}}class Aw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aw).fromBinary(t,r)}static fromJson(t,r){return(new Aw).fromJson(t,r)}static fromJsonString(t,r){return(new Aw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aw,t,r)}static $(){return["ClearTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class $w extends T{constructor(t){super(),this.family="",this.discoveryUrl="",this.adapter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $w).fromBinary(t,r)}static fromJson(t,r){return(new $w).fromJson(t,r)}static fromJsonString(t,r){return(new $w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($w,t,r)}static $(){return["LlmGatewayModelDiscoverySource|1 family 9|2 discovery_url 9|3 adapter 9"]}}class Mw extends T{constructor(t){super(),this.enabled=!1,this.sources=[],this.scope=cr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mw).fromBinary(t,r)}static fromJson(t,r){return(new Mw).fromJson(t,r)}static fromJsonString(t,r){return(new Mw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mw,t,r)}static $(){return["LlmGatewayModelDiscovery|1 enabled 8|2 sources #0*|3 scope #1",$w,cr]}}class Ow extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ow).fromBinary(t,r)}static fromJson(t,r){return(new Ow).fromJson(t,r)}static fromJsonString(t,r){return(new Ow).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ow,t,r)}static $(){return["UpdateTeamLlmGatewayModelDiscoveryRequest|1 team_id 5|2 model_discovery #0",Mw]}}class Dw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dw).fromBinary(t,r)}static fromJson(t,r){return(new Dw).fromJson(t,r)}static fromJsonString(t,r){return(new Dw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dw,t,r)}static $(){return["UpdateTeamLlmGatewayModelDiscoveryResponse|1 model_discovery #0",Mw]}}class Nw extends T{constructor(t){super(),this.teamId=0,this.endpoints={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nw).fromBinary(t,r)}static fromJson(t,r){return(new Nw).fromJson(t,r)}static fromJsonString(t,r){return(new Nw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nw,t,r)}static $(){return["UpdateTeamLlmGatewayProviderEndpointsRequest|1 team_id 5|2 endpoints 9,9"]}}class Gw extends T{constructor(t){super(),this.endpoints={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gw).fromBinary(t,r)}static fromJson(t,r){return(new Gw).fromJson(t,r)}static fromJsonString(t,r){return(new Gw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gw,t,r)}static $(){return["UpdateTeamLlmGatewayProviderEndpointsResponse|1 endpoints 9,9"]}}class Lw extends T{constructor(t){super(),this.enabled=!1,this.endpoints={},this.outboundModelPrefixes={},this.outboundModelRewrites={},this.audience="",this.canEnable=!1,this.authMode=or.UNSPECIFIED,this.credentialSourceStrategy=ur.UNSPECIFIED,this.routingMode=ar.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lw).fromBinary(t,r)}static fromJson(t,r){return(new Lw).fromJson(t,r)}static fromJsonString(t,r){return(new Lw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lw,t,r)}static $(){return["LlmGatewaySettings|1 enabled 8|2 endpoints 9,9|9 outbound_model_prefixes 9,9|10 outbound_model_rewrites 9,9|3 audience 9|4 routing #0|5 can_enable 8|6 auth_mode #1|7 team_credential_status #2|8 credential_source_strategy #3|11 model_discovery #4|12 routing_mode #5",Fw,or,bw,ur,Mw,ar]}}class Fw extends T{constructor(t){super(),this.providers={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fw).fromBinary(t,r)}static fromJson(t,r){return(new Fw).fromJson(t,r)}static fromJsonString(t,r){return(new Fw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fw,t,r)}static $(){return["LlmGatewayRouting|1 providers 9,#0",Kw]}}class Kw extends T{constructor(t){super(),this.enabled=!1,this.models={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kw).fromBinary(t,r)}static fromJson(t,r){return(new Kw).fromJson(t,r)}static fromJsonString(t,r){return(new Kw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kw,t,r)}static $(){return["LlmGatewayRoutingProviderEntry|1 enabled 8|2 models 9,#0",zw]}}class zw extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zw).fromBinary(t,r)}static fromJson(t,r){return(new zw).fromJson(t,r)}static fromJsonString(t,r){return(new zw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zw,t,r)}static $(){return["LlmGatewayRoutedModelEntry|1 enabled 8"]}}class jw extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jw).fromBinary(t,r)}static fromJson(t,r){return(new jw).fromJson(t,r)}static fromJsonString(t,r){return(new jw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jw,t,r)}static $(){return["AutoReviewRunModeReset|1 issued_at_ms 3"]}}class Hw extends T{constructor(t){super(),this.allowedModels=[],this.blockedModels=[],this.dotCursorProtection=!1,this.browserOriginAllowlist=[],this.networkDenylist=[],this.networkAllowlist=[],this.cloudAgentEgressAllowlist=[],this.remotePermissionsFilePaths=[],this.localPermissionsFilePath=[],this.sandGroupAccessMode=lr.UNSPECIFIED,this.memberSlackManagedWorkspaces=[],this.memberSlackManagedWorkspacesUnreadable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hw).fromBinary(t,r)}static fromJson(t,r){return(new Hw).fromJson(t,r)}static fromJsonString(t,r){return(new Hw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hw,t,r)}static $(){return["GetTeamAdminSettingsResponse|1 allowed_models 9*|2 blocked_models 9*|3 auto_run_controls #0|4 cursor_ignore_controls #1|5 dot_cursor_protection 8|6 allowed_mcp_configuration #2?|7 background_agent_settings #3?|8 cli_settings #4?|9 mcp_controls #5?|10 prompt_deeplink_controls #6?|11 command_deeplink_controls #7?|12 deeplink_controls #8?|13 github_integration_settings #9?|14 slack_integration_settings #10?|15 linear_integration_settings #11?|16 workspace_trust_controls #12?|17 gitlab_integration_settings #13?|18 browser_features 8?|23 browser_origin_allowlist 9*|19 byok_disabled 8?|20 dashboard_analytics_requires_admin 8?|21 shared_conversation_settings #14?|22 allowed_extensions 9?|24 disable_conversation_insights 8?|25 cursor_blame_settings #15?|26 network_denylist 9*|27 network_allowlist 9*|28 extension_signing_settings #16?|29 enforce_invite_domain_on_accept 8?|30 first_party_plugin_configuration #17?|31 attribution_controls #18?|32 allow_third_party_plugin_imports 8?|44 allow_user_local_plugin_imports 8?|33 glass_settings #19?|34 new_chat_model_reset_settings #20?|35 model_allowlist #21?|36 jira_integration_settings #22?|37 pull_request_preferences #23?|38 browser_settings #24?|39 cloud_agent_egress_allowlist 9*|40 mirror_sandbox_allowlist_for_egress 8?|49 auto_review #25|60 local_tool_controls #26?|64 sand_network_controls #27?|61 sand_action_audit_settings #28?|41 remote_permissions_file_path 9?|46 remote_permissions_file_paths 9*|45 local_permissions_file_path 9*|47 permissions_file_overrides_auto_run 8?|42 shared_canvas_settings #29?|43 invite_link_max_ttl_seconds 5?|48 extension_install_cooldown_settings #30?|50 public_profile_settings #31?|51 bitbucket_integration_settings #32?|52 marketplace_leaderboard_disabled 8?|53 new_chat_nudge_all_to_smart_auto 8?|54 models_auto_only 8?|55 new_chat_nudge_all_to_smart_auto_optimize_for 9?|56 restrict_invites_to_admins 8?|57 viewer_can_invite_members 8?|58 enforce_hooks_readiness 8?|59 llm_gateway #33?|62 sand_onboarding #34?|63 origin_disabled 8?|65 user_agent_store_skills_sync_settings #35?|66 auto_review_run_mode_reset #36|67 enterprise_grok_bot_trial_available 8?|68 sand_group_access_mode #37|69 sand_auto_review_controls #38?|71 remote_control_v2_policy #39|72 sand_local_egress_controls #40?|74 projects_settings #41?|75 allow_skills_cli_installs 8?|76 grok_bot_agent_email_controls #42?|77 sand_box_sudo_controls #43?|117 sand_box_vnc_controls #44?|78 sand_box_restart #45?|79 origin_allow_public_repos 8?|80 cloud_agent_group_access_mode #46?|81 allow_unlisted_plugins_and_mcp_servers 8?|82 team_list_enforced 8?|83 grok_bot_secret_forwarding_controls #47?|84 grok_bot_meetings_controls #48?|85 team_list_available 8?|86 grok_bot_pages_sharing_controls #49?|87 grok_bot_bot_messaging_controls #50?|88 member_slack_managed_workspaces #51*|89 member_slack_managed_workspaces_unreadable 8|90 apps_settings #52?|94 grok_bot_team_bot_sharing_controls #53?|91 grok_bot_sharing_admin_controls_available 8?|92 viewer_may_share_team_bots 8?|95 computer_use 8?|96 grok_bot_delegated_auth_controls #54?|97 grok_bot_delegated_auth_controls_available 8?|98 personal_api_key_creation_disabled 8?|99 cloud_agent_mcp_allowlist_applied 8?|100 grok_bot_texting_controls #55?|101 grok_bot_wall_snapshot_controls #56?|102 sand_box_sudo_not_applied_box_count 13?|103 can_control_model_access 8?|104 voice_chat_disabled 8?|105 mcp_allowlist_enabled 8?|106 mcp_servers_surfaces #57?|107 user_mcp_extensions_surfaces #57?|108 organization_network_blocklist #58|109 grok_bot_proactivity_controls #59?|110 off_mcp_server_rules_allowed 8?|111 legacy_model_allowlist #21?|112 cursor_enabled 8?|113 cursor_group_access_mode #60?|114 grok_bot_designated_bot_sharers_available 8?|115 mcp_allowlist_enabled_stored 8?|116 mcp_allowlist_rule_save_turns_on 8?|118 extension_sideload_settings #61?|119 invite_link_join_requires_approval 8?",j_,W_,V_,cJ,_J,yJ,qJ,BJ,IJ,PJ,vJ,TJ,AJ,bJ,$J,DJ,WJ,Y_,XJ,hw,rw,qw,UJ,Z_,wJ,H_,ew,nw,iw,MJ,QJ,OJ,RJ,Lw,ay,FJ,jw,lr,ow,p,cw,NJ,Xw,Qw,Vw,Ww,mr,Yw,Zw,ty,ry,xJ,GJ,ey,ny,sy,oy,Z,tu,iy,fr,VJ]}}class Ww extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ww).fromBinary(t,r)}static fromJson(t,r){return(new Ww).fromJson(t,r)}static fromJsonString(t,r){return(new Ww).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ww,t,r)}static $(){return["SandBoxRestart|1 required_at_ms 3?"]}}class Qw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qw).fromBinary(t,r)}static fromJson(t,r){return(new Qw).fromJson(t,r)}static fromJsonString(t,r){return(new Qw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qw,t,r)}static $(){return["SandBoxSudoControls|1 disallowed 8?"]}}class Vw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vw).fromBinary(t,r)}static fromJson(t,r){return(new Vw).fromJson(t,r)}static fromJsonString(t,r){return(new Vw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vw,t,r)}static $(){return["SandBoxVncControls|1 disallowed 8?"]}}class Xw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xw).fromBinary(t,r)}static fromJson(t,r){return(new Xw).fromJson(t,r)}static fromJsonString(t,r){return(new Xw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xw,t,r)}static $(){return["GrokBotAgentEmailControls|1 allowed 8?"]}}class Yw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yw).fromBinary(t,r)}static fromJson(t,r){return(new Yw).fromJson(t,r)}static fromJsonString(t,r){return(new Yw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yw,t,r)}static $(){return["GrokBotSecretForwardingControls|1 allowed 8?"]}}class Zw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zw).fromBinary(t,r)}static fromJson(t,r){return(new Zw).fromJson(t,r)}static fromJsonString(t,r){return(new Zw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zw,t,r)}static $(){return["GrokBotMeetingsControls|1 allowed 8?"]}}class ty extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ty).fromBinary(t,r)}static fromJson(t,r){return(new ty).fromJson(t,r)}static fromJsonString(t,r){return(new ty).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ty,t,r)}static $(){return["GrokBotPagesSharingControls|1 team_sharing_allowed 8?|2 team_sharing_level #0?",ir]}}class ry extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ry).fromBinary(t,r)}static fromJson(t,r){return(new ry).fromJson(t,r)}static fromJsonString(t,r){return(new ry).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ry,t,r)}static $(){return["GrokBotBotMessagingControls|1 allowed 8?"]}}class ey extends T{constructor(t){super(),this.sharing=sr.UNSPECIFIED,this.designatedSharerUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ey).fromBinary(t,r)}static fromJson(t,r){return(new ey).fromJson(t,r)}static fromJsonString(t,r){return(new ey).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ey,t,r)}static $(){return["GrokBotTeamBotSharingControls|1 sharing #0|2 designated_sharer_user_ids 3*",sr]}}class ny extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ny).fromBinary(t,r)}static fromJson(t,r){return(new ny).fromJson(t,r)}static fromJsonString(t,r){return(new ny).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ny,t,r)}static $(){return["GrokBotDelegatedAuthControls|1 allowed 8?"]}}class sy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sy).fromBinary(t,r)}static fromJson(t,r){return(new sy).fromJson(t,r)}static fromJsonString(t,r){return(new sy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sy,t,r)}static $(){return["GrokBotTextingControls|1 allowed 8?"]}}class iy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iy).fromBinary(t,r)}static fromJson(t,r){return(new iy).fromJson(t,r)}static fromJsonString(t,r){return(new iy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iy,t,r)}static $(){return["GrokBotProactivityControls|1 allowed 8?"]}}class oy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oy).fromBinary(t,r)}static fromJson(t,r){return(new oy).fromJson(t,r)}static fromJsonString(t,r){return(new oy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oy,t,r)}static $(){return["GrokBotWallSnapshotControls|1 allowed 8?"]}}class ay extends T{constructor(t){super(),this.completed=!1,this.seen=!1,this.checkedSetupChecklistItems=[],this.skippedSetupChecklistItems=[],this.hasEverCompleted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ay).fromBinary(t,r)}static fromJson(t,r){return(new ay).fromJson(t,r)}static fromJsonString(t,r){return(new ay).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ay,t,r)}static $(){return["SandOnboardingState|1 completed 8|2 seen 8|3 checked_setup_checklist_items 9*|4 skipped_setup_checklist_items 9*|5 has_ever_completed 8"]}}class uy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uy).fromBinary(t,r)}static fromJson(t,r){return(new uy).fromJson(t,r)}static fromJsonString(t,r){return(new uy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uy,t,r)}static $(){return["GetBaseTeamAdminSettingsRequest|1 team_id 5"]}}class cy extends T{constructor(t){super(),this.teamId=0,this.allowedModels=[],this.blockedModels=[],this.browserOriginAllowlist=[],this.networkDenylist=[],this.networkAllowlist=[],this.firstPartyWindowDecisionMcids=[],this.cloudAgentEgressAllowlist=[],this.remotePermissionsFilePaths=[],this.localPermissionsFilePath=[],this.sandGroupAccessEnabledGroupIds=[],this.cloudAgentGroupAccessEnabledGroupIds=[],this.cursorGroupAccessEnabledGroupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cy).fromBinary(t,r)}static fromJson(t,r){return(new cy).fromJson(t,r)}static fromJsonString(t,r){return(new cy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cy,t,r)}static $(){return["UpdateTeamAdminSettingsRequest|1 team_id 5|2 allowed_models 9*|3 blocked_models 9*|4 auto_run_controls #0|5 cursor_ignore_controls #1|6 dot_cursor_protection 8?|7 allowed_mcp_configuration #2?|8 background_agent_settings #3?|9 cli_settings #4?|10 mcp_controls #5?|11 prompt_deeplink_controls #6?|12 command_deeplink_controls #7?|13 deeplink_controls #8?|14 github_integration_settings #9?|15 slack_integration_settings #10?|16 linear_integration_settings #11?|17 workspace_trust_controls #12?|18 gitlab_integration_settings #13?|19 browser_features 8?|24 browser_origin_allowlist 9*|20 byok_disabled 8?|21 dashboard_analytics_requires_admin 8?|22 shared_conversation_settings #14?|23 allowed_extensions 9?|25 disable_conversation_insights 8?|26 cursor_blame_settings #15?|27 network_denylist 9*|28 network_allowlist 9*|29 extension_signing_settings #16?|30 enforce_invite_domain_on_accept 8?|31 first_party_plugin_configuration #17?|32 attribution_controls #18?|33 allow_third_party_plugin_imports 8?|44 allow_user_local_plugin_imports 8?|34 glass_settings #19?|59 local_tool_controls #20?|60 sand_action_audit_settings #21?|35 new_chat_model_reset_settings #22?|36 model_allowlist #23?|76 first_party_window_decision_mcids 9*|37 jira_integration_settings #24?|38 pull_request_preferences #25?|39 browser_settings #26?|40 cloud_agent_egress_allowlist 9*|41 mirror_sandbox_allowlist_for_egress 8?|88 update_cloud_agent_egress_allowlist 8?|89 update_legacy_model_lists 8?|90 update_browser_origin_allowlist 8?|91 update_network_lists 8?|49 auto_review #27|42 remote_permissions_file_path 9?|46 remote_permissions_file_paths 9*|45 local_permissions_file_path 9*|47 permissions_file_overrides_auto_run 8?|57 update_permissions_file_paths 8?|43 shared_canvas_settings #28?|48 extension_install_cooldown_settings #29?|50 public_profile_settings #30?|51 bitbucket_integration_settings #31?|52 marketplace_leaderboard_disabled 8?|53 new_chat_nudge_all_to_smart_auto 8?|54 models_auto_only 8?|55 new_chat_nudge_all_to_smart_auto_optimize_for 9?|56 enforce_hooks_readiness 8?|58 llm_gateway #32?|63 origin_disabled 8?|64 user_agent_store_skills_sync_settings #33?|65 sand_group_access_mode #34?|66 sand_group_access_enabled_group_ids 3*|67 update_sand_group_access_groups 8?|69 sand_auto_review_controls #35?|74 projects_settings #36?|75 allow_skills_cli_installs 8?|79 cloud_agent_group_access_mode #37?|80 cloud_agent_group_access_enabled_group_ids 3*|81 update_cloud_agent_group_access_groups 8?|82 allow_unlisted_plugins_and_mcp_servers 8?|83 apps_settings #38?|84 computer_use 8?|85 mcp_allowlist_enabled 8?|86 mcp_servers_surfaces #39?|87 user_mcp_extensions_surfaces #39?|92 saves_both_mcp_rule_lists 8?|93 cursor_enabled 8?|94 cursor_group_access_mode #40?|95 cursor_group_access_enabled_group_ids 3*|96 update_cursor_group_access_groups 8?|97 extension_sideload_settings #41?",j_,W_,V_,cJ,_J,yJ,qJ,BJ,IJ,PJ,vJ,TJ,AJ,bJ,$J,DJ,WJ,Y_,XJ,hw,ew,iw,rw,qw,UJ,Z_,wJ,H_,MJ,QJ,OJ,RJ,Lw,FJ,lr,ow,NJ,mr,GJ,Z,fr,VJ]}}class ly extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ly).fromBinary(t,r)}static fromJson(t,r){return(new ly).fromJson(t,r)}static fromJsonString(t,r){return(new ly).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ly,t,r)}static $(){return["UpdateTeamAdminSettingsResponse"]}}class my extends T{constructor(t){super(),this.teamId=0,this.inviteLinkMaxTtlSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new my).fromBinary(t,r)}static fromJson(t,r){return(new my).fromJson(t,r)}static fromJsonString(t,r){return(new my).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(my,t,r)}static $(){return["UpdateTeamInviteLinkTTLSettingRequest|1 team_id 5|2 invite_link_max_ttl_seconds 5"]}}class fy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fy).fromBinary(t,r)}static fromJson(t,r){return(new fy).fromJson(t,r)}static fromJsonString(t,r){return(new fy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fy,t,r)}static $(){return["UpdateTeamInviteLinkTTLSettingResponse"]}}class dy extends T{constructor(t){super(),this.teamId=0,this.restrictInvitesToAdmins=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dy).fromBinary(t,r)}static fromJson(t,r){return(new dy).fromJson(t,r)}static fromJsonString(t,r){return(new dy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dy,t,r)}static $(){return["UpdateTeamMemberInviteSettingRequest|1 team_id 5|2 restrict_invites_to_admins 8"]}}class py extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new py).fromBinary(t,r)}static fromJson(t,r){return(new py).fromJson(t,r)}static fromJsonString(t,r){return(new py).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(py,t,r)}static $(){return["UpdateTeamMemberInviteSettingResponse"]}}class hy extends T{constructor(t){super(),this.teamId=0,this.personalApiKeyCreationDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hy).fromBinary(t,r)}static fromJson(t,r){return(new hy).fromJson(t,r)}static fromJsonString(t,r){return(new hy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hy,t,r)}static $(){return["UpdateTeamPersonalApiKeyCreationSettingRequest|1 team_id 5|2 personal_api_key_creation_disabled 8"]}}class gy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gy).fromBinary(t,r)}static fromJson(t,r){return(new gy).fromJson(t,r)}static fromJsonString(t,r){return(new gy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gy,t,r)}static $(){return["UpdateTeamPersonalApiKeyCreationSettingResponse"]}}class _y extends T{constructor(t){super(),this.teamId=0,this.voiceChatDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _y).fromBinary(t,r)}static fromJson(t,r){return(new _y).fromJson(t,r)}static fromJsonString(t,r){return(new _y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_y,t,r)}static $(){return["UpdateTeamVoiceChatSettingRequest|1 team_id 5|2 voice_chat_disabled 8"]}}class Jy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jy).fromBinary(t,r)}static fromJson(t,r){return(new Jy).fromJson(t,r)}static fromJsonString(t,r){return(new Jy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jy,t,r)}static $(){return["UpdateTeamVoiceChatSettingResponse"]}}class wy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wy).fromBinary(t,r)}static fromJson(t,r){return(new wy).fromJson(t,r)}static fromJsonString(t,r){return(new wy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wy,t,r)}static $(){return["UpdateTeamDefaultMemberBillingTierRequest|1 team_id 5|2 billing_tier #0?",ot]}}class yy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yy).fromBinary(t,r)}static fromJson(t,r){return(new yy).fromJson(t,r)}static fromJsonString(t,r){return(new yy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yy,t,r)}static $(){return["UpdateTeamDefaultMemberBillingTierResponse"]}}class Sy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sy).fromBinary(t,r)}static fromJson(t,r){return(new Sy).fromJson(t,r)}static fromJsonString(t,r){return(new Sy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sy,t,r)}static $(){return["CreateTeamFreeTrialCodeRequest|1 trial_type #0?|2 code_purpose #1?|3 mint_actor 9?",dr,pr]}}class qy extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qy).fromBinary(t,r)}static fromJson(t,r){return(new qy).fromJson(t,r)}static fromJsonString(t,r){return(new qy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qy,t,r)}static $(){return["CreateTeamFreeTrialCodeResponse|1 code 9"]}}class By extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new By).fromBinary(t,r)}static fromJson(t,r){return(new By).fromJson(t,r)}static fromJsonString(t,r){return(new By).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(By,t,r)}static $(){return["SetTrialSpendLimitOverrideInternalRequest|1 team_id 5|2 override_dollars 5?|3 clear 8?|4 changed_by 9?"]}}class Iy extends T{constructor(t){super(),this.teamId=0,this.effectiveLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iy).fromBinary(t,r)}static fromJson(t,r){return(new Iy).fromJson(t,r)}static fromJsonString(t,r){return(new Iy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iy,t,r)}static $(){return["SetTrialSpendLimitOverrideInternalResponse|1 team_id 5|2 override_dollars 5?|3 effective_limit_dollars 5"]}}class Py extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Py).fromBinary(t,r)}static fromJson(t,r){return(new Py).fromJson(t,r)}static fromJsonString(t,r){return(new Py).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Py,t,r)}static $(){return["GetTrialSpendLimitInternalRequest|1 team_id 5"]}}class by extends T{constructor(t){super(),this.teamId=0,this.isTokenBasedContractTrial=!1,this.defaultLimitDollars=0,this.effectiveLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new by).fromBinary(t,r)}static fromJson(t,r){return(new by).fromJson(t,r)}static fromJsonString(t,r){return(new by).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(by,t,r)}static $(){return["GetTrialSpendLimitInternalResponse|1 team_id 5|2 is_token_based_contract_trial 8|3 override_dollars 5?|4 default_limit_dollars 5|5 effective_limit_dollars 5|6 membership_start_ms 3?|7 membership_expiration_ms 3?"]}}class Ry extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ry).fromBinary(t,r)}static fromJson(t,r){return(new Ry).fromJson(t,r)}static fromJsonString(t,r){return(new Ry).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ry,t,r)}static $(){return["GetOrganizationEnterpriseTrialExtendContextInternalRequest|1 team_id 5"]}}class vy extends T{constructor(t){super(),this.teamId=0,this.membershipType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vy).fromBinary(t,r)}static fromJson(t,r){return(new vy).fromJson(t,r)}static fromJsonString(t,r){return(new vy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vy,t,r)}static $(){return["OrganizationEnterpriseTrialTeam|1 team_id 5|2 membership_type 9|3 membership_expiration_ms 3?|4 subscription_status 9?|5 customer_id 9?"]}}class xy extends T{constructor(t){super(),this.teamId=0,this.teams=[],this.convertSelfServeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xy).fromBinary(t,r)}static fromJson(t,r){return(new xy).fromJson(t,r)}static fromJsonString(t,r){return(new xy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xy,t,r)}static $(){return["GetOrganizationEnterpriseTrialExtendContextInternalResponse|1 team_id 5|2 organization_id 3?|3 organization_name 9?|4 enterprise_trial_end_ms 3?|5 teams #0*|6 convert_self_serve_enabled 8",vy]}}class ky extends T{constructor(t){super(),this.teamId=0,this.enterpriseTrialEndMs=n.protoInt64.zero,this.denormTeamIds=[],this.convertTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ky).fromBinary(t,r)}static fromJson(t,r){return(new ky).fromJson(t,r)}static fromJsonString(t,r){return(new ky).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ky,t,r)}static $(){return["ApplyOrganizationEnterpriseTrialEndInternalRequest|1 team_id 5|2 enterprise_trial_end_ms 3|3 changed_by 9?|4 denorm_team_ids 5*|5 convert_team_ids 5*|6 convert_membership_type 9?"]}}class Ey extends T{constructor(t){super(),this.teamId=0,this.membershipType="",this.outcome="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ey).fromBinary(t,r)}static fromJson(t,r){return(new Ey).fromJson(t,r)}static fromJsonString(t,r){return(new Ey).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ey,t,r)}static $(){return["OrganizationEnterpriseTrialTeamApplyResult|1 team_id 5|2 membership_type 9|3 outcome 9|4 previous_expiration_ms 3?|5 membership_expiration_ms 3?"]}}class Cy extends T{constructor(t){super(),this.organizationId=n.protoInt64.zero,this.enterpriseTrialEndMs=n.protoInt64.zero,this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cy).fromBinary(t,r)}static fromJson(t,r){return(new Cy).fromJson(t,r)}static fromJsonString(t,r){return(new Cy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cy,t,r)}static $(){return["ApplyOrganizationEnterpriseTrialEndInternalResponse|1 organization_id 3|2 enterprise_trial_end_ms 3|3 teams #0*",Ey]}}class Ty extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ty).fromBinary(t,r)}static fromJson(t,r){return(new Ty).fromJson(t,r)}static fromJsonString(t,r){return(new Ty).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ty,t,r)}static $(){return["GetXaiUserUsageSnapshotRequest|1 xai_team_id 9?"]}}class Uy extends T{constructor(t){super(),this.product="",this.usagePercent=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uy).fromBinary(t,r)}static fromJson(t,r){return(new Uy).fromJson(t,r)}static fromJsonString(t,r){return(new Uy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uy,t,r)}static $(){return["XaiUsageProductShare|1 product 9|2 usage_percent 1"]}}class Ay extends T{constructor(t){super(),this.productUsage=[],this.prepaidBalanceWithheld=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ay).fromBinary(t,r)}static fromJson(t,r){return(new Ay).fromJson(t,r)}static fromJsonString(t,r){return(new Ay).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ay,t,r)}static $(){return["GetXaiUserUsageSnapshotResponse|1 current_period_start_ms 3?|2 current_period_end_ms 3?|3 usage_percent 1?|4 product_usage #0*|5 prepaid_balance_cents 3?|6 prepaid_balance_withheld 8",Uy]}}class $y extends T{constructor(t){super(),this.teamId=0,this.addDelayDays=0,this.hideAllNudges=!1,this.hideNonAdminNudges=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $y).fromBinary(t,r)}static fromJson(t,r){return(new $y).fromJson(t,r)}static fromJsonString(t,r){return(new $y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($y,t,r)}static $(){return["TeamOffboardingConfigInternal|1 team_id 5|2 add_delay_days 5|3 hide_all_nudges 8|4 hide_non_admin_nudges 8"]}}class My extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new My).fromBinary(t,r)}static fromJson(t,r){return(new My).fromJson(t,r)}static fromJsonString(t,r){return(new My).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(My,t,r)}static $(){return["GetTeamOffboardingConfigInternalRequest|1 team_id 5"]}}class Oy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oy).fromBinary(t,r)}static fromJson(t,r){return(new Oy).fromJson(t,r)}static fromJsonString(t,r){return(new Oy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oy,t,r)}static $(){return["GetTeamOffboardingConfigInternalResponse|1 config #0",$y]}}class Dy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dy).fromBinary(t,r)}static fromJson(t,r){return(new Dy).fromJson(t,r)}static fromJsonString(t,r){return(new Dy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dy,t,r)}static $(){return["UpdateTeamOffboardingConfigInternalRequest|1 team_id 5|2 add_delay_days 5?|3 hide_all_nudges 8?|4 hide_non_admin_nudges 8?|5 changed_by 9?"]}}class Ny extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ny).fromBinary(t,r)}static fromJson(t,r){return(new Ny).fromJson(t,r)}static fromJsonString(t,r){return(new Ny).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ny,t,r)}static $(){return["UpdateTeamOffboardingConfigInternalResponse|1 config #0",$y]}}class Gy extends T{constructor(t){super(),this.teamId=0,this.amountCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.subscriptionProductId="",this.applicableProducts=[],this.entitlements=[],this.ownership=hr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gy).fromBinary(t,r)}static fromJson(t,r){return(new Gy).fromJson(t,r)}static fromJsonString(t,r){return(new Gy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gy,t,r)}static $(){return["CreateTeamCreditGrantInternalRequest|1 team_id 5|2 amount_cents 3|3 expires_at_ms 3|4 starts_at_ms 3?|5 allowed_model_ids 9*|6 subscription_product_id 9|7 applicable_products 9*|8 show_in_client 8?|9 created_by 9?|10 entitlements 9*|11 ownership #0",hr]}}class Ly extends T{constructor(t){super(),this.grantId="",this.teamId=0,this.totalCents=n.protoInt64.zero,this.usedCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.subscriptionProductId="",this.applicableProducts=[],this.showInClient=!1,this.priority=0,this.createdAtMs=n.protoInt64.zero,this.entitlements=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ly).fromBinary(t,r)}static fromJson(t,r){return(new Ly).fromJson(t,r)}static fromJsonString(t,r){return(new Ly).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ly,t,r)}static $(){return["TeamCreditGrantInternal|1 grant_id 9|2 team_id 5|3 total_cents 3|4 used_cents 3|5 starts_at_ms 3?|6 expires_at_ms 3|7 allowed_model_ids 9*|8 subscription_product_id 9|9 applicable_products 9*|10 show_in_client 8|11 priority 5|12 created_at_ms 3|13 source_type 9?|14 organization_id 9?|15 entitlements 9*"]}}class Fy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fy).fromBinary(t,r)}static fromJson(t,r){return(new Fy).fromJson(t,r)}static fromJsonString(t,r){return(new Fy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fy,t,r)}static $(){return["CreateTeamCreditGrantInternalResponse|1 grant #0",Ly]}}class Ky extends T{constructor(t){super(),this.teamId=0,this.includeExpired=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ky).fromBinary(t,r)}static fromJson(t,r){return(new Ky).fromJson(t,r)}static fromJsonString(t,r){return(new Ky).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ky,t,r)}static $(){return["ListTeamCreditGrantsInternalRequest|1 team_id 5|2 include_expired 8"]}}class zy extends T{constructor(t){super(),this.grants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zy).fromBinary(t,r)}static fromJson(t,r){return(new zy).fromJson(t,r)}static fromJsonString(t,r){return(new zy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zy,t,r)}static $(){return["ListTeamCreditGrantsInternalResponse|1 grants #0*",Ly]}}class jy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jy).fromBinary(t,r)}static fromJson(t,r){return(new jy).fromJson(t,r)}static fromJsonString(t,r){return(new jy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jy,t,r)}static $(){return["CreateTeamsTrialV2ReferralCodeRequest"]}}class Hy extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hy).fromBinary(t,r)}static fromJson(t,r){return(new Hy).fromJson(t,r)}static fromJsonString(t,r){return(new Hy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hy,t,r)}static $(){return["CreateTeamsTrialV2ReferralCodeResponse|1 code 9"]}}class Wy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wy).fromBinary(t,r)}static fromJson(t,r){return(new Wy).fromJson(t,r)}static fromJsonString(t,r){return(new Wy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wy,t,r)}static $(){return["GetTeamAnalyticsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 version 9?"]}}class Qy extends T{constructor(t){super(),this.dailyMetrics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qy).fromBinary(t,r)}static fromJson(t,r){return(new Qy).fromJson(t,r)}static fromJsonString(t,r){return(new Qy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qy,t,r)}static $(){return["GetTeamAnalyticsResponse|1 daily_metrics #0*|2 period #1|3 active_users #2",nS,eS,rS]}}class Vy extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vy).fromBinary(t,r)}static fromJson(t,r){return(new Vy).fromJson(t,r)}static fromJsonString(t,r){return(new Vy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vy,t,r)}static $(){return["GetUserAnalyticsRequest|1 team_id 5|2 user_id 5|3 start_date 3?|4 end_date 3?|5 version 9?|6 daily_metrics_only 8?"]}}class Xy extends T{constructor(t){super(),this.dailyMetrics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xy).fromBinary(t,r)}static fromJson(t,r){return(new Xy).fromJson(t,r)}static fromJsonString(t,r){return(new Xy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xy,t,r)}static $(){return["GetUserAnalyticsResponse|1 daily_metrics #0*|2 period #1|3 apply_lines_rank 5?|4 tabs_accepted_rank 5?|5 total_team_members 5?|6 total_apply_lines 5?|7 team_average_apply_lines 5?|8 total_tabs_accepted 5?|9 team_average_tabs_accepted 5?|10 total_members_in_team 5?",nS,eS]}}class Yy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yy).fromBinary(t,r)}static fromJson(t,r){return(new Yy).fromJson(t,r)}static fromJsonString(t,r){return(new Yy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yy,t,r)}static $(){return["GetTeamRawDataRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 version 9?"]}}class Zy extends T{constructor(t){super(),this.data=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zy).fromBinary(t,r)}static fromJson(t,r){return(new Zy).fromJson(t,r)}static fromJsonString(t,r){return(new Zy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zy,t,r)}static $(){return["GetTeamRawDataResponse|1 data #0*|2 period #1",tS,eS]}}class tS extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.userId=0,this.isActive=!1,this.totalLinesAdded=0,this.totalLinesDeleted=0,this.acceptedLinesAdded=0,this.acceptedLinesDeleted=0,this.totalApplies=0,this.totalAccepts=0,this.totalRejects=0,this.totalTabsShown=0,this.totalTabsAccepted=0,this.composerRequests=0,this.chatRequests=0,this.agentRequests=0,this.cmdkUsages=0,this.subscriptionIncludedReqs=0,this.apiKeyReqs=0,this.usageBasedReqs=0,this.bugbotUsages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tS).fromBinary(t,r)}static fromJson(t,r){return(new tS).fromJson(t,r)}static fromJsonString(t,r){return(new tS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tS,t,r)}static $(){return["RawUserData|1 date 3|2 user_id 5|3 is_active 8|4 total_lines_added 5|5 total_lines_deleted 5|6 accepted_lines_added 5|7 accepted_lines_deleted 5|8 total_applies 5|9 total_accepts 5|10 total_rejects 5|11 total_tabs_shown 5|12 total_tabs_accepted 5|13 composer_requests 5|14 chat_requests 5|15 agent_requests 5|16 cmdk_usages 5|17 subscription_included_reqs 5|18 api_key_reqs 5|19 usage_based_reqs 5|20 bugbot_usages 5|21 most_used_model 9?|22 apply_most_used_extension 9?|23 tab_most_used_extension 9?|24 client_version 9?|25 email 9?"]}}class rS extends T{constructor(t){super(),this.current=0,this.previous=0,this.percentChange=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rS).fromBinary(t,r)}static fromJson(t,r){return(new rS).fromJson(t,r)}static fromJsonString(t,r){return(new rS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rS,t,r)}static $(){return["ActiveUsers|1 current 5|2 previous 5|3 percent_change 5"]}}class eS extends T{constructor(t){super(),this.startDate=n.protoInt64.zero,this.endDate=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eS).fromBinary(t,r)}static fromJson(t,r){return(new eS).fromJson(t,r)}static fromJsonString(t,r){return(new eS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eS,t,r)}static $(){return["AnalyticsPeriod|1 start_date 3|2 end_date 3"]}}class nS extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.activeUsers=0,this.linesAdded=0,this.linesDeleted=0,this.acceptedLinesAdded=0,this.acceptedLinesDeleted=0,this.totalApplies=0,this.totalAccepts=0,this.totalRejects=0,this.totalTabsShown=0,this.totalTabsAccepted=0,this.composerRequests=0,this.chatRequests=0,this.agentRequests=0,this.cmdkUsages=0,this.subscriptionIncludedReqs=0,this.apiKeyReqs=0,this.usageBasedReqs=0,this.bugbotUsages=0,this.modelUsage=[],this.extensionUsage=[],this.tabExtensionUsage=[],this.clientVersionUsage=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nS).fromBinary(t,r)}static fromJson(t,r){return(new nS).fromJson(t,r)}static fromJsonString(t,r){return(new nS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nS,t,r)}static $(){return["DailyMetrics|1 date 3|2 active_users 5|3 lines_added 5|4 lines_deleted 5|5 accepted_lines_added 5|6 accepted_lines_deleted 5|7 total_applies 5|8 total_accepts 5|9 total_rejects 5|10 total_tabs_shown 5|11 total_tabs_accepted 5|12 composer_requests 5|13 chat_requests 5|14 agent_requests 5|15 cmdk_usages 5|16 subscription_included_reqs 5|17 api_key_reqs 5|18 usage_based_reqs 5|19 bugbot_usages 5|20 model_usage #0*|21 extension_usage #0*|22 tab_extension_usage #0*|23 client_version_usage #0*",sS]}}class sS extends T{constructor(t){super(),this.name="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sS).fromBinary(t,r)}static fromJson(t,r){return(new sS).fromJson(t,r)}static fromJsonString(t,r){return(new sS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sS,t,r)}static $(){return["StringCount|1 name 9|2 count 5"]}}class iS extends T{constructor(t){super(),this.teamId=0,this.teamRepoType="",this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iS).fromBinary(t,r)}static fromJson(t,r){return(new iS).fromJson(t,r)}static fromJsonString(t,r){return(new iS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iS,t,r)}static $(){return["SetTeamRepoTypeRequest|1 team_id 5|2 team_repo_type 9|3 repo_id 5"]}}class oS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oS).fromBinary(t,r)}static fromJson(t,r){return(new oS).fromJson(t,r)}static fromJsonString(t,r){return(new oS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oS,t,r)}static $(){return["SetTeamRepoTypeResponse"]}}class aS extends T{constructor(t){super(),this.conversationId="",this.timestampBeforeRequest=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aS).fromBinary(t,r)}static fromJson(t,r){return(new aS).fromJson(t,r)}static fromJsonString(t,r){return(new aS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aS,t,r)}static $(){return["GetClientUsageDataRequest|1 conversation_id 9|2 timestamp_before_request 5"]}}class uS extends T{constructor(t){super(),this.itemsWithCost=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uS).fromBinary(t,r)}static fromJson(t,r){return(new uS).fromJson(t,r)}static fromJsonString(t,r){return(new uS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uS,t,r)}static $(){return["GetClientUsageDataResponse|1 items_with_cost #0*",cS]}}class cS extends T{constructor(t){super(),this.name="",this.costInCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cS).fromBinary(t,r)}static fromJson(t,r){return(new cS).fromJson(t,r)}static fromJsonString(t,r){return(new cS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cS,t,r)}static $(){return["GetClientUsageDataResponse.NameToCost|1 name 9|2 cost_in_cents 5"]}}class lS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lS).fromBinary(t,r)}static fromJson(t,r){return(new lS).fromJson(t,r)}static fromJsonString(t,r){return(new lS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lS,t,r)}static $(){return["GetCurrentPeriodUsageRequest|1 team_id 5?|2 include_pooled_usage 8?|3 personal_scope 8?"]}}class mS extends T{constructor(t){super(),this.billingCycleStart=n.protoInt64.zero,this.billingCycleEnd=n.protoInt64.zero,this.enabled=!1,this.displayMessage="",this.autoBucketModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mS).fromBinary(t,r)}static fromJson(t,r){return(new mS).fromJson(t,r)}static fromJsonString(t,r){return(new mS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mS,t,r)}static $(){return["GetCurrentPeriodUsageResponse|1 billing_cycle_start 3|2 billing_cycle_end 3|3 plan_usage #0|4 spend_limit_usage #1|5 display_threshold 5?|6 enabled 8|7 display_message 9|8 free_best_of_n_promotion #2?|11 auto_model_selected_display_message 9?|12 named_model_selected_display_message 9?|13 auto_bucket_models 9*",fS,dS,pS]}}class fS extends T{constructor(t){super(),this.totalSpend=0,this.includedSpend=0,this.bonusSpend=0,this.remaining=0,this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fS).fromBinary(t,r)}static fromJson(t,r){return(new fS).fromJson(t,r)}static fromJsonString(t,r){return(new fS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.PlanUsage|1 total_spend 5|2 included_spend 5|3 bonus_spend 5|4 remaining 5|5 limit 5|6 remaining_bonus 8?|7 bonus_tooltip 9?|8 auto_spend 5?|9 api_spend 5?|10 auto_limit 5?|11 api_limit 5?|12 auto_percent_used 1?|13 api_percent_used 1?|14 total_percent_used 1?"]}}class dS extends T{constructor(t){super(),this.totalSpend=0,this.individualUsed=0,this.individualRemaining=0,this.limitType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dS).fromBinary(t,r)}static fromJson(t,r){return(new dS).fromJson(t,r)}static fromJsonString(t,r){return(new dS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.SpendLimitUsage|1 total_spend 5|2 pooled_limit 3?|3 pooled_used 5?|4 pooled_remaining 3?|5 individual_limit 5?|6 individual_used 5|7 individual_remaining 5|8 limit_type 9|9 overall_limit 5?|10 overall_used 5?|11 overall_remaining 5?"]}}class pS extends T{constructor(t){super(),this.trialsUsed=0,this.trialsRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pS).fromBinary(t,r)}static fromJson(t,r){return(new pS).fromJson(t,r)}static fromJsonString(t,r){return(new pS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.FreeBestOfNPromotion|1 trials_used 5|2 trials_remaining 5"]}}class hS extends T{constructor(t){super(),this.id="",this.kind=gr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hS).fromBinary(t,r)}static fromJson(t,r){return(new hS).fromJson(t,r)}static fromJsonString(t,r){return(new hS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hS,t,r)}static $(){return["UnifiedBankedUsageReset|1 id 9|2 created_at #0|3 expires_at #0?|4 kind #1",n.Timestamp,gr]}}class gS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gS).fromBinary(t,r)}static fromJson(t,r){return(new gS).fromJson(t,r)}static fromJsonString(t,r){return(new gS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gS,t,r)}static $(){return["ListUnifiedBankedUsageResetsRequest"]}}class _S extends T{constructor(t){super(),this.resets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _S).fromBinary(t,r)}static fromJson(t,r){return(new _S).fromJson(t,r)}static fromJsonString(t,r){return(new _S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_S,t,r)}static $(){return["ListUnifiedBankedUsageResetsResponse|1 resets #0*|2 next_redeem_allowed_at #1?|3 next_team_redeem_allowed_at #1?|4 next_user_redeem_allowed_at #1?",hS,n.Timestamp]}}class JS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JS).fromBinary(t,r)}static fromJson(t,r){return(new JS).fromJson(t,r)}static fromJsonString(t,r){return(new JS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JS,t,r)}static $(){return["RedeemUnifiedBankedUsageResetRequest"]}}class wS extends T{constructor(t){super(),this.remaining=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wS).fromBinary(t,r)}static fromJson(t,r){return(new wS).fromJson(t,r)}static fromJsonString(t,r){return(new wS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wS,t,r)}static $(){return["RedeemUnifiedBankedUsageResetResponse|1 redeemed #0|2 redeemed_at #1|3 next_redeem_allowed_at #1|4 remaining #0*",hS,n.Timestamp]}}class yS extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yS).fromBinary(t,r)}static fromJson(t,r){return(new yS).fromJson(t,r)}static fromJsonString(t,r){return(new yS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yS,t,r)}static $(){return["ListPendingUserAccessRequestsRequest|1 team_id 5"]}}class SS extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.kind=_r.UNSPECIFIED,this.requesterUserId=0,this.requesterName="",this.requesterEmail="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SS).fromBinary(t,r)}static fromJson(t,r){return(new SS).fromJson(t,r)}static fromJsonString(t,r){return(new SS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SS,t,r)}static $(){return["PendingUserAccessRequest|1 id 3|2 kind #0|3 requester_user_id 5|4 requester_name 9|5 requester_email 9|6 requested_at #1|7 summary 9",_r,n.Timestamp]}}class qS extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qS).fromBinary(t,r)}static fromJson(t,r){return(new qS).fromJson(t,r)}static fromJsonString(t,r){return(new qS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qS,t,r)}static $(){return["ListPendingUserAccessRequestsResponse|1 requests #0*",SS]}}class BS extends T{constructor(t){super(),this.refresh=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BS).fromBinary(t,r)}static fromJson(t,r){return(new BS).fromJson(t,r)}static fromJsonString(t,r){return(new BS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BS,t,r)}static $(){return["GetBonfireStatusRequest|1 refresh 8"]}}class IS extends T{constructor(t){super(),this.eligible=!1,this.inviteUrl="",this.inviteCode="",this.pendingRewardCount=0,this.availableResetCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IS).fromBinary(t,r)}static fromJson(t,r){return(new IS).fromJson(t,r)}static fromJsonString(t,r){return(new IS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IS,t,r)}static $(){return["GetBonfireStatusResponse|1 eligible 8|2 invite_url 9|3 invite_code 9|4 pending_reward_count 5|5 available_reset_count 5"]}}class PS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PS).fromBinary(t,r)}static fromJson(t,r){return(new PS).fromJson(t,r)}static fromJsonString(t,r){return(new PS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PS,t,r)}static $(){return["CreateBonfireInviteRequest"]}}class bS extends T{constructor(t){super(),this.inviteUrl="",this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bS).fromBinary(t,r)}static fromJson(t,r){return(new bS).fromJson(t,r)}static fromJsonString(t,r){return(new bS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bS,t,r)}static $(){return["CreateBonfireInviteResponse|1 invite_url 9|2 invite_code 9"]}}class RS extends T{constructor(t){super(),this.inviteeEmail="",this.idempotencyKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RS).fromBinary(t,r)}static fromJson(t,r){return(new RS).fromJson(t,r)}static fromJsonString(t,r){return(new RS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RS,t,r)}static $(){return["SendBonfireInviteRequest|1 invitee_email 9|2 idempotency_key 9"]}}class vS extends T{constructor(t){super(),this.outcome=xS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vS).fromBinary(t,r)}static fromJson(t,r){return(new vS).fromJson(t,r)}static fromJsonString(t,r){return(new vS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vS,t,r)}static $(){return["SendBonfireInviteResponse|1 outcome #0|2 retry_after #1?",xS,n.Timestamp]}}var xS=(0,a.QT)(n.proto3,C,"SendBonfireInviteResponse.Outcome",[[0,"UNSPECIFIED"],[1,"SENT"],[2,"RATE_LIMITED"],[3,"NOT_ELIGIBLE"],[4,"INVALID_EMAIL"],[5,"UNAVAILABLE"],[6,"SELF_INVITE"],[7,"UNCONFIRMED"]],1);class kS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kS).fromBinary(t,r)}static fromJson(t,r){return(new kS).fromJson(t,r)}static fromJsonString(t,r){return(new kS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kS,t,r)}static $(){return["GetPlanInfoRequest"]}}class ES extends T{constructor(t){super(),this.isMerged=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ES).fromBinary(t,r)}static fromJson(t,r){return(new ES).fromJson(t,r)}static fromJsonString(t,r){return(new ES).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ES,t,r)}static $(){return["GetPlanInfoResponse|1 plan_info #0?|2 next_upgrade #1?|3 is_merged 8",TS,$S]}}var CS=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.IncludedUsagePeriod",[[0,"UNSPECIFIED"],[1,"MONTHLY"],[2,"WEEKLY"]],1);class TS extends T{constructor(t){super(),this.planName="",this.includedAmountCents=0,this.planOwner=US.UNSPECIFIED,this.includedUsagePeriod=CS.UNSPECIFIED,this.standing=AS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TS).fromBinary(t,r)}static fromJson(t,r){return(new TS).fromJson(t,r)}static fromJsonString(t,r){return(new TS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TS,t,r)}static $(){return["GetPlanInfoResponse.PlanInfo|1 plan_name 9|2 included_amount_cents 5|3 price 9?|4 billing_cycle_end 3?|5 plan_owner #0|6 included_usage_period #1|7 included_usage_resets_at 3?|8 cancels_at 3?|9 trial_ends_at 3?|10 grok_bot_trial_ends_at 3?|11 standing #2|12 renews_at 3?|13 restore_by 3?",US,CS,AS]}}var US=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.PlanInfo.PlanOwner",[[0,"UNSPECIFIED"],[1,"STRIPE"],[2,"APPLE"]],1),AS=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.PlanInfo.Standing",[[0,"UNSPECIFIED"],[1,"PAST_DUE"],[2,"GRACE"],[3,"EXPIRING"],[4,"CANCELED"],[5,"CANCELED_IN_TRIAL"]],1);class $S extends T{constructor(t){super(),this.tier="",this.name="",this.includedAmountCents=0,this.price="",this.description="",this.includedUsagePeriod=CS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $S).fromBinary(t,r)}static fromJson(t,r){return(new $S).fromJson(t,r)}static fromJsonString(t,r){return(new $S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($S,t,r)}static $(){return["GetPlanInfoResponse.NextUpgrade|1 tier 9|2 name 9|3 included_amount_cents 5|4 price 9|5 description 9|6 dashboard_action #0?|7 included_usage_period #1",o.bV,CS]}}class MS extends T{constructor(t){super(),this.signedTransactionJws="",this.productId="",this.appAccountToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MS).fromBinary(t,r)}static fromJson(t,r){return(new MS).fromJson(t,r)}static fromJsonString(t,r){return(new MS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MS,t,r)}static $(){return["VerifyAppleTransactionRequest|1 signed_transaction_jws 9|2 product_id 9|3 app_account_token 9|4 verification_provenance #0?",Jr]}}class OS extends T{constructor(t){super(),this.tier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OS).fromBinary(t,r)}static fromJson(t,r){return(new OS).fromJson(t,r)}static fromJsonString(t,r){return(new OS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OS,t,r)}static $(){return["VerifyAppleTransactionResponse|1 tier 9"]}}class DS extends T{constructor(t){super(),this.purchaseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DS).fromBinary(t,r)}static fromJson(t,r){return(new DS).fromJson(t,r)}static fromJsonString(t,r){return(new DS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DS,t,r)}static $(){return["VerifyGooglePlayPurchaseRequest|1 purchase_token 9|2 product_id 9?|3 client_obfuscated_account_id 9?|4 verification_provenance #0?",Jr]}}class NS extends T{constructor(t){super(),this.tier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NS).fromBinary(t,r)}static fromJson(t,r){return(new NS).fromJson(t,r)}static fromJsonString(t,r){return(new NS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NS,t,r)}static $(){return["VerifyGooglePlayPurchaseResponse|1 tier 9|2 pending_tier 9?|3 pending_tier_starts_at_ms 3?"]}}class GS extends T{constructor(t){super(),this.purpose=LS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GS).fromBinary(t,r)}static fromJson(t,r){return(new GS).fromJson(t,r)}static fromJsonString(t,r){return(new GS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GS,t,r)}static $(){return["GetGooglePlayBillingAccountIdRequest|1 product_id 9?|2 purpose #0",LS]}}var LS=(0,a.QT)(n.proto3,C,"GetGooglePlayBillingAccountIdRequest.Purpose",[[0,"UNSPECIFIED"],[1,"LEGACY"],[2,"COMMERCE"]],1);class FS extends T{constructor(t){super(),this.obfuscatedAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FS).fromBinary(t,r)}static fromJson(t,r){return(new FS).fromJson(t,r)}static fromJsonString(t,r){return(new FS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FS,t,r)}static $(){return["GetGooglePlayBillingAccountIdResponse|1 obfuscated_account_id 9"]}}class KS extends T{constructor(t){super(),this.googlePurchaseTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KS).fromBinary(t,r)}static fromJson(t,r){return(new KS).fromJson(t,r)}static fromJsonString(t,r){return(new KS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KS,t,r)}static $(){return["RestoreCommerceStorePurchasesRequest|1 google_purchase_tokens 9*"]}}class zS extends T{constructor(t){super(),this.googlePurchaseToken="",this.outcome=wr.UNSPECIFIED,this.errorCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zS).fromBinary(t,r)}static fromJson(t,r){return(new zS).fromJson(t,r)}static fromJsonString(t,r){return(new zS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zS,t,r)}static $(){return["RestoredCommerceStorePurchase|1 google_purchase_token 9|2 outcome #0|3 error_code 9",wr]}}class jS extends T{constructor(t){super(),this.purchases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jS).fromBinary(t,r)}static fromJson(t,r){return(new jS).fromJson(t,r)}static fromJsonString(t,r){return(new jS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jS,t,r)}static $(){return["RestoreCommerceStorePurchasesResponse|1 purchases #0*",zS]}}class HS extends T{constructor(t){super(),this.purchaseToken="",this.clientState=yr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HS).fromBinary(t,r)}static fromJson(t,r){return(new HS).fromJson(t,r)}static fromJsonString(t,r){return(new HS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HS,t,r)}static $(){return["GooglePlayPurchaseTokenInventoryItem|1 purchase_token 9|2 product_id 9?|3 client_state #0",yr]}}class WS extends T{constructor(t){super(),this.packageName="",this.items=[],this.trigger=Sr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WS).fromBinary(t,r)}static fromJson(t,r){return(new WS).fromJson(t,r)}static fromJsonString(t,r){return(new WS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WS,t,r)}static $(){return["InventoryGooglePlayPurchaseTokensRequest|1 package_name 9|2 items #0*|3 trigger #1",HS,Sr]}}class QS extends T{constructor(t){super(),this.submittedCount=0,this.retainedCount=0,this.rejectedCount=0,this.unavailableCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QS).fromBinary(t,r)}static fromJson(t,r){return(new QS).fromJson(t,r)}static fromJsonString(t,r){return(new QS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QS,t,r)}static $(){return["InventoryGooglePlayPurchaseTokensResponse|1 submitted_count 13|2 retained_count 13|3 rejected_count 13|4 unavailable_count 13"]}}class VS extends T{constructor(t){super(),this.packageName="",this.purchaseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VS).fromBinary(t,r)}static fromJson(t,r){return(new VS).fromJson(t,r)}static fromJsonString(t,r){return(new VS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VS,t,r)}static $(){return["InspectGooglePlaySubscriptionInternalRequest|1 package_name 9|2 purchase_token 9"]}}class XS extends T{constructor(t){super(),this.subscriptionJson="",this.ownerMismatch=!1,this.orderLookupStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XS).fromBinary(t,r)}static fromJson(t,r){return(new XS).fromJson(t,r)}static fromJsonString(t,r){return(new XS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XS,t,r)}static $(){return["InspectGooglePlaySubscriptionInternalResponse|1 subscription_json 9|2 token_owner #0?|3 binding_owner #0?|4 ledger_subscription #1?|5 owner_mismatch 8|6 order_json 9?|7 order_lookup_status 9",oq,aq]}}class YS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YS).fromBinary(t,r)}static fromJson(t,r){return(new YS).fromJson(t,r)}static fromJsonString(t,r){return(new YS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YS,t,r)}static $(){return["InspectGooglePlayTransactionsInternalRequest|1 user_id 3?|2 order_id 9?"]}}class ZS extends T{constructor(t){super(),this.diagnosticsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZS).fromBinary(t,r)}static fromJson(t,r){return(new ZS).fromJson(t,r)}static fromJsonString(t,r){return(new ZS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZS,t,r)}static $(){return["InspectGooglePlayTransactionsInternalResponse|1 diagnostics_json 9"]}}class tq extends T{constructor(t){super(),this.title="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tq).fromBinary(t,r)}static fromJson(t,r){return(new tq).fromJson(t,r)}static fromJsonString(t,r){return(new tq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tq,t,r)}static $(){return["TestPushCustomContent|1 title 9|2 subtitle 9?|3 body 9|4 type 9?|5 data_json 9?"]}}class rq extends T{constructor(t){super(),this.agentName="",this.awaitingUserResponse=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rq).fromBinary(t,r)}static fromJson(t,r){return(new rq).fromJson(t,r)}static fromJsonString(t,r){return(new rq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rq,t,r)}static $(){return["TestPushSandAgentFinished|1 agent_name 9|2 message_preview 9?|3 awaiting_user_response 8"]}}class eq extends T{constructor(t){super(),this.target={case:void 0},this.platform=Br.UNSPECIFIED,this.scenario=qr.UNSPECIFIED,this.send=!1,this.bypassTypeAllowlist=!1,this.bypassStatsigGate=!1,this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eq).fromBinary(t,r)}static fromJson(t,r){return(new eq).fromJson(t,r)}static fromJsonString(t,r){return(new eq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eq,t,r)}static $(){return["SendTestPushNotificationInternalRequest|1 user_id 3 target|2 email 9 target|3 platform #0|4 scenario #1|5 custom #2?|6 bc_id 9?|7 send 8|8 bypass_type_allowlist 8|9 bypass_statsig_gate 8|10 apps #3*|11 sand_agent_finished #4?|12 agent_id 9?|13 task_id 9?",Br,qr,tq,Ir,rq]}}class nq extends T{constructor(t){super(),this.tokenId=n.protoInt64.zero,this.platform="",this.app="",this.deviceIdPrefix="",this.outcome="",this.lane=Ir.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nq).fromBinary(t,r)}static fromJson(t,r){return(new nq).fromJson(t,r)}static fromJsonString(t,r){return(new nq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nq,t,r)}static $(){return["TestPushTokenResult|1 token_id 3|2 platform 9|3 app 9|4 bundle_id 9?|5 device_id_prefix 9|6 client_version 9?|7 outcome 9|8 error_code 9?|9 lane #0",Ir]}}class sq extends T{constructor(t){super(),this.app=Ir.UNSPECIFIED,this.outcome="",this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sq).fromBinary(t,r)}static fromJson(t,r){return(new sq).fromJson(t,r)}static fromJsonString(t,r){return(new sq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sq,t,r)}static $(){return["TestPushLaneOutcome|1 app #0|2 outcome 9|3 warnings 9*",Ir]}}class iq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.email="",this.tokens=[],this.payloadJson="",this.iosOutcome="",this.androidOutcome="",this.lanes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iq).fromBinary(t,r)}static fromJson(t,r){return(new iq).fromJson(t,r)}static fromJsonString(t,r){return(new iq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iq,t,r)}static $(){return["SendTestPushNotificationInternalResponse|1 user_id 3|2 email 9|3 tokens #0*|4 payload_json 9|5 ios_outcome 9|6 android_outcome 9|7 lanes #1*",nq,sq]}}class oq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.authId="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oq).fromBinary(t,r)}static fromJson(t,r){return(new oq).fromJson(t,r)}static fromJsonString(t,r){return(new oq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oq,t,r)}static $(){return["GooglePlayInspectedCursorAccount|1 user_id 3|2 auth_id 9|3 email 9"]}}class aq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.status="",this.tier="",this.productId="",this.startedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.autoRenewEnabled=!1,this.acknowledgementState="",this.lastVerifiedAtMs=n.protoInt64.zero,this.purchaseTokenHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aq).fromBinary(t,r)}static fromJson(t,r){return(new aq).fromJson(t,r)}static fromJsonString(t,r){return(new aq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aq,t,r)}static $(){return["GooglePlayInspectedLedgerSubscription|1 user_id 3|2 status 9|3 tier 9|4 product_id 9|5 base_plan_id 9?|6 pending_product_id 9?|7 pending_tier 9?|8 started_at_ms 3|9 expires_at_ms 3|10 auto_renew_enabled 8|11 acknowledgement_state 9|12 acknowledged_at_ms 3?|13 last_verified_at_ms 3|14 purchase_token_hash 9|15 linked_purchase_token_hash 9?"]}}class uq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uq).fromBinary(t,r)}static fromJson(t,r){return(new uq).fromJson(t,r)}static fromJsonString(t,r){return(new uq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uq,t,r)}static $(){return["GetCursorReviewEntitlementRequest"]}}class cq extends T{constructor(t){super(),this.subject={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cq).fromBinary(t,r)}static fromJson(t,r){return(new cq).fromJson(t,r)}static fromJsonString(t,r){return(new cq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cq,t,r)}static $(){return["CursorReviewEntitlementScope|1 team_id 5 subject|2 cursor_user_id 9 subject"]}}class lq extends T{constructor(t){super(),this.eligibleForCursorReview=!1,this.billingContext=mq.UNSPECIFIED,this.reason=fq.UNSPECIFIED,this.eligibleForOriginReview=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lq).fromBinary(t,r)}static fromJson(t,r){return(new lq).fromJson(t,r)}static fromJsonString(t,r){return(new lq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lq,t,r)}static $(){return["GetCursorReviewEntitlementResponse|1 eligible_for_cursor_review 8|3 billing_context #0|4 reason #1|5 team_id 5?|7 scope #2?|8 eligible_for_origin_review 8",mq,fq,cq]}}var mq=(0,a.QT)(n.proto3,C,"GetCursorReviewEntitlementResponse.BillingContext",[[0,"UNSPECIFIED"],[1,"INDIVIDUAL"],[2,"TEAM"],[3,"ENTERPRISE"]],1),fq=(0,a.QT)(n.proto3,C,"GetCursorReviewEntitlementResponse.Reason",[[0,"UNSPECIFIED"],[1,"OK"],[2,"REQUIRES_TEAM_OR_ENTERPRISE"],[3,"CURSOR_REVIEW_DISABLED"],[4,"REQUIRES_PAID_PLAN"],[5,"CURSOR_IDENTITY_UNAVAILABLE"]],1);class dq extends T{constructor(t){super(),this.query="",this.includeTeamBots=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dq).fromBinary(t,r)}static fromJson(t,r){return(new dq).fromJson(t,r)}static fromJsonString(t,r){return(new dq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dq,t,r)}static $(){return["SearchOriginReviewPeopleRequest|1 query 9|2 team_id 5?|3 limit 5?|4 include_team_bots 8"]}}class pq extends T{constructor(t){super(),this.login="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pq).fromBinary(t,r)}static fromJson(t,r){return(new pq).fromJson(t,r)}static fromJsonString(t,r){return(new pq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pq,t,r)}static $(){return["OriginReviewGithubIdentity|1 login 9|2 database_id 9?|3 node_id 9?"]}}class hq extends T{constructor(t){super(),this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hq).fromBinary(t,r)}static fromJson(t,r){return(new hq).fromJson(t,r)}static fromJsonString(t,r){return(new hq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hq,t,r)}static $(){return["OriginReviewPersonRef|1 cursor_user_id 9?|2 display_name 9|3 avatar_url 9?|4 github #0?|5 service_account_id 9?",pq]}}class gq extends T{constructor(t){super(),this.people=[],this.exactMatchOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gq).fromBinary(t,r)}static fromJson(t,r){return(new gq).fromJson(t,r)}static fromJsonString(t,r){return(new gq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gq,t,r)}static $(){return["SearchOriginReviewPeopleResponse|1 people #0*|2 exact_match_only 8",hq]}}class _q extends T{constructor(t){super(),this.schemaVersion=0,this.prefsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _q).fromBinary(t,r)}static fromJson(t,r){return(new _q).fromJson(t,r)}static fromJsonString(t,r){return(new _q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_q,t,r)}static $(){return["OriginReviewPreferences|1 schema_version 5|2 prefs_json 9|3 updated_at #0",n.Timestamp]}}class Jq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jq).fromBinary(t,r)}static fromJson(t,r){return(new Jq).fromJson(t,r)}static fromJsonString(t,r){return(new Jq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jq,t,r)}static $(){return["GetOriginReviewPreferencesRequest"]}}class wq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wq).fromBinary(t,r)}static fromJson(t,r){return(new wq).fromJson(t,r)}static fromJsonString(t,r){return(new wq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wq,t,r)}static $(){return["GetOriginReviewPreferencesResponse|1 preferences #0?",_q]}}class yq extends T{constructor(t){super(),this.schemaVersion=0,this.prefsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yq).fromBinary(t,r)}static fromJson(t,r){return(new yq).fromJson(t,r)}static fromJsonString(t,r){return(new yq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yq,t,r)}static $(){return["SetOriginReviewPreferencesRequest|1 schema_version 5|2 prefs_json 9"]}}class Sq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sq).fromBinary(t,r)}static fromJson(t,r){return(new Sq).fromJson(t,r)}static fromJsonString(t,r){return(new Sq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sq,t,r)}static $(){return["SetOriginReviewPreferencesResponse|1 preferences #0",_q]}}class qq extends T{constructor(t){super(),this.id="",this.label="",this.explanation="",this.turnedOn="",this.turnedOff="",this.on=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qq).fromBinary(t,r)}static fromJson(t,r){return(new qq).fromJson(t,r)}static fromJsonString(t,r){return(new qq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qq,t,r)}static $(){return["MergeBotRung|1 id 9|2 label 9|3 explanation 9|4 turned_on 9|5 turned_off 9|6 on 8"]}}class Bq extends T{constructor(t){super(),this.inTestGroup=!1,this.nudges=!1,this.agenticMerge=!1,this.rungs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bq).fromBinary(t,r)}static fromJson(t,r){return(new Bq).fromJson(t,r)}static fromJsonString(t,r){return(new Bq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bq,t,r)}static $(){return["MergeBotSettings|1 in_test_group 8|2 nudges 8|3 agentic_merge 8|4 rungs #0*|5 saved_at #1|6 working_hours_time_zone 9?",qq,n.Timestamp]}}class Iq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iq).fromBinary(t,r)}static fromJson(t,r){return(new Iq).fromJson(t,r)}static fromJsonString(t,r){return(new Iq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iq,t,r)}static $(){return["GetMergeBotSettingsRequest"]}}class Pq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pq).fromBinary(t,r)}static fromJson(t,r){return(new Pq).fromJson(t,r)}static fromJsonString(t,r){return(new Pq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pq,t,r)}static $(){return["GetMergeBotSettingsResponse|1 settings #0",Bq]}}class bq extends T{constructor(t){super(),this.rungs={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bq).fromBinary(t,r)}static fromJson(t,r){return(new bq).fromJson(t,r)}static fromJsonString(t,r){return(new bq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bq,t,r)}static $(){return["SetMergeBotConsentRequest|1 nudges 8?|2 agentic_merge 8?|3 rungs 9,8"]}}class Rq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rq).fromBinary(t,r)}static fromJson(t,r){return(new Rq).fromJson(t,r)}static fromJsonString(t,r){return(new Rq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rq,t,r)}static $(){return["SetMergeBotConsentResponse|1 settings #0",Bq]}}class vq extends T{constructor(t){super(),this.status=[],this.pr=[],this.source=[],this.sourceOptIns=[],this.archivedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vq).fromBinary(t,r)}static fromJson(t,r){return(new vq).fromJson(t,r)}static fromJsonString(t,r){return(new vq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vq,t,r)}static $(){return["SyncedSidebarFilters|1 status 9*|2 pr 9*|3 source 9*|4 source_opt_ins 9*|5 archived_only 8"]}}class xq extends T{constructor(t){super(),this.value="",this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xq).fromBinary(t,r)}static fromJson(t,r){return(new xq).fromJson(t,r)}static fromJsonString(t,r){return(new xq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xq,t,r)}static $(){return["SyncedStringSetting|1 value 9|2 set_at_ms 3"]}}class kq extends T{constructor(t){super(),this.value=!1,this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kq).fromBinary(t,r)}static fromJson(t,r){return(new kq).fromJson(t,r)}static fromJsonString(t,r){return(new kq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kq,t,r)}static $(){return["SyncedBoolSetting|1 value 8|2 set_at_ms 3"]}}class Eq extends T{constructor(t){super(),this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eq).fromBinary(t,r)}static fromJson(t,r){return(new Eq).fromJson(t,r)}static fromJsonString(t,r){return(new Eq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eq,t,r)}static $(){return["SyncedSidebarFiltersSetting|1 value #0|2 set_at_ms 3",vq]}}class Cq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cq).fromBinary(t,r)}static fromJson(t,r){return(new Cq).fromJson(t,r)}static fromJsonString(t,r){return(new Cq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cq,t,r)}static $(){return["SyncedSettings|1 new_messages #0|2 manual_send #0|3 first_steer_notice_shown #1|4 sidebar_filters #2",xq,kq,Eq]}}class Tq extends T{constructor(t){super(),this.setNow=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tq).fromBinary(t,r)}static fromJson(t,r){return(new Tq).fromJson(t,r)}static fromJsonString(t,r){return(new Tq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tq,t,r)}static $(){return["SyncClientSettingsRequest|1 changed #0|2 set_now 8",Cq]}}class Uq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uq).fromBinary(t,r)}static fromJson(t,r){return(new Uq).fromJson(t,r)}static fromJsonString(t,r){return(new Uq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uq,t,r)}static $(){return["SyncClientSettingsResponse|1 settings #0",Cq]}}class Aq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aq).fromBinary(t,r)}static fromJson(t,r){return(new Aq).fromJson(t,r)}static fromJsonString(t,r){return(new Aq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aq,t,r)}static $(){return["GetUsageLimitPolicyStatusRequest"]}}class $q extends T{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $q).fromBinary(t,r)}static fromJson(t,r){return(new $q).fromJson(t,r)}static fromJsonString(t,r){return(new $q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($q,t,r)}static $(){return["AllowedModelSelection|1 model_id 9|2 max_mode 8?|3 parameters #0*",Mq]}}class Mq extends T{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mq).fromBinary(t,r)}static fromJson(t,r){return(new Mq).fromJson(t,r)}static fromJsonString(t,r){return(new Mq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mq,t,r)}static $(){return["AllowedModelSelection.ModelParameterValue|1 id 9|2 value 9"]}}class Oq extends T{constructor(t){super(),this.isInSlowPool=!1,this.features={},this.canConfigureSpendLimit=!1,this.hasPendingRequest=!1,this.allowedModelIds=[],this.allowedModelTags=[],this.allowedModelSelections=[],this.stage=Pr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oq).fromBinary(t,r)}static fromJson(t,r){return(new Oq).fromJson(t,r)}static fromJsonString(t,r){return(new Oq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oq,t,r)}static $(){return["GetUsageLimitPolicyStatusResponse|1 is_in_slow_pool 8|2 error_title 9?|3 error_detail 9?|4 slowness_ms 5?|5 features 9,9|6 can_configure_spend_limit 8|7 limit_type 9?|8 has_pending_request 8|9 allowed_model_ids 9*|10 allowed_model_tags 9*|24 allowed_model_selections #0*|11 primary_button #1?|25 credit_request_button_hidden 8?|12 stage #2|13 tray_label 9?|14 tray_description 9?|15 cta_label 9?|16 dismissible 8?|17 reset_at_ms 3?|18 reset_days_remaining 5?|19 can_adjust_on_demand 8?|20 recommended_on_demand_limit_cents 3?|21 on_demand_min_cents 3?|22 on_demand_max_cents 3?|23 current_on_demand_limit_cents 3?",$q,o.Bo,Pr]}}class Dq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dq).fromBinary(t,r)}static fromJson(t,r){return(new Dq).fromJson(t,r)}static fromJsonString(t,r){return(new Dq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsRequest|1 mid_conversation_model_recommendation_context #0?",Nq]}}class Nq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nq).fromBinary(t,r)}static fromJson(t,r){return(new Nq).fromJson(t,r)}static fromJsonString(t,r){return(new Nq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nq,t,r)}static $(){return["MidConversationModelRecommendationContext|1 current_model #0|2 supports_third_party_usage_nudge 8?|3 model_nudges_enabled 8?|4 supports_first_party_limit_upsell 8?|5 declined_first_party_limit_upsell_offer_id 9?",h.G4]}}class Gq extends T{constructor(t){super(),this.grantId="",this.totalCents=n.protoInt64.zero,this.remainingCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.allowedModelTags=[],this.grantType="",this.showInClient=!1,this.allowedClientTypes=[],this.allowedModelSelections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gq).fromBinary(t,r)}static fromJson(t,r){return(new Gq).fromJson(t,r)}static fromJsonString(t,r){return(new Gq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gq,t,r)}static $(){return["ActiveCreditGrant|1 grant_id 9|2 total_cents 3|3 remaining_cents 3|4 expires_at_ms 3|5 allowed_model_ids 9*|6 allowed_model_tags 9*|7 grant_type 9|8 slowness_ms 5?|9 source 9?|10 campaign_name 9?|11 show_in_client 8|12 allowed_client_types 9*|13 allowed_model_selections #0*",$q]}}class Lq extends T{constructor(t){super(),this.grantId="",this.remainingCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.grantedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.surface=br.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lq).fromBinary(t,r)}static fromJson(t,r){return(new Lq).fromJson(t,r)}static fromJsonString(t,r){return(new Lq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lq,t,r)}static $(){return["ProjectsCredit|1 grant_id 9|2 remaining_cents 3|3 total_cents 3|4 granted_at_ms 3|5 expires_at_ms 3|6 surface #0|7 campaign_id 3?|8 team_id 3?",br]}}class Fq extends T{constructor(t){super(),this.activeGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fq).fromBinary(t,r)}static fromJson(t,r){return(new Fq).fromJson(t,r)}static fromJsonString(t,r){return(new Fq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsResponse|1 usage_limit_policy_status #0|2 active_grants #1*|3 third_party_usage_nudge #2?|4 model_recommendation_nudge #3?|5 projects_credit #4?|6 first_party_limit_upsell #5?",Kq,Gq,jq,zq,Lq,Hq]}}class Kq extends T{constructor(t){super(),this.isInSlowPool=!1,this.features={},this.canConfigureSpendLimit=!1,this.hasPendingRequest=!1,this.allowedModelIds=[],this.allowedModelTags=[],this.stage=Pr.UNSPECIFIED,this.allowedModelSelections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kq).fromBinary(t,r)}static fromJson(t,r){return(new Kq).fromJson(t,r)}static fromJsonString(t,r){return(new Kq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsResponse.UsageLimitPolicyStatus|1 is_in_slow_pool 8|2 error_title 9?|3 error_detail 9?|4 slowness_ms 5?|5 features 9,9|6 can_configure_spend_limit 8|7 limit_type 9?|8 has_pending_request 8|9 allowed_model_ids 9*|10 allowed_model_tags 9*|11 primary_button #0?|12 stage #1|13 tray_label 9?|14 tray_description 9?|15 cta_label 9?|16 dismissible 8?|17 reset_at_ms 3?|18 reset_days_remaining 5?|19 can_adjust_on_demand 8?|20 recommended_on_demand_limit_cents 3?|21 on_demand_min_cents 3?|22 on_demand_max_cents 3?|23 current_on_demand_limit_cents 3?|24 allowed_model_selections #2*|25 secondary_button #0?|26 credit_request_button_hidden 8?",o.Bo,Pr,$q]}}class zq extends T{constructor(t){super(),this.nudgeId="",this.experimentName="",this.group="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zq).fromBinary(t,r)}static fromJson(t,r){return(new zq).fromJson(t,r)}static fromJsonString(t,r){return(new zq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zq,t,r)}static $(){return["ModelRecommendationNudge|1 nudge_id 9|2 experiment_name 9|3 group 9|4 source_model #0|5 target_model #0",h.G4]}}class jq extends T{constructor(t){super(),this.experimentName="",this.group="",this.threshold=0,this.cycleId="",this.targetModel="",this.label="",this.ctaLabel="",this.nudgeId="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jq).fromBinary(t,r)}static fromJson(t,r){return(new jq).fromJson(t,r)}static fromJsonString(t,r){return(new jq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jq,t,r)}static $(){return["ThirdPartyUsageNudge|1 experiment_name 9|2 group 9|3 threshold 5|4 cycle_id 9|5 target_model 9|6 label 9|7 cta_label 9|8 nudge_id 9|9 description 9"]}}class Hq extends T{constructor(t){super(),this.offerId="",this.title="",this.body="",this.ctaLabel="",this.ctaUrl="",this.dismissLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hq).fromBinary(t,r)}static fromJson(t,r){return(new Hq).fromJson(t,r)}static fromJsonString(t,r){return(new Hq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hq,t,r)}static $(){return["FirstPartyLimitUpsell|1 offer_id 9|2 title 9|3 body 9|4 cta_label 9|5 cta_url 9|6 dismiss_label 9"]}}class Wq extends T{constructor(t){super(),this.includeAllProducts=!1,this.includePersonalTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wq).fromBinary(t,r)}static fromJson(t,r){return(new Wq).fromJson(t,r)}static fromJsonString(t,r){return(new Wq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wq,t,r)}static $(){return["GetCreditGrantsBalanceRequest|1 team_id 5?|2 include_all_products 8|3 include_personal_team 8"]}}class Qq extends T{constructor(t){super(),this.hasCreditGrants=!1,this.creditBalanceCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.usedCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qq).fromBinary(t,r)}static fromJson(t,r){return(new Qq).fromJson(t,r)}static fromJsonString(t,r){return(new Qq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qq,t,r)}static $(){return["GetCreditGrantsBalanceResponse|1 has_credit_grants 8|2 credit_balance_cents 3|3 total_cents 3|4 used_cents 3"]}}class Vq extends T{constructor(t){super(),this.includeAllProducts=!1,this.includePersonalTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vq).fromBinary(t,r)}static fromJson(t,r){return(new Vq).fromJson(t,r)}static fromJsonString(t,r){return(new Vq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vq,t,r)}static $(){return["GetClientVisibleCreditGrantsRequest|1 team_id 5?|2 include_all_products 8|3 include_personal_team 8"]}}class Xq extends T{constructor(t){super(),this.grants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xq).fromBinary(t,r)}static fromJson(t,r){return(new Xq).fromJson(t,r)}static fromJsonString(t,r){return(new Xq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xq,t,r)}static $(){return["GetClientVisibleCreditGrantsResponse|1 grants #0*",Yq]}}class Yq extends T{constructor(t){super(),this.remainingCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.displayName="",this.applicableProducts=[],this.appliesToAllProducts=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yq).fromBinary(t,r)}static fromJson(t,r){return(new Yq).fromJson(t,r)}static fromJsonString(t,r){return(new Yq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yq,t,r)}static $(){return["ClientVisibleCreditGrant|1 remaining_cents 3|2 total_cents 3|3 expires_at_ms 3|4 display_name 9|5 percent_used 5?|6 applicable_products 9*|7 applies_to_all_products 8"]}}class Zq extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zq).fromBinary(t,r)}static fromJson(t,r){return(new Zq).fromJson(t,r)}static fromJsonString(t,r){return(new Zq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zq,t,r)}static $(){return["GetAdvancedAnalyticsEnabledRequest|1 team_id 5"]}}class tB extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tB).fromBinary(t,r)}static fromJson(t,r){return(new tB).fromJson(t,r)}static fromJsonString(t,r){return(new tB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tB,t,r)}static $(){return["GetAdvancedAnalyticsEnabledResponse|1 enabled 8"]}}class rB extends T{constructor(t){super(),this.usageUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rB).fromBinary(t,r)}static fromJson(t,r){return(new rB).fromJson(t,r)}static fromJsonString(t,r){return(new rB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rB,t,r)}static $(){return["GetTokenUsageRequest|1 usage_uuid 9"]}}class eB extends T{constructor(t){super(),this.inputTokens=0,this.outputTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eB).fromBinary(t,r)}static fromJson(t,r){return(new eB).fromJson(t,r)}static fromJsonString(t,r){return(new eB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eB,t,r)}static $(){return["GetTokenUsageResponse|1 input_tokens 5|2 output_tokens 5"]}}class nB extends T{constructor(t){super(),this.teamId=0,this.bedrockIamRole="",this.region="",this.modelId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nB).fromBinary(t,r)}static fromJson(t,r){return(new nB).fromJson(t,r)}static fromJsonString(t,r){return(new nB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nB,t,r)}static $(){return["ValidateBedrockIamRoleRequest|1 team_id 5|2 bedrock_iam_role 9|3 region 9|4 model_id 9"]}}class sB extends T{constructor(t){super(),this.success=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sB).fromBinary(t,r)}static fromJson(t,r){return(new sB).fromJson(t,r)}static fromJsonString(t,r){return(new sB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sB,t,r)}static $(){return["ValidateBedrockIamRoleResponse|1 success 8|2 error_message 9"]}}class iB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iB).fromBinary(t,r)}static fromJson(t,r){return(new iB).fromJson(t,r)}static fromJsonString(t,r){return(new iB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iB,t,r)}static $(){return["DeleteBedrockIamRoleRequest|1 team_id 5"]}}class oB extends T{constructor(t){super(),this.success=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oB).fromBinary(t,r)}static fromJson(t,r){return(new oB).fromJson(t,r)}static fromJsonString(t,r){return(new oB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oB,t,r)}static $(){return["DeleteBedrockIamRoleResponse|1 success 8|2 error_message 9"]}}class aB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aB).fromBinary(t,r)}static fromJson(t,r){return(new aB).fromJson(t,r)}static fromJsonString(t,r){return(new aB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aB,t,r)}static $(){return["GetTeamSpendRequest|1 team_id 5|2 page 5?|3 page_size 5?|4 sort_by 9?|5 sort_direction 9?|6 search_term 9?|7 directory_group_id 5?|8 start_date 3?|9 end_date 3?|10 user_id 5?"]}}class uB extends T{constructor(t){super(),this.role=it.UNSPECIFIED,this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uB).fromBinary(t,r)}static fromJson(t,r){return(new uB).fromJson(t,r)}static fromJsonString(t,r){return(new uB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uB,t,r)}static $(){return["TeamRoleCount|1 role #0|2 count 5",it]}}class cB extends T{constructor(t){super(),this.teamMemberSpend=[],this.subscriptionCycleStart=n.protoInt64.zero,this.totalMembers=0,this.totalPages=0,this.totalByRole=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cB).fromBinary(t,r)}static fromJson(t,r){return(new cB).fromJson(t,r)}static fromJsonString(t,r){return(new cB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cB,t,r)}static $(){return["GetTeamSpendResponse|1 team_member_spend #0*|2 subscription_cycle_start 3|3 total_members 5|4 total_pages 5|5 total_by_role #1*|6 next_cycle_start 3?|7 pooled_limit_dollars 5?|8 limited_user_count 5?|9 max_user_spend_cents 5?|10 subscription_limited_users 5?|11 has_any_spend_limit_overrides 8?|12 has_any_free_usage 8?|13 self_serve_tiered_pricing_enabled 8?|14 merged_seat_rail 8?|15 unified_included_usage 8?|16 included_usage_resets_at 3?|17 on_demand_usage_unavailable 8?",lB,uB]}}class lB extends T{constructor(t){super(),this.userId=0,this.spendCents=0,this.fastPremiumRequests=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.hardLimitOverrideDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lB).fromBinary(t,r)}static fromJson(t,r){return(new lB).fromJson(t,r)}static fromJsonString(t,r){return(new lB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lB,t,r)}static $(){return["GetTeamSpendResponse.TeamMemberSpend|1 user_id 5|2 spend_cents 5|3 fast_premium_requests 5|4 name 9|5 email 9|6 role #0|7 hard_limit_override_dollars 5|8 included_spend_cents 5?|9 overall_spend_cents 5?|10 monthly_limit_dollars 5?|11 removed_at 3?|12 effective_per_user_limit_dollars 5?|13 profile_picture_url 9?|14 billing_tier #1?|15 auto_percent_used 1?|16 api_percent_used 1?|17 total_percent_used 1?|18 usage_promo_expires_at 3?|19 first_party_models_additional_budget_dollars 5?|20 first_party_models_additional_budget_unlimited 8?|21 merged_seat_tier #2?|22 included_percent_used 1?",it,ot,at]}}class mB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mB).fromBinary(t,r)}static fromJson(t,r){return(new mB).fromJson(t,r)}static fromJsonString(t,r){return(new mB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mB,t,r)}static $(){return["GetTeamSeatUpgradeRecommendationsRequest|1 team_id 5"]}}class fB extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.billingTier=ot.UNSPECIFIED,this.previousCycleSavings=!1,this.currentCyclePacing=!1,this.poolDriver=Rr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fB).fromBinary(t,r)}static fromJson(t,r){return(new fB).fromJson(t,r)}static fromJsonString(t,r){return(new fB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fB,t,r)}static $(){return["SeatUpgradeRecommendation|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?|5 role #0|6 billing_tier #1|7 previous_cycle_savings 8|8 current_cycle_pacing 8|9 pool_driver #2|10 previous_cycle_savings_cents 5?|11 projected_current_cycle_savings_cents 5?",it,ot,Rr]}}class dB extends T{constructor(t){super(),this.recommendations=[],this.enabled=!1,this.totalMonthlySavingsCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dB).fromBinary(t,r)}static fromJson(t,r){return(new dB).fromJson(t,r)}static fromJsonString(t,r){return(new dB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dB,t,r)}static $(){return["GetTeamSeatUpgradeRecommendationsResponse|1 recommendations #0*|2 enabled 8|3 total_monthly_savings_cents 5",fB]}}class pB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pB).fromBinary(t,r)}static fromJson(t,r){return(new pB).fromJson(t,r)}static fromJsonString(t,r){return(new pB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pB,t,r)}static $(){return["GetPendingSeatTierUpgradeRequestsRequest|1 team_id 5"]}}class hB extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.billingTier=ot.UNSPECIFIED,this.requestedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hB).fromBinary(t,r)}static fromJson(t,r){return(new hB).fromJson(t,r)}static fromJsonString(t,r){return(new hB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hB,t,r)}static $(){return["PendingSeatTierUpgradeRequest|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?|5 role #0|6 billing_tier #1|7 requested_at 9",it,ot]}}class gB extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gB).fromBinary(t,r)}static fromJson(t,r){return(new gB).fromJson(t,r)}static fromJsonString(t,r){return(new gB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gB,t,r)}static $(){return["GetPendingSeatTierUpgradeRequestsResponse|1 requests #0*",hB]}}class _B extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _B).fromBinary(t,r)}static fromJson(t,r){return(new _B).fromJson(t,r)}static fromJsonString(t,r){return(new _B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_B,t,r)}static $(){return["GetTeamSeatCapacityRequest|1 team_id 5"]}}class JB extends T{constructor(t){super(),this.purchasedSeats=0,this.inUseSeats=0,this.availableSeats=0,this.pendingReleaseSeats=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JB).fromBinary(t,r)}static fromJson(t,r){return(new JB).fromJson(t,r)}static fromJsonString(t,r){return(new JB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JB,t,r)}static $(){return["GetTeamSeatCapacityResponse|1 purchased_seats 5|2 in_use_seats 5|3 available_seats 5|4 pending_release_seats 5"]}}class wB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wB).fromBinary(t,r)}static fromJson(t,r){return(new wB).fromJson(t,r)}static fromJsonString(t,r){return(new wB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wB,t,r)}static $(){return["GetXaiTeamPlanManagementRequest|1 team_id 5"]}}class yB extends T{constructor(t){super(),this.skuId="",this.quantity=0,this.scheduledQuantity=0,this.reducibleQuantity=0,this.tier=at.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yB).fromBinary(t,r)}static fromJson(t,r){return(new yB).fromJson(t,r)}static fromJsonString(t,r){return(new yB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yB,t,r)}static $(){return["XaiTeamPlanSeatLine|1 sku_id 9|2 quantity 5|3 scheduled_quantity 5|4 reducible_quantity 5|5 tier #0",at]}}class SB extends T{constructor(t){super(),this.skuId="",this.tier=at.UNSPECIFIED,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SB).fromBinary(t,r)}static fromJson(t,r){return(new SB).fromJson(t,r)}static fromJsonString(t,r){return(new SB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SB,t,r)}static $(){return["XaiTeamPlanSeatOffer|1 sku_id 9|2 tier #0|3 unit_price_micros 3?|4 currency_code 9|5 yearly_unit_price_micros 3?",at]}}class qB extends T{constructor(t){super(),this.kind=BB.UNSPECIFIED,this.value={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qB).fromBinary(t,r)}static fromJson(t,r){return(new qB).fromJson(t,r)}static fromJsonString(t,r){return(new qB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qB,t,r)}static $(){return["XaiTeamPlanDiscount|1 kind #0|2 percent_off 5 value|3 amount_off #1 value|4 ends_at #2?",BB,IB,n.Timestamp]}}var BB=(0,a.QT)(n.proto3,C,"XaiTeamPlanDiscount.Kind",[[0,"UNSPECIFIED"],[1,"TRIAL"],[2,"PERCENT_OFF"],[3,"AMOUNT_OFF"],[4,"PAY_UPFRONT"]],1);class IB extends T{constructor(t){super(),this.unitMicros=n.protoInt64.zero,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IB).fromBinary(t,r)}static fromJson(t,r){return(new IB).fromJson(t,r)}static fromJsonString(t,r){return(new IB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IB,t,r)}static $(){return["XaiTeamPlanDiscount.AmountOff|1 unit_micros 3|2 currency_code 9"]}}class PB extends T{constructor(t){super(),this.available=!1,this.cancelling=!1,this.seatLines=[],this.unassignedSeats=0,this.manageOnGrokUrl="",this.manageOnGrokOnly=!1,this.reducibleSeats=0,this.pendingChangeAt="",this.addSeatOffered=!1,this.seatOffers=[],this.maxSeatsPerPurchase=0,this.paymentMethodUpdateOffered=!1,this.declinedCardJoin=!1,this.annualSwitchOffered=!1,this.planCancellingJoinerName="",this.declinedCardJoinWaitsForPayer=!1,this.planEnded=!1,this.seatPrices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PB).fromBinary(t,r)}static fromJson(t,r){return(new PB).fromJson(t,r)}static fromJsonString(t,r){return(new PB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PB,t,r)}static $(){return["GetXaiTeamPlanManagementResponse|1 available 8|2 cancelling 8|3 seat_lines #0*|4 unassigned_seats 5|5 manage_on_grok_url 9|6 manage_on_grok_only 8|7 reducible_seats 5|8 seats_after_pending_change 5?|9 pending_change_at 9|10 add_seat_offered 8|11 pending_payment_check #1|12 seat_offers #2*|13 max_seats_per_purchase 5|14 active_discount #3?|15 payment_method_update_offered 8|16 declined_card_join 8|17 annual_switch_offered 8|18 plan_cancelling_joiner_name 9|19 declined_card_join_waits_for_payer 8|20 plan_ended 8|21 seat_prices #2*|22 enterprise_trial_ends_at #4?",yB,yF,SB,qB,n.Timestamp]}}class bB extends T{constructor(t){super(),this.teamId=0,this.idempotencyKey="",this.change={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bB).fromBinary(t,r)}static fromJson(t,r){return(new bB).fromJson(t,r)}static fromJsonString(t,r){return(new bB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bB,t,r)}static $(){return["ChangeXaiTeamPlanRequest|1 team_id 5|2 idempotency_key 9|3 cancel #0 change|4 reinstate #1 change|5 reduce_seats #2 change|6 add_seat #3 change|7 finish_seat_payment_check #4 change|8 start_payment_method_update #5 change|9 update_payment_method #6 change|10 switch_to_annual #7 change",RB,vB,xB,kB,EB,CB,TB,UB]}}class RB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RB).fromBinary(t,r)}static fromJson(t,r){return(new RB).fromJson(t,r)}static fromJsonString(t,r){return(new RB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.Cancel"]}}class vB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vB).fromBinary(t,r)}static fromJson(t,r){return(new vB).fromJson(t,r)}static fromJsonString(t,r){return(new vB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.Reinstate"]}}class xB extends T{constructor(t){super(),this.quantity=0,this.skuId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xB).fromBinary(t,r)}static fromJson(t,r){return(new xB).fromJson(t,r)}static fromJsonString(t,r){return(new xB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.ReduceSeats|1 quantity 5|2 sku_id 9"]}}class kB extends T{constructor(t){super(),this.quantity=0,this.skuId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kB).fromBinary(t,r)}static fromJson(t,r){return(new kB).fromJson(t,r)}static fromJsonString(t,r){return(new kB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.AddSeat|1 quantity 5|2 sku_id 9"]}}class EB extends T{constructor(t){super(),this.checkId="",this.confirmed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EB).fromBinary(t,r)}static fromJson(t,r){return(new EB).fromJson(t,r)}static fromJsonString(t,r){return(new EB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.FinishSeatPaymentCheck|1 check_id 9|2 confirmed 8"]}}class CB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CB).fromBinary(t,r)}static fromJson(t,r){return(new CB).fromJson(t,r)}static fromJsonString(t,r){return(new CB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.StartPaymentMethodUpdate"]}}class TB extends T{constructor(t){super(),this.paymentMethodId="",this.billingCountry="",this.billingPostalCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TB).fromBinary(t,r)}static fromJson(t,r){return(new TB).fromJson(t,r)}static fromJsonString(t,r){return(new TB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.UpdatePaymentMethod|1 payment_method_id 9|2 billing_country 9|3 billing_postal_code 9"]}}class UB extends T{constructor(t){super(),this.preview=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UB).fromBinary(t,r)}static fromJson(t,r){return(new UB).fromJson(t,r)}static fromJsonString(t,r){return(new UB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.SwitchToAnnual|1 preview 8"]}}class AB extends T{constructor(t){super(),this.outcome=vr.UNSPECIFIED,this.message="",this.effectiveAt="",this.manageOnGrokUrl="",this.stripePublishableKey="",this.billingCountry="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AB).fromBinary(t,r)}static fromJson(t,r){return(new AB).fromJson(t,r)}static fromJsonString(t,r){return(new AB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AB,t,r)}static $(){return["ChangeXaiTeamPlanResponse|1 outcome #0|2 message 9|3 effective_at 9|4 manage_on_grok_url 9|5 payment_challenge #1|6 stripe_publishable_key 9|7 annual_switch #2|8 billing_country 9",vr,wF,$B]}}class $B extends T{constructor(t){super(),this.atRenewal=!1,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $B).fromBinary(t,r)}static fromJson(t,r){return(new $B).fromJson(t,r)}static fromJsonString(t,r){return(new $B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($B,t,r)}static $(){return["ChangeXaiTeamPlanResponse.AnnualSwitch|1 at_renewal 8|2 amount_due_cents 3?|3 currency_code 9"]}}class MB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MB).fromBinary(t,r)}static fromJson(t,r){return(new MB).fromJson(t,r)}static fromJsonString(t,r){return(new MB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MB,t,r)}static $(){return["GetCurrentBillingCycleRequest|1 team_id 5?"]}}class OB extends T{constructor(t){super(),this.startDateEpochMillis=n.protoInt64.zero,this.endDateEpochMillis=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OB).fromBinary(t,r)}static fromJson(t,r){return(new OB).fromJson(t,r)}static fromJsonString(t,r){return(new OB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OB,t,r)}static $(){return["GetCurrentBillingCycleResponse|1 start_date_epoch_millis 3|2 end_date_epoch_millis 3"]}}class DB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DB).fromBinary(t,r)}static fromJson(t,r){return(new DB).fromJson(t,r)}static fromJsonString(t,r){return(new DB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DB,t,r)}static $(){return["GetMonthlyBillingCycleRequest|1 team_id 5?"]}}class NB extends T{constructor(t){super(),this.startDateEpochMillis=n.protoInt64.zero,this.endDateEpochMillis=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NB).fromBinary(t,r)}static fromJson(t,r){return(new NB).fromJson(t,r)}static fromJsonString(t,r){return(new NB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NB,t,r)}static $(){return["GetMonthlyBillingCycleResponse|1 start_date_epoch_millis 3|2 end_date_epoch_millis 3"]}}class GB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GB).fromBinary(t,r)}static fromJson(t,r){return(new GB).fromJson(t,r)}static fromJsonString(t,r){return(new GB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GB,t,r)}static $(){return["GetBugbotSettingsRequest"]}}class LB extends T{constructor(t){super(),this.available=!1,this.enabled=!1,this.prUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LB).fromBinary(t,r)}static fromJson(t,r){return(new LB).fromJson(t,r)}static fromJsonString(t,r){return(new LB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LB,t,r)}static $(){return["GetBugbotSettingsResponse|1 available 8|2 enabled 8|3 pr_urls 9*"]}}class FB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FB).fromBinary(t,r)}static fromJson(t,r){return(new FB).fromJson(t,r)}static fromJsonString(t,r){return(new FB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FB,t,r)}static $(){return["GetBugbotAnalyticsV2Request|1 start_date 9?|2 end_date 9?|3 grouping 9?|4 team_id 5?"]}}class KB extends T{constructor(t){super(),this.shouldSeeAnalytics=!1,this.prsReviewedSeries=[],this.bugsFoundSeries=[],this.numRunsSeries=[],this.bugsResolvedSeries=[],this.pctResolutionRate=0,this.uniqueUsersSeries=[],this.uniqueUsersTotal=0,this.highSevResolvedSeries=[],this.mediumSevResolvedSeries=[],this.lowSevResolvedSeries=[],this.autofixPrsMergedSeries=[],this.totalAutofixRuns=0,this.costCentsSeries=[],this.numBilledRunsSeries=[],this.totalBugsFound=0,this.totalBugsEvaluated=0,this.bugsEvaluatedSeries=[],this.prsReviewedTotal=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KB).fromBinary(t,r)}static fromJson(t,r){return(new KB).fromJson(t,r)}static fromJsonString(t,r){return(new KB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KB,t,r)}static $(){return["GetBugbotAnalyticsV2Response|1 should_see_analytics 8|2 prs_reviewed_series #0*|3 bugs_found_series #0*|4 num_runs_series #0*|5 bugs_resolved_series #0*|6 pct_resolution_rate 1|7 unique_users_series #0*|8 unique_users_total 5|9 high_sev_resolved_series #0*|10 medium_sev_resolved_series #0*|11 low_sev_resolved_series #0*|12 autofix_prs_merged_series #0*|13 total_autofix_runs 5|14 cost_cents_series #0*|15 num_billed_runs_series #0*|16 total_bugs_found 5|17 total_bugs_evaluated 5|18 bugs_evaluated_series #0*|19 prs_reviewed_total 5",zB]}}class zB extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.value=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zB).fromBinary(t,r)}static fromJson(t,r){return(new zB).fromJson(t,r)}static fromJsonString(t,r){return(new zB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zB,t,r)}static $(){return["BugbotAnalyticsDataPoint|1 date 3|2 value 5"]}}class jB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jB).fromBinary(t,r)}static fromJson(t,r){return(new jB).fromJson(t,r)}static fromJsonString(t,r){return(new jB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jB,t,r)}static $(){return["GetBugBotPRAnalyticsRequest|1 github_repo_node_id 9?|2 status 9?|3 github_user_node_id 9?|4 start_date 9?|5 end_date 9?|6 min_bugs_found 5?|7 limit 5?|8 team_id 5?"]}}class HB extends T{constructor(t){super(),this.prs=[],this.userOptions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HB).fromBinary(t,r)}static fromJson(t,r){return(new HB).fromJson(t,r)}static fromJsonString(t,r){return(new HB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HB,t,r)}static $(){return["GetBugBotPRAnalyticsResponse|2 prs #0*|3 user_options #1*",QB,WB]}}class WB extends T{constructor(t){super(),this.githubUserNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WB).fromBinary(t,r)}static fromJson(t,r){return(new WB).fromJson(t,r)}static fromJsonString(t,r){return(new WB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WB,t,r)}static $(){return["PRUserOption|1 github_user_node_id 9|2 github_username 9?"]}}class QB extends T{constructor(t){super(),this.githubRepoNodeId="",this.prNumber=0,this.requestTime=n.protoInt64.zero,this.totalRuns=0,this.totalBugs=0,this.resolvedBugs=0,this.unresolvedBugs=0,this.isMerged=!1,this.highSevResolvedBugs=0,this.mediumSevResolvedBugs=0,this.lowSevResolvedBugs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QB).fromBinary(t,r)}static fromJson(t,r){return(new QB).fromJson(t,r)}static fromJsonString(t,r){return(new QB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QB,t,r)}static $(){return["BugBotPRAnalytics|1 github_repo_node_id 9|2 pr_number 5|3 request_time 3|4 total_runs 5|5 total_bugs 5|6 resolved_bugs 5|7 unresolved_bugs 5|8 is_merged 8|9 github_username 9?|10 high_sev_resolved_bugs 5|11 medium_sev_resolved_bugs 5|12 low_sev_resolved_bugs 5"]}}class VB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VB).fromBinary(t,r)}static fromJson(t,r){return(new VB).fromJson(t,r)}static fromJsonString(t,r){return(new VB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VB,t,r)}static $(){return["GetGithubInstallationsRequest|2 include_team_owned_repos 8?|3 ghe_application 9?|4 search 9?|5 team_id 5?|6 viewer_credentials_only 8?"]}}class XB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XB).fromBinary(t,r)}static fromJson(t,r){return(new XB).fromJson(t,r)}static fromJsonString(t,r){return(new XB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XB,t,r)}static $(){return["GetDeploymentIntegrationAvailabilityRequest"]}}class YB extends T{constructor(t){super(),this.disabledIntegrations=[],this.hiddenIntegrations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YB).fromBinary(t,r)}static fromJson(t,r){return(new YB).fromJson(t,r)}static fromJsonString(t,r){return(new YB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YB,t,r)}static $(){return["GetDeploymentIntegrationAvailabilityResponse|1 disabled_integrations #0*|2 hidden_integrations #0*",xr]}}class ZB extends T{constructor(t){super(),this.code=Er.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZB).fromBinary(t,r)}static fromJson(t,r){return(new ZB).fromJson(t,r)}static fromJsonString(t,r){return(new ZB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZB,t,r)}static $(){return["ScmReason|1 code #0",Er]}}class tI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tI).fromBinary(t,r)}static fromJson(t,r){return(new tI).fromJson(t,r)}static fromJsonString(t,r){return(new tI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tI,t,r)}static $(){return["GetScmConnectionStatusRequest|1 ghe_application 9?|2 team_id 5?|3 user_scoped 8?"]}}class rI extends T{constructor(t){super(),this.connected=!1,this.grantedInstallationOwners=[],this.providerDisabled=!1,this.health=kr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rI).fromBinary(t,r)}static fromJson(t,r){return(new rI).fromJson(t,r)}static fromJsonString(t,r){return(new rI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rI,t,r)}static $(){return["GetScmConnectionStatusResponse|1 connected 8|2 granted_installation_owners #0*|3 connected_at_ms 3?|4 provider_disabled 8|5 health #1|6 reason #2?",eI,kr,ZB]}}class eI extends T{constructor(t){super(),this.ownerTeamId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eI).fromBinary(t,r)}static fromJson(t,r){return(new eI).fromJson(t,r)}static fromJsonString(t,r){return(new eI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eI,t,r)}static $(){return["GetScmConnectionStatusResponse.GrantedInstallationOwner|1 owner_team_id 3|2 owner_team_name 9?"]}}class nI extends T{constructor(t){super(),this.gheApplications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nI).fromBinary(t,r)}static fromJson(t,r){return(new nI).fromJson(t,r)}static fromJsonString(t,r){return(new nI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nI,t,r)}static $(){return["GetScmConnectionStatusesRequest|1 ghe_applications 9*"]}}class sI extends T{constructor(t){super(),this.statuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sI).fromBinary(t,r)}static fromJson(t,r){return(new sI).fromJson(t,r)}static fromJsonString(t,r){return(new sI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sI,t,r)}static $(){return["GetScmConnectionStatusesResponse|1 statuses #0*",iI]}}class iI extends T{constructor(t){super(),this.gheApplication="",this.connected=!1,this.failed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iI).fromBinary(t,r)}static fromJson(t,r){return(new iI).fromJson(t,r)}static fromJsonString(t,r){return(new iI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iI,t,r)}static $(){return["GetScmConnectionStatusesResponse.Status|1 ghe_application 9|2 connected 8|3 connected_at_ms 3?|4 failed 8"]}}class oI extends T{constructor(t){super(),this.repoSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oI).fromBinary(t,r)}static fromJson(t,r){return(new oI).fromJson(t,r)}static fromJsonString(t,r){return(new oI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oI,t,r)}static $(){return["GetGithubRepoAccessStatusRequest|1 repo_slug 9"]}}class aI extends T{constructor(t){super(),this.granted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aI).fromBinary(t,r)}static fromJson(t,r){return(new aI).fromJson(t,r)}static fromJsonString(t,r){return(new aI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aI,t,r)}static $(){return["GetGithubRepoAccessStatusResponse|1 granted 8"]}}class uI extends T{constructor(t){super(),this.directPush=!1,this.sideBranchDelivery=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uI).fromBinary(t,r)}static fromJson(t,r){return(new uI).fromJson(t,r)}static fromJsonString(t,r){return(new uI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uI,t,r)}static $(){return["BugbotAutofixCapabilities|1 direct_push 8|2 side_branch_delivery 8"]}}class cI extends T{constructor(t){super(),this.autoEnableNewRepos=!1,this.learnedRules=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cI).fromBinary(t,r)}static fromJson(t,r){return(new cI).fromJson(t,r)}static fromJsonString(t,r){return(new cI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cI,t,r)}static $(){return["BugbotSettingsCapabilities|1 auto_enable_new_repos 8|2 learned_rules 8"]}}class lI extends T{constructor(t){super(),this.label="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lI).fromBinary(t,r)}static fromJson(t,r){return(new lI).fromJson(t,r)}static fromJsonString(t,r){return(new lI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lI,t,r)}static $(){return["BugbotSetupAction|1 label 9|2 url 9"]}}class mI extends T{constructor(t){super(),this.title="",this.description="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mI).fromBinary(t,r)}static fromJson(t,r){return(new mI).fromJson(t,r)}static fromJsonString(t,r){return(new mI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mI,t,r)}static $(){return["BugbotSetupActionRequired|1 title 9|2 description 9|3 action #0?|4 reason 9",lI]}}class fI extends T{constructor(t){super(),this.installations=[],this.githubConnected=!1,this.teamHasBugbotRepos=!1,this.githubUsernames=[],this.ssoRequiredOrgs=[],this.ssoRequiredOrgDisplayNames=[],this.providerDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fI).fromBinary(t,r)}static fromJson(t,r){return(new fI).fromJson(t,r)}static fromJsonString(t,r){return(new fI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fI,t,r)}static $(){return["GetGithubInstallationsResponse|1 installations #0*|2 github_connected 8|3 team_has_bugbot_repos 8|4 github_usernames 9*|5 ghe_hostname 9?|6 ghe_app_slug 9?|7 sso_required_orgs 3*|8 sso_required_org_display_names 9*|9 github_app_slug 9?|10 repo_picker_search_debounce_ms 5?|11 reconnect_reason 9?|12 ghe_app_html_url 9?|13 provider_disabled 8",pI]}}class dI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",this.htmlUrl="",this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dI).fromBinary(t,r)}static fromJson(t,r){return(new dI).fromJson(t,r)}static fromJsonString(t,r){return(new dI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dI,t,r)}static $(){return["GetGithubInstallationsResponse.Repository|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9|5 html_url 9|6 settings #0|7 archived 8|8 bugbot_enabled_by_team_name 9?",vI]}}class pI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repos=[],this.canModify=!1,this.hasMoreRepos=!1,this.canModifyInstallationSettings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pI).fromBinary(t,r)}static fromJson(t,r){return(new pI).fromJson(t,r)}static fromJsonString(t,r){return(new pI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pI,t,r)}static $(){return["GetGithubInstallationsResponse.Installation|1 installation_id 3|2 repos #0*|3 settings #1|4 can_modify 8|5 has_more_repos 8|6 total_pages 5?|7 access_error 9?|9 needs_team_scope 8?|10 can_modify_installation_settings 8|11 account_login 9?|12 autofix_capabilities #2?|13 team_owned 8?|14 settings_capabilities #3?|15 azure_devops_managed 8?|16 setup_action_required #4?|17 can_share_with_other_teams 8?|18 owner_team_id 3?|19 owner_team_name 9?|20 account_type 9?",dI,RI,uI,cI,mI]}}class hI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hI).fromBinary(t,r)}static fromJson(t,r){return(new hI).fromJson(t,r)}static fromJsonString(t,r){return(new hI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hI,t,r)}static $(){return["GetGithubInstallationTenantGrantsRequest|1 installation_id 3|2 ghe_application 9?"]}}class gI extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gI).fromBinary(t,r)}static fromJson(t,r){return(new gI).fromJson(t,r)}static fromJsonString(t,r){return(new gI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gI,t,r)}static $(){return["GetGithubInstallationTenantGrantsResponse|1 teams #0*",_I]}}class _I extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.granted=!1,this.stale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _I).fromBinary(t,r)}static fromJson(t,r){return(new _I).fromJson(t,r)}static fromJsonString(t,r){return(new _I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_I,t,r)}static $(){return["GetGithubInstallationTenantGrantsResponse.Team|1 team_id 5|2 team_name 9|3 granted 8|4 stale 8"]}}class JI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JI).fromBinary(t,r)}static fromJson(t,r){return(new JI).fromJson(t,r)}static fromJsonString(t,r){return(new JI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JI,t,r)}static $(){return["GrantGithubInstallationTenantRequest|1 installation_id 3|2 ghe_application 9?|3 target_team_id 5"]}}class wI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wI).fromBinary(t,r)}static fromJson(t,r){return(new wI).fromJson(t,r)}static fromJsonString(t,r){return(new wI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wI,t,r)}static $(){return["GrantGithubInstallationTenantResponse"]}}class yI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yI).fromBinary(t,r)}static fromJson(t,r){return(new yI).fromJson(t,r)}static fromJsonString(t,r){return(new yI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yI,t,r)}static $(){return["RevokeGithubInstallationTenantRequest|1 installation_id 3|2 ghe_application 9?|3 target_team_id 5"]}}class SI extends T{constructor(t){super(),this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SI).fromBinary(t,r)}static fromJson(t,r){return(new SI).fromJson(t,r)}static fromJsonString(t,r){return(new SI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SI,t,r)}static $(){return["RevokeGithubInstallationTenantResponse|1 revoked 8"]}}class qI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qI).fromBinary(t,r)}static fromJson(t,r){return(new qI).fromJson(t,r)}static fromJsonString(t,r){return(new qI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qI,t,r)}static $(){return["GetBugbotSuggestedReposRequest|1 ghe_application 9?|2 limit 5?"]}}class BI extends T{constructor(t){super(),this.repos=[],this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BI).fromBinary(t,r)}static fromJson(t,r){return(new BI).fromJson(t,r)}static fromJsonString(t,r){return(new BI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BI,t,r)}static $(){return["GetBugbotSuggestedReposResponse|1 repos #0*|2 can_enable 8",II]}}class II extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",this.htmlUrl="",this.prCountLastWeek=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new II).fromBinary(t,r)}static fromJson(t,r){return(new II).fromJson(t,r)}static fromJsonString(t,r){return(new II).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(II,t,r)}static $(){return["GetBugbotSuggestedReposResponse.SuggestedRepo|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9|5 html_url 9|6 pr_count_last_week 5"]}}class PI extends T{constructor(t){super(),this.agentType=Cr.UNSPECIFIED,this.coveredRepos=[],this.coveredOrgs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PI).fromBinary(t,r)}static fromJson(t,r){return(new PI).fromJson(t,r)}static fromJsonString(t,r){return(new PI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PI,t,r)}static $(){return["GetSecurityAgentSuggestedReposRequest|1 agent_type #0|2 ghe_application 9?|3 limit 5?|4 covered_repos 9*|5 covered_orgs 9*",Cr]}}class bI extends T{constructor(t){super(),this.repos=[],this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bI).fromBinary(t,r)}static fromJson(t,r){return(new bI).fromJson(t,r)}static fromJsonString(t,r){return(new bI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bI,t,r)}static $(){return["GetSecurityAgentSuggestedReposResponse|1 repos #0*|2 can_enable 8",II]}}class RI extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.disableInlineReviews=!1,this.autoEnableNewRepos=!1,this.isPrSummaryEnabled=!1,this.prSummaryUseComment=!1,this.isLearningEnabled=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableDraft=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RI).fromBinary(t,r)}static fromJson(t,r){return(new RI).fromJson(t,r)}static fromJsonString(t,r){return(new RI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RI,t,r)}static $(){return["InstallationSettings|1 allowlist 9*|2 allowlist_config #0|3 run_only_once 8|4 suppress_no_bugs_comments 8|5 disable_inline_reviews 8|6 auto_enable_new_repos 8|7 is_pr_summary_enabled 8|8 pr_summary_use_comment 8|9 is_learning_enabled 8|10 bugbot_autofix_mode #1|11 enable_draft 8|12 fail_github_action_on_bugbot_findings 8|13 bugbot_autofix_severity_filter 9*|14 is_pr_risk_score_enabled 8?",Tr,Ur]}}class vI extends T{constructor(t){super(),this.bugBotEnabled=!1,this.bugBotManualOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vI).fromBinary(t,r)}static fromJson(t,r){return(new vI).fromJson(t,r)}static fromJsonString(t,r){return(new vI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vI,t,r)}static $(){return["RepoSettings|1 bug_bot_enabled 8|2 bug_bot_manual_only 8|3 bug_bot_learning_enabled 8?|4 bug_bot_learning_inherit_installation_default 8?"]}}class xI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xI).fromBinary(t,r)}static fromJson(t,r){return(new xI).fromJson(t,r)}static fromJsonString(t,r){return(new xI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xI,t,r)}static $(){return["RepoIdentifier|1 installation_id 3|2 repo_node_id 9"]}}class kI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kI).fromBinary(t,r)}static fromJson(t,r){return(new kI).fromJson(t,r)}static fromJsonString(t,r){return(new kI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kI,t,r)}static $(){return["UpdateGithubRepoSettingsRequest|1 repo #0|2 settings #1|3 skip_write_access_check 8?|4 ghe_application 9?|5 team_id 5?",xI,vI]}}class EI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EI).fromBinary(t,r)}static fromJson(t,r){return(new EI).fromJson(t,r)}static fromJsonString(t,r){return(new EI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EI,t,r)}static $(){return["UpdateGithubRepoSettingsResponse"]}}class CI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CI).fromBinary(t,r)}static fromJson(t,r){return(new CI).fromJson(t,r)}static fromJsonString(t,r){return(new CI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CI,t,r)}static $(){return["UpdateGithubInstallationSettingsRequest|1 installation_id 3|2 settings #0|4 ghe_application 9?|5 team_id 5?",RI]}}class TI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TI).fromBinary(t,r)}static fromJson(t,r){return(new TI).fromJson(t,r)}static fromJsonString(t,r){return(new TI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TI,t,r)}static $(){return["UpdateGithubInstallationSettingsResponse"]}}class UI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UI).fromBinary(t,r)}static fromJson(t,r){return(new UI).fromJson(t,r)}static fromJsonString(t,r){return(new UI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UI,t,r)}static $(){return["UpdateGithubInstallationTeamScopeRequest|1 installation_id 3|2 ghe_application 9?|3 team_id 5"]}}class AI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AI).fromBinary(t,r)}static fromJson(t,r){return(new AI).fromJson(t,r)}static fromJsonString(t,r){return(new AI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AI,t,r)}static $(){return["UpdateGithubInstallationTeamScopeResponse"]}}class $I extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $I).fromBinary(t,r)}static fromJson(t,r){return(new $I).fromJson(t,r)}static fromJsonString(t,r){return(new $I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($I,t,r)}static $(){return["StartBugbotBackfillLearningRequest|1 installation_id 3|2 repo_node_id 9|3 ghe_application 9?|4 skip_write_access_check 8?"]}}class MI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MI).fromBinary(t,r)}static fromJson(t,r){return(new MI).fromJson(t,r)}static fromJsonString(t,r){return(new MI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MI,t,r)}static $(){return["StartBugbotBackfillLearningResponse"]}}class OI extends T{constructor(t){super(),this.workflowId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OI).fromBinary(t,r)}static fromJson(t,r){return(new OI).fromJson(t,r)}static fromJsonString(t,r){return(new OI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OI,t,r)}static $(){return["GetBugbotBackfillStatusRequest|1 workflow_id 9"]}}class DI extends T{constructor(t){super(),this.status=Ar.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DI).fromBinary(t,r)}static fromJson(t,r){return(new DI).fromJson(t,r)}static fromJsonString(t,r){return(new DI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DI,t,r)}static $(){return["GetBugbotBackfillStatusResponse|1 status #0|2 error_message 9?|3 rules_generated 5?",Ar]}}class NI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.bugBotEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NI).fromBinary(t,r)}static fromJson(t,r){return(new NI).fromJson(t,r)}static fromJsonString(t,r){return(new NI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NI,t,r)}static $(){return["UpdateAllGithubRepoSettingsRequest|1 installation_id 3|2 bug_bot_enabled 8|3 total_pages 5?|5 include_all_team_owned_repos 8?|6 ghe_application 9?|7 team_id 5?"]}}class GI extends T{constructor(t){super(),this.repoNodeId="",this.reason=LI.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GI).fromBinary(t,r)}static fromJson(t,r){return(new GI).fromJson(t,r)}static fromJsonString(t,r){return(new GI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GI,t,r)}static $(){return["UpdateAllGithubRepoSettingsFailure|1 repo_node_id 9|2 reason #0",LI]}}var LI=(0,a.QT)(n.proto3,C,"UpdateAllGithubRepoSettingsFailure.Reason",[[0,"UNSPECIFIED"],[1,"INTERNAL"],[2,"BITBUCKET_WORKSPACE_UNLINKED"],[3,"BITBUCKET_WORKSPACE_LINKED_TO_OTHER_TEAM"],[4,"BITBUCKET_WORKSPACE_CONNECTION_UNVERIFIABLE"],[5,"BUGBOT_ENABLED_BY_OTHER_TEAM"]],1);class FI extends T{constructor(t){super(),this.updatedCount=0,this.asyncOperationStarted=!1,this.asyncOperationAlreadyInProgress=!1,this.failedRepoNodeIds=[],this.failures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FI).fromBinary(t,r)}static fromJson(t,r){return(new FI).fromJson(t,r)}static fromJsonString(t,r){return(new FI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FI,t,r)}static $(){return["UpdateAllGithubRepoSettingsResponse|1 updated_count 5|2 async_operation_started 8|3 async_operation_already_in_progress 8|4 failed_repo_node_ids 9*|5 failures #0*",GI]}}class KI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.operation=zI.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KI).fromBinary(t,r)}static fromJson(t,r){return(new KI).fromJson(t,r)}static fromJsonString(t,r){return(new KI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KI,t,r)}static $(){return["UpdateSelfGithubAllowlistRequest|1 installation_id 3|2 operation #0|4 ghe_application 9?",zI]}}var zI=(0,a.QT)(n.proto3,C,"UpdateSelfGithubAllowlistRequest.Operation",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"REMOVE"]],1);class jI extends T{constructor(t){super(),this.allowlist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jI).fromBinary(t,r)}static fromJson(t,r){return(new jI).fromJson(t,r)}static fromJsonString(t,r){return(new jI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jI,t,r)}static $(){return["UpdateSelfGithubAllowlistResponse|1 allowlist 9*"]}}class HI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.startPage=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HI).fromBinary(t,r)}static fromJson(t,r){return(new HI).fromJson(t,r)}static fromJsonString(t,r){return(new HI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HI,t,r)}static $(){return["GetInstallationReposRequest|1 installation_id 3|2 start_page 5|4 ghe_application 9?|5 page_size 5?|6 search 9?|7 include_all_team_owned_repos 8?|8 viewer_credentials_only 8?"]}}class WI extends T{constructor(t){super(),this.repos=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WI).fromBinary(t,r)}static fromJson(t,r){return(new WI).fromJson(t,r)}static fromJsonString(t,r){return(new WI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WI,t,r)}static $(){return["GetInstallationReposResponse|1 repos #0*|2 has_more 8|3 access_error 9?",dI]}}class QI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QI).fromBinary(t,r)}static fromJson(t,r){return(new QI).fromJson(t,r)}static fromJsonString(t,r){return(new QI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QI,t,r)}static $(){return["FetchAllInstallationReposRequest|1 installation_id 3|2 total_pages 5?|4 include_all_team_owned_repos 8?|5 ghe_application 9?|6 skip_cache 8?|7 viewer_credentials_only 8?"]}}class VI extends T{constructor(t){super(),this.repos=[],this.hasMoreRepos=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VI).fromBinary(t,r)}static fromJson(t,r){return(new VI).fromJson(t,r)}static fromJsonString(t,r){return(new VI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VI,t,r)}static $(){return["FetchAllInstallationReposResponse|1 repos #0*|2 access_error 9?|3 has_more_repos 8",dI]}}class XI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XI).fromBinary(t,r)}static fromJson(t,r){return(new XI).fromJson(t,r)}static fromJsonString(t,r){return(new XI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XI,t,r)}static $(){return["GetInstallationGithubUsersRequest|1 installation_id 3|4 ghe_application 9?|5 team_id 5?"]}}class YI extends T{constructor(t){super(),this.login="",this.nodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YI).fromBinary(t,r)}static fromJson(t,r){return(new YI).fromJson(t,r)}static fromJsonString(t,r){return(new YI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YI,t,r)}static $(){return["GithubUser|1 login 9|2 node_id 9|3 hostname 9?"]}}class ZI extends T{constructor(t){super(),this.hasPermission=!1,this.permissionSettingsUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZI).fromBinary(t,r)}static fromJson(t,r){return(new ZI).fromJson(t,r)}static fromJsonString(t,r){return(new ZI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZI,t,r)}static $(){return["GithubPermissionInfo|1 has_permission 8|2 permission_settings_url 9"]}}class tP extends T{constructor(t){super(),this.githubUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tP).fromBinary(t,r)}static fromJson(t,r){return(new tP).fromJson(t,r)}static fromJsonString(t,r){return(new tP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tP,t,r)}static $(){return["GetInstallationGithubUsersResponse|1 github_users #0*|2 permission_info #1?",YI,ZI]}}class rP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rP).fromBinary(t,r)}static fromJson(t,r){return(new rP).fromJson(t,r)}static fromJsonString(t,r){return(new rP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rP,t,r)}static $(){return["GetUserAdminOrganizationsRequest|1 ghe_application_uuid 9?"]}}class eP extends T{constructor(t){super(),this.organizations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eP).fromBinary(t,r)}static fromJson(t,r){return(new eP).fromJson(t,r)}static fromJsonString(t,r){return(new eP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eP,t,r)}static $(){return["GetUserAdminOrganizationsResponse|1 organizations #0*",nP]}}class nP extends T{constructor(t){super(),this.login="",this.hostname="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nP).fromBinary(t,r)}static fromJson(t,r){return(new nP).fromJson(t,r)}static fromJsonString(t,r){return(new nP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nP,t,r)}static $(){return["GetUserAdminOrganizationsResponse.Organization|1 login 9|2 hostname 9"]}}class sP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sP).fromBinary(t,r)}static fromJson(t,r){return(new sP).fromJson(t,r)}static fromJsonString(t,r){return(new sP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sP,t,r)}static $(){return["GetTeamGithubUsersRequest|1 team_id 5|3 ghe_application 9?"]}}class iP extends T{constructor(t){super(),this.users=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iP).fromBinary(t,r)}static fromJson(t,r){return(new iP).fromJson(t,r)}static fromJsonString(t,r){return(new iP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iP,t,r)}static $(){return["GetTeamGithubUsersResponse|1 users #0*",YI]}}class oP extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.githubUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oP).fromBinary(t,r)}static fromJson(t,r){return(new oP).fromJson(t,r)}static fromJsonString(t,r){return(new oP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oP,t,r)}static $(){return["AddGithubUsersToTeamRequest|1 installation_id 3|2 github_users #0*|4 ghe_application 9?",YI]}}class aP extends T{constructor(t){super(),this.addedUserCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aP).fromBinary(t,r)}static fromJson(t,r){return(new aP).fromJson(t,r)}static fromJsonString(t,r){return(new aP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aP,t,r)}static $(){return["AddGithubUsersToTeamResponse|1 added_user_count 5"]}}class uP extends T{constructor(t){super(),this.scope={case:void 0},this.identities=[],this.resolveLoginsViaGithub=!1,this.export=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uP).fromBinary(t,r)}static fromJson(t,r){return(new uP).fromJson(t,r)}static fromJsonString(t,r){return(new uP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uP,t,r)}static $(){return["ResolveGithubIdentitiesRequest|1 team_id 3 scope|2 org_id 3 scope|3 identities #0*|4 resolve_logins_via_github 8|5 export 8",cP]}}class cP extends T{constructor(t){super(),this.identity={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cP).fromBinary(t,r)}static fromJson(t,r){return(new cP).fromJson(t,r)}static fromJsonString(t,r){return(new cP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cP,t,r)}static $(){return["ResolveGithubIdentitiesRequest.Identity|1 github_user_node_id 9 identity|2 github_user_database_id 3 identity|3 login 9 identity"]}}class lP extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lP).fromBinary(t,r)}static fromJson(t,r){return(new lP).fromJson(t,r)}static fromJsonString(t,r){return(new lP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lP,t,r)}static $(){return["ResolveGithubIdentitiesResponse|1 results #0*",dP]}}class mP extends T{constructor(t){super(),this.teamPublicId="",this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mP).fromBinary(t,r)}static fromJson(t,r){return(new mP).fromJson(t,r)}static fromJsonString(t,r){return(new mP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Team|1 team_public_id 9|2 team_name 9"]}}class fP extends T{constructor(t){super(),this.publicId="",this.displayName="",this.email="",this.profileHandle="",this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fP).fromBinary(t,r)}static fromJson(t,r){return(new fP).fromJson(t,r)}static fromJsonString(t,r){return(new fP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Match|1 public_id 9|2 display_name 9|3 email 9|4 profile_handle 9|5 teams #0*",mP]}}class dP extends T{constructor(t){super(),this.githubUserNodeId="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dP).fromBinary(t,r)}static fromJson(t,r){return(new dP).fromJson(t,r)}static fromJsonString(t,r){return(new dP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Result|1 request #0|2 github_user_node_id 9|3 matches #1*|4 resolved_at #2",cP,fP,n.Timestamp]}}class pP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pP).fromBinary(t,r)}static fromJson(t,r){return(new pP).fromJson(t,r)}static fromJsonString(t,r){return(new pP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pP,t,r)}static $(){return["GetUserPullRequestsRequest|1 repository_filter 9?|2 git_application 9?|3 page 5?|4 page_size 5?|5 search_query 9?|6 author_filter 9?|7 state_filter 9?|8 pr_number 5?"]}}class hP extends T{constructor(t){super(),this.pullRequests=[],this.hasMore=!1,this.hasGitConnection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hP).fromBinary(t,r)}static fromJson(t,r){return(new hP).fromJson(t,r)}static fromJsonString(t,r){return(new hP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hP,t,r)}static $(){return["GetUserPullRequestsResponse|1 pull_requests #0*|2 has_more 8|3 total_count 5?|4 has_git_connection 8|5 current_user_login 9?",_P]}}class gP extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.nodeId="",this.url="",this.name="",this.description="",this.color="",this.isDefault=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gP).fromBinary(t,r)}static fromJson(t,r){return(new gP).fromJson(t,r)}static fromJsonString(t,r){return(new gP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gP,t,r)}static $(){return["PullRequestLabel|1 id 3|2 node_id 9|3 url 9|4 name 9|5 description 9|6 color 9|7 is_default 8"]}}class _P extends T{constructor(t){super(),this.number=0,this.title="",this.state="",this.url="",this.repository="",this.createdAt="",this.updatedAt="",this.isDraft=!1,this.author="",this.description="",this.labels=[],this.headRef="",this.baseRef="",this.comments=0,this.reviewComments=0,this.mergedAt="",this.closedAt="",this.descriptionRaw="",this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _P).fromBinary(t,r)}static fromJson(t,r){return(new _P).fromJson(t,r)}static fromJsonString(t,r){return(new _P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_P,t,r)}static $(){return["UserPullRequest|1 number 5|2 title 9|3 state 9|4 url 9|5 repository 9|6 created_at 9|7 updated_at 9|8 is_draft 8|9 author 9|10 description 9|11 labels #0*|12 head_ref 9|13 base_ref 9|14 comments 5|15 review_comments 5|16 merged_at 9|17 closed_at 9|18 description_raw 9|19 head_sha 9",gP]}}class JP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JP).fromBinary(t,r)}static fromJson(t,r){return(new JP).fromJson(t,r)}static fromJsonString(t,r){return(new JP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JP,t,r)}static $(){return["GetUserReviewRequestsRequest|1 repository_filter 9?|2 git_application 9?|3 page 5?|4 page_size 5?|5 search_query 9?|6 state_filter 9?"]}}class wP extends T{constructor(t){super(),this.pullRequests=[],this.hasMore=!1,this.hasGitConnection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wP).fromBinary(t,r)}static fromJson(t,r){return(new wP).fromJson(t,r)}static fromJsonString(t,r){return(new wP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wP,t,r)}static $(){return["GetUserReviewRequestsResponse|1 pull_requests #0*|2 has_more 8|3 total_count 5?|4 has_git_connection 8|5 current_user_login 9?",_P]}}class yP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yP).fromBinary(t,r)}static fromJson(t,r){return(new yP).fromJson(t,r)}static fromJsonString(t,r){return(new yP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yP,t,r)}static $(){return["GetBugbotUserSettingsRequest|1 team_id 5?"]}}class SP extends T{constructor(t){super(),this.manualTriggerOnly=!1,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableVmRun=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],this.installationDefaultBugbotAutofixMode=Ur.UNSPECIFIED,this.installationDefaultBugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SP).fromBinary(t,r)}static fromJson(t,r){return(new SP).fromJson(t,r)}static fromJsonString(t,r){return(new SP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SP,t,r)}static $(){return["GetBugbotUserSettingsResponse|1 manual_trigger_only 8|2 run_only_once 8|3 suppress_no_bugs_comments 8|4 enable_draft 8?|5 is_pr_summary_enabled 8?|6 bugbot_autofix_mode #0|7 enable_vm_run 8|8 fail_github_action_on_bugbot_findings 8|9 bugbot_autofix_severity_filter 9*|10 installation_default_enable_draft 8?|11 installation_default_is_pr_summary_enabled 8?|12 installation_default_bugbot_autofix_mode #0|13 installation_default_bugbot_autofix_severity_filter 9*|14 is_incremental_review_enabled 8?|15 team_default_is_incremental_review_enabled 8?|16 is_pr_risk_score_enabled 8?|17 installation_default_is_pr_risk_score_enabled 8?|18 installation_default_enable_draft_mixed 8?|19 installation_default_is_pr_summary_enabled_mixed 8?|20 installation_default_is_pr_risk_score_enabled_mixed 8?|21 installation_default_bugbot_autofix_mode_mixed 8?|22 installation_default_bugbot_autofix_severity_filter_mixed 8?",Ur]}}class qP extends T{constructor(t){super(),this.manualTriggerOnly=!1,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableVmRun=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qP).fromBinary(t,r)}static fromJson(t,r){return(new qP).fromJson(t,r)}static fromJsonString(t,r){return(new qP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qP,t,r)}static $(){return["UpdateBugbotUserSettingsRequest|1 manual_trigger_only 8|2 run_only_once 8|3 suppress_no_bugs_comments 8|4 enable_draft 8?|5 is_pr_summary_enabled 8?|6 bugbot_autofix_mode #0|7 enable_vm_run 8|8 fail_github_action_on_bugbot_findings 8|9 bugbot_autofix_severity_filter 9*|10 is_incremental_review_enabled 8?|11 is_pr_risk_score_enabled 8?",Ur]}}class BP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BP).fromBinary(t,r)}static fromJson(t,r){return(new BP).fromJson(t,r)}static fromJsonString(t,r){return(new BP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BP,t,r)}static $(){return["UpdateBugbotUserSettingsResponse"]}}class IP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IP).fromBinary(t,r)}static fromJson(t,r){return(new IP).fromJson(t,r)}static fromJsonString(t,r){return(new IP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IP,t,r)}static $(){return["GetFullSelfDrivingUserSettingsRequest"]}}class PP extends T{constructor(t){super(),this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,this.slackNotificationsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PP).fromBinary(t,r)}static fromJson(t,r){return(new PP).fromJson(t,r)}static fromJsonString(t,r){return(new PP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PP,t,r)}static $(){return["GetFullSelfDrivingUserSettingsResponse|1 default_mode #0|2 only_cloud_agent_prs 8|3 globally_disabled 8|4 auto_create_on_first_pr_push 8|5 slack_notifications_enabled 8|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class bP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bP).fromBinary(t,r)}static fromJson(t,r){return(new bP).fromJson(t,r)}static fromJsonString(t,r){return(new bP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bP,t,r)}static $(){return["UpdateFullSelfDrivingUserSettingsRequest|1 default_mode #0?|2 only_cloud_agent_prs 8?|3 globally_disabled 8?|4 auto_create_on_first_pr_push 8?|5 slack_notifications_enabled 8?|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class RP extends T{constructor(t){super(),this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,this.slackNotificationsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RP).fromBinary(t,r)}static fromJson(t,r){return(new RP).fromJson(t,r)}static fromJsonString(t,r){return(new RP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RP,t,r)}static $(){return["UpdateFullSelfDrivingUserSettingsResponse|1 default_mode #0|2 only_cloud_agent_prs 8|3 globally_disabled 8|4 auto_create_on_first_pr_push 8|5 slack_notifications_enabled 8|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class vP extends T{constructor(t){super(),this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vP).fromBinary(t,r)}static fromJson(t,r){return(new vP).fromJson(t,r)}static fromJsonString(t,r){return(new vP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vP,t,r)}static $(){return["FullSelfDrivingRepoSetting|1 scm_provider #0|2 git_enterprise_uuid 9?|3 scm_repo_node_id 9|4 repo_url 9|5 enabled 8",At]}}class xP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xP).fromBinary(t,r)}static fromJson(t,r){return(new xP).fromJson(t,r)}static fromJsonString(t,r){return(new xP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xP,t,r)}static $(){return["ListFullSelfDrivingRepoSettingsRequest"]}}class kP extends T{constructor(t){super(),this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kP).fromBinary(t,r)}static fromJson(t,r){return(new kP).fromJson(t,r)}static fromJsonString(t,r){return(new kP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kP,t,r)}static $(){return["ListFullSelfDrivingRepoSettingsResponse|1 repos #0*",vP]}}class EP extends T{constructor(t){super(),this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EP).fromBinary(t,r)}static fromJson(t,r){return(new EP).fromJson(t,r)}static fromJsonString(t,r){return(new EP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EP,t,r)}static $(){return["SetFullSelfDrivingRepoEnabledRequest|1 scm_provider #0|2 git_enterprise_uuid 9?|3 scm_repo_node_id 9|4 repo_url 9|5 enabled 8",At]}}class CP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CP).fromBinary(t,r)}static fromJson(t,r){return(new CP).fromJson(t,r)}static fromJsonString(t,r){return(new CP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CP,t,r)}static $(){return["SetFullSelfDrivingRepoEnabledResponse|1 repo #0",vP]}}class TP extends T{constructor(t){super(),this.teamId=0,this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TP).fromBinary(t,r)}static fromJson(t,r){return(new TP).fromJson(t,r)}static fromJsonString(t,r){return(new TP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TP,t,r)}static $(){return["FullSelfDrivingTeamSettings|1 team_id 5|2 default_mode #0|3 only_cloud_agent_prs 8|4 globally_disabled 8|5 auto_create_on_first_pr_push 8",g]}}class UP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UP).fromBinary(t,r)}static fromJson(t,r){return(new UP).fromJson(t,r)}static fromJsonString(t,r){return(new UP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UP,t,r)}static $(){return["GetFullSelfDrivingTeamSettingsRequest|1 team_id 5"]}}class AP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AP).fromBinary(t,r)}static fromJson(t,r){return(new AP).fromJson(t,r)}static fromJsonString(t,r){return(new AP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AP,t,r)}static $(){return["GetFullSelfDrivingTeamSettingsResponse|1 settings #0",TP]}}class $P extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $P).fromBinary(t,r)}static fromJson(t,r){return(new $P).fromJson(t,r)}static fromJsonString(t,r){return(new $P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($P,t,r)}static $(){return["UpdateFullSelfDrivingTeamSettingsRequest|1 team_id 5|2 default_mode #0?|3 only_cloud_agent_prs 8?|4 globally_disabled 8?|5 auto_create_on_first_pr_push 8?",g]}}class MP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MP).fromBinary(t,r)}static fromJson(t,r){return(new MP).fromJson(t,r)}static fromJsonString(t,r){return(new MP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MP,t,r)}static $(){return["UpdateFullSelfDrivingTeamSettingsResponse|1 settings #0",TP]}}class OP extends T{constructor(t){super(),this.teamId=0,this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OP).fromBinary(t,r)}static fromJson(t,r){return(new OP).fromJson(t,r)}static fromJsonString(t,r){return(new OP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OP,t,r)}static $(){return["FullSelfDrivingTeamRepoSetting|1 team_id 5|2 scm_provider #0|3 git_enterprise_uuid 9?|4 scm_repo_node_id 9|5 repo_url 9|6 enabled 8",At]}}class DP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DP).fromBinary(t,r)}static fromJson(t,r){return(new DP).fromJson(t,r)}static fromJsonString(t,r){return(new DP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DP,t,r)}static $(){return["ListFullSelfDrivingTeamRepoSettingsRequest|1 team_id 5"]}}class NP extends T{constructor(t){super(),this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NP).fromBinary(t,r)}static fromJson(t,r){return(new NP).fromJson(t,r)}static fromJsonString(t,r){return(new NP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NP,t,r)}static $(){return["ListFullSelfDrivingTeamRepoSettingsResponse|1 repos #0*",OP]}}class GP extends T{constructor(t){super(),this.teamId=0,this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GP).fromBinary(t,r)}static fromJson(t,r){return(new GP).fromJson(t,r)}static fromJsonString(t,r){return(new GP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GP,t,r)}static $(){return["SetFullSelfDrivingTeamRepoEnabledRequest|1 team_id 5|2 scm_provider #0|3 git_enterprise_uuid 9?|4 scm_repo_node_id 9|5 repo_url 9|6 enabled 8",At]}}class LP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LP).fromBinary(t,r)}static fromJson(t,r){return(new LP).fromJson(t,r)}static fromJsonString(t,r){return(new LP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LP,t,r)}static $(){return["SetFullSelfDrivingTeamRepoEnabledResponse|1 repo #0",OP]}}class FP extends T{constructor(t){super(),this.prUrl="",this.repoUrl="",this.pullNumber=0,this.bcId="",this.enabled=!1,this.mode=g.UNSPECIFIED,this.ownerUserId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FP).fromBinary(t,r)}static fromJson(t,r){return(new FP).fromJson(t,r)}static fromJsonString(t,r){return(new FP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FP,t,r)}static $(){return["FullSelfDrivingActiveAgent|1 pr_url 9|2 repo_url 9|3 pull_number 5|4 bc_id 9|5 enabled 8|6 mode #0|7 owner_user_id 5|8 owner_display_name 9?|9 owner_email 9?|10 mergeable_state 9?|11 is_mergeable 8?|12 visible_findings_count 5?|13 latest_status_update #1?|14 pr_title 9?",g,KP]}}class KP extends T{constructor(t){super(),this.state="",this.status="",this.loadingMessages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KP).fromBinary(t,r)}static fromJson(t,r){return(new KP).fromJson(t,r)}static fromJsonString(t,r){return(new KP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KP,t,r)}static $(){return["FullSelfDrivingStatusUpdate|1 state 9|2 status 9|3 loading_messages 9*|4 updated_at #0",n.Timestamp]}}class zP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zP).fromBinary(t,r)}static fromJson(t,r){return(new zP).fromJson(t,r)}static fromJsonString(t,r){return(new zP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zP,t,r)}static $(){return["ListFullSelfDrivingActiveAgentsRequest|1 search_query 9?|2 page 5?|3 page_size 5?|4 archived 8?|5 status_visual 9?"]}}class jP extends T{constructor(t){super(),this.agents=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jP).fromBinary(t,r)}static fromJson(t,r){return(new jP).fromJson(t,r)}static fromJsonString(t,r){return(new jP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jP,t,r)}static $(){return["ListFullSelfDrivingActiveAgentsResponse|1 agents #0*|2 total_count 5",FP]}}class HP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HP).fromBinary(t,r)}static fromJson(t,r){return(new HP).fromJson(t,r)}static fromJsonString(t,r){return(new HP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HP,t,r)}static $(){return["ListFullSelfDrivingTeamActiveAgentsRequest|1 team_id 5|2 search_query 9?|3 page 5?|4 page_size 5?|5 archived 8?"]}}class WP extends T{constructor(t){super(),this.agents=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WP).fromBinary(t,r)}static fromJson(t,r){return(new WP).fromJson(t,r)}static fromJsonString(t,r){return(new WP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WP,t,r)}static $(){return["ListFullSelfDrivingTeamActiveAgentsResponse|1 agents #0*|2 total_count 5",FP]}}class QP extends T{constructor(t){super(),this.prUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QP).fromBinary(t,r)}static fromJson(t,r){return(new QP).fromJson(t,r)}static fromJsonString(t,r){return(new QP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QP,t,r)}static $(){return["UpdateFullSelfDrivingPrConfigRequest|1 pr_url 9|2 enabled 8?|3 mode #0?|4 team_id 5?",g]}}class VP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VP).fromBinary(t,r)}static fromJson(t,r){return(new VP).fromJson(t,r)}static fromJsonString(t,r){return(new VP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VP,t,r)}static $(){return["UpdateFullSelfDrivingPrConfigResponse|1 agent #0",FP]}}class XP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XP).fromBinary(t,r)}static fromJson(t,r){return(new XP).fromJson(t,r)}static fromJsonString(t,r){return(new XP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XP,t,r)}static $(){return["GetBugBotProUserSettingsRequest"]}}class YP extends T{constructor(t){super(),this.enabled=!1,this.bugbotWasEnabledInThisBillingCycle=!1,this.bugbotUsageTier=$r.UNSPECIFIED,this.bugbotBillingMode=Mr.UNSPECIFIED,this.canMigrateToUsageBased=!1,this.seatLicenseCount=0,this.bugbotUsageBasedOnEnable=!1,this.bugbotMigrationCreditAlreadyGranted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YP).fromBinary(t,r)}static fromJson(t,r){return(new YP).fromJson(t,r)}static fromJsonString(t,r){return(new YP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YP,t,r)}static $(){return["GetBugBotProUserSettingsResponse|1 enabled 8|2 bugbot_was_enabled_in_this_billing_cycle 8|3 bugbot_usage_tier #0|4 bugbot_billing_mode #1|5 can_migrate_to_usage_based 8|6 seat_license_count 5|7 bugbot_usage_based_on_enable 8|8 bugbot_migration_credit_already_granted 8",$r,Mr]}}class ZP extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZP).fromBinary(t,r)}static fromJson(t,r){return(new ZP).fromJson(t,r)}static fromJsonString(t,r){return(new ZP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZP,t,r)}static $(){return["UpdateBugBotProUserSettingsRequest|1 enabled 8"]}}class tb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tb).fromBinary(t,r)}static fromJson(t,r){return(new tb).fromJson(t,r)}static fromJsonString(t,r){return(new tb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tb,t,r)}static $(){return["UpdateBugBotProUserSettingsResponse"]}}class rb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rb).fromBinary(t,r)}static fromJson(t,r){return(new rb).fromJson(t,r)}static fromJsonString(t,r){return(new rb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rb,t,r)}static $(){return["MigrateBugBotProUserToUsageBasedBillingRequest|1 keep_high_effort_default 8?"]}}class eb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eb).fromBinary(t,r)}static fromJson(t,r){return(new eb).fromJson(t,r)}static fromJsonString(t,r){return(new eb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eb,t,r)}static $(){return["MigrateBugBotProUserToUsageBasedBillingResponse"]}}class nb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nb).fromBinary(t,r)}static fromJson(t,r){return(new nb).fromJson(t,r)}static fromJsonString(t,r){return(new nb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nb,t,r)}static $(){return["GetGlassEarlyPreviewEnrollmentRequest"]}}class sb extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sb).fromBinary(t,r)}static fromJson(t,r){return(new sb).fromJson(t,r)}static fromJsonString(t,r){return(new sb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sb,t,r)}static $(){return["GetGlassEarlyPreviewEnrollmentResponse|1 enabled 8|2 enterprise_glass_self_enroll_eligible 8?|3 glass_access_granted 8?"]}}class ib extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ib).fromBinary(t,r)}static fromJson(t,r){return(new ib).fromJson(t,r)}static fromJsonString(t,r){return(new ib).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ib,t,r)}static $(){return["EnrollInGlassEarlyPreviewRequest"]}}class ob extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ob).fromBinary(t,r)}static fromJson(t,r){return(new ob).fromJson(t,r)}static fromJsonString(t,r){return(new ob).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ob,t,r)}static $(){return["EnrollInGlassEarlyPreviewResponse"]}}class ab extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ab).fromBinary(t,r)}static fromJson(t,r){return(new ab).fromJson(t,r)}static fromJsonString(t,r){return(new ab).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ab,t,r)}static $(){return["UnenrollFromGlassEarlyPreviewRequest"]}}class ub extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ub).fromBinary(t,r)}static fromJson(t,r){return(new ub).fromJson(t,r)}static fromJsonString(t,r){return(new ub).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ub,t,r)}static $(){return["UnenrollFromGlassEarlyPreviewResponse"]}}class cb extends T{constructor(t){super(),this.bugId="",this.event=lb.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cb).fromBinary(t,r)}static fromJson(t,r){return(new cb).fromJson(t,r)}static fromJsonString(t,r){return(new cb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cb,t,r)}static $(){return["RecordBugbotDeeplinkEventRequest|1 bug_id 9|2 event #0|3 comment_id 9?",lb]}}var lb=(0,a.QT)(n.proto3,C,"RecordBugbotDeeplinkEventRequest.BugbotDeeplinkEvent",[[0,"UNSPECIFIED"],[1,"CLICKED"],[2,"HANDLED_DIALOG_SHOWN"],[3,"HANDLED_CHAT_CREATED"],[4,"ERROR"],[5,"HANDLED_FIX_IN_WEB"]],1);class mb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mb).fromBinary(t,r)}static fromJson(t,r){return(new mb).fromJson(t,r)}static fromJsonString(t,r){return(new mb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mb,t,r)}static $(){return["RecordBugbotDeeplinkEventResponse"]}}class fb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fb).fromBinary(t,r)}static fromJson(t,r){return(new fb).fromJson(t,r)}static fromJsonString(t,r){return(new fb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fb,t,r)}static $(){return["GetFilteredUsageEventsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 user_id 5?|5 model_id 9?|6 page 5?|7 page_size 5?|8 service_account_id 9?|9 cloud_agent_id 9?|10 automation_id 9?|11 automation_managed_type 9?|12 client_type 9?"]}}class db extends T{constructor(t){super(),this.usageEvents=[],this.totalUsageEventsCount=0,this.usageEventsDisplay=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new db).fromBinary(t,r)}static fromJson(t,r){return(new db).fromJson(t,r)}static fromJsonString(t,r){return(new db).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(db,t,r)}static $(){return["GetFilteredUsageEventsResponse|1 usage_events #0*|2 total_usage_events_count 5|3 usage_events_display #1*",i.aq,i.GF]}}class pb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pb).fromBinary(t,r)}static fromJson(t,r){return(new pb).fromJson(t,r)}static fromJsonString(t,r){return(new pb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pb,t,r)}static $(){return["GetAggregatedUsageEventsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 user_id 5?|5 use_monthly_billing_cycle_start 8?"]}}class hb extends T{constructor(t){super(),this.aggregations=[],this.totalInputTokens=n.protoInt64.zero,this.totalOutputTokens=n.protoInt64.zero,this.totalCacheWriteTokens=n.protoInt64.zero,this.totalCacheReadTokens=n.protoInt64.zero,this.totalCostCents=0,this.percentOfBurstUsed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hb).fromBinary(t,r)}static fromJson(t,r){return(new hb).fromJson(t,r)}static fromJsonString(t,r){return(new hb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hb,t,r)}static $(){return["GetAggregatedUsageEventsResponse|1 aggregations #0*|2 total_input_tokens 3|3 total_output_tokens 3|4 total_cache_write_tokens 3|5 total_cache_read_tokens 3|6 total_cost_cents 1|7 percent_of_burst_used 1|8 total_request_cost 1?|9 start_date 3?",gb]}}class gb extends T{constructor(t){super(),this.modelIntent="",this.inputTokens=n.protoInt64.zero,this.outputTokens=n.protoInt64.zero,this.cacheWriteTokens=n.protoInt64.zero,this.cacheReadTokens=n.protoInt64.zero,this.totalCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gb).fromBinary(t,r)}static fromJson(t,r){return(new gb).fromJson(t,r)}static fromJsonString(t,r){return(new gb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gb,t,r)}static $(){return["GetAggregatedUsageEventsResponse.ModelUsageAggregation|1 model_intent 9|2 input_tokens 3|3 output_tokens 3|4 cache_write_tokens 3|5 cache_read_tokens 3|6 total_cents 1|7 request_cost 1?|8 tier 5?"]}}class _b extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _b).fromBinary(t,r)}static fromJson(t,r){return(new _b).fromJson(t,r)}static fromJsonString(t,r){return(new _b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_b,t,r)}static $(){return["GetAuditLogsRequest|1 team_id 5?|2 start_date 3?|3 end_date 3?|4 event_type 9?|5 search 9?|6 page 5?|7 page_size 5?|8 application_type 9?|9 actor_api_key_id 9?|10 actor_api_key_kind 9?"]}}class Jb extends T{constructor(t){super(),this.events=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jb).fromBinary(t,r)}static fromJson(t,r){return(new Jb).fromJson(t,r)}static fromJsonString(t,r){return(new Jb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jb,t,r)}static $(){return["GetAuditLogsResponse|1 events #0*|2 total_count 5",bb]}}class wb extends T{constructor(t){super(),this.taskHandle="",this.createdAtMs=n.protoInt64.zero,this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wb).fromBinary(t,r)}static fromJson(t,r){return(new wb).fromJson(t,r)}static fromJsonString(t,r){return(new wb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wb,t,r)}static $(){return["TeamDataExportArchive|1 task_handle 9|2 created_at_ms 3|3 size_bytes 3"]}}class yb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yb).fromBinary(t,r)}static fromJson(t,r){return(new yb).fromJson(t,r)}static fromJsonString(t,r){return(new yb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yb,t,r)}static $(){return["ListTeamDataExportsRequest|1 team_id 5?"]}}class Sb extends T{constructor(t){super(),this.archives=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sb).fromBinary(t,r)}static fromJson(t,r){return(new Sb).fromJson(t,r)}static fromJsonString(t,r){return(new Sb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sb,t,r)}static $(){return["ListTeamDataExportsResponse|1 archives #0*",wb]}}class qb extends T{constructor(t){super(),this.taskHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qb).fromBinary(t,r)}static fromJson(t,r){return(new qb).fromJson(t,r)}static fromJsonString(t,r){return(new qb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qb,t,r)}static $(){return["CreateTeamDataExportDownloadUrlRequest|1 team_id 5?|2 task_handle 9"]}}class Bb extends T{constructor(t){super(),this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bb).fromBinary(t,r)}static fromJson(t,r){return(new Bb).fromJson(t,r)}static fromJsonString(t,r){return(new Bb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bb,t,r)}static $(){return["CreateTeamDataExportDownloadUrlResponse|1 url 9|2 expires_at_ms 3"]}}class Ib extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ib).fromBinary(t,r)}static fromJson(t,r){return(new Ib).fromJson(t,r)}static fromJsonString(t,r){return(new Ib).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ib,t,r)}static $(){return["GetOrganizationAuditLogsRequest|1 organization_id 9|2 team_id 5?|3 start_date 3?|4 end_date 3?|5 event_type 9?|6 search 9?|7 page 5?|8 page_size 5?|9 application_type 9?|10 actor_api_key_id 9?|11 actor_api_key_kind 9?"]}}class Pb extends T{constructor(t){super(),this.events=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pb).fromBinary(t,r)}static fromJson(t,r){return(new Pb).fromJson(t,r)}static fromJsonString(t,r){return(new Pb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pb,t,r)}static $(){return["GetOrganizationAuditLogsResponse|1 events #0*|2 total_count 5",bb]}}class bb extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.createdAt="",this.eventId="",this.timestamp="",this.requestId="",this.authId="",this.ghostMode=!1,this.teamId="",this.ipAddress="",this.userEmail="",this.eventType="",this.eventData="",this.orgId="",this.applicationType="",this.actorApiKeyKind="",this.actorApiKeyId="",this.actorApiKeyName="",this.actorDelegatedUserEmail="",this.userId="",this.clientType="",this.clientVersion="",this.clientOs="",this.clientOsVersion="",this.clientDeviceType="",this.clientUserAgent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bb).fromBinary(t,r)}static fromJson(t,r){return(new bb).fromJson(t,r)}static fromJsonString(t,r){return(new bb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bb,t,r)}static $(){return["AuditLogEvent|1 id 3|2 created_at 9|3 event_id 9|4 timestamp 9|5 request_id 9|6 auth_id 9|7 ghost_mode 8|8 team_id 9|9 ip_address 9|10 user_email 9|11 event_type 9|12 event_data 9|13 org_id 9|14 application_type 9|15 actor_api_key_kind 9|16 actor_api_key_id 9|17 actor_api_key_name 9|18 actor_delegated_user_email 9|19 user_id 9|20 client_type 9|21 client_version 9|22 client_os 9|23 client_os_version 9|24 client_device_type 9|25 client_user_agent 9"]}}class Rb extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rb).fromBinary(t,r)}static fromJson(t,r){return(new Rb).fromJson(t,r)}static fromJsonString(t,r){return(new Rb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rb,t,r)}static $(){return["RevokeTeamInviteLinkRequest|1 invite_code 9"]}}class vb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vb).fromBinary(t,r)}static fromJson(t,r){return(new vb).fromJson(t,r)}static fromJsonString(t,r){return(new vb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vb,t,r)}static $(){return["RevokeTeamInviteLinkResponse"]}}class xb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xb).fromBinary(t,r)}static fromJson(t,r){return(new xb).fromJson(t,r)}static fromJsonString(t,r){return(new xb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xb,t,r)}static $(){return["ListTeamInviteLinksRequest|1 team_id 5|2 castle_request_token 9?"]}}class kb extends T{constructor(t){super(),this.inviteLink="",this.validUntil=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kb).fromBinary(t,r)}static fromJson(t,r){return(new kb).fromJson(t,r)}static fromJsonString(t,r){return(new kb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kb,t,r)}static $(){return["InviteLinkInfo|1 invite_link 9|2 valid_until 3"]}}class Eb extends T{constructor(t){super(),this.inviteLinks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eb).fromBinary(t,r)}static fromJson(t,r){return(new Eb).fromJson(t,r)}static fromJsonString(t,r){return(new Eb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eb,t,r)}static $(){return["ListTeamInviteLinksResponse|1 invite_links #0*",kb]}}class Cb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cb).fromBinary(t,r)}static fromJson(t,r){return(new Cb).fromJson(t,r)}static fromJsonString(t,r){return(new Cb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cb,t,r)}static $(){return["ListTeamInviteLinksInternalRequest|1 team_id 5"]}}class Tb extends T{constructor(t){super(),this.inviteId="",this.validUntilMs=n.protoInt64.zero,this.kind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tb).fromBinary(t,r)}static fromJson(t,r){return(new Tb).fromJson(t,r)}static fromJsonString(t,r){return(new Tb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tb,t,r)}static $(){return["InternalTeamInviteLink|1 invite_id 9|2 valid_until_ms 3|3 kind 9|4 creator_user_id 5?|5 created_at_ms 3?"]}}class Ub extends T{constructor(t){super(),this.inviteLinks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ub).fromBinary(t,r)}static fromJson(t,r){return(new Ub).fromJson(t,r)}static fromJsonString(t,r){return(new Ub).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ub,t,r)}static $(){return["ListTeamInviteLinksInternalResponse|1 invite_links #0*",Tb]}}class Ab extends T{constructor(t){super(),this.teamId=0,this.inviteIds=[],this.revokeAll=!1,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ab).fromBinary(t,r)}static fromJson(t,r){return(new Ab).fromJson(t,r)}static fromJsonString(t,r){return(new Ab).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ab,t,r)}static $(){return["RevokeTeamInviteLinksInternalRequest|1 team_id 5|2 invite_ids 9*|3 revoke_all 8|4 reason 9"]}}class $b extends T{constructor(t){super(),this.inviteId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $b).fromBinary(t,r)}static fromJson(t,r){return(new $b).fromJson(t,r)}static fromJsonString(t,r){return(new $b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($b,t,r)}static $(){return["RevokeTeamInviteLinksInternalFailure|1 invite_id 9|2 message 9"]}}class Mb extends T{constructor(t){super(),this.revokedInviteIds=[],this.failures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mb).fromBinary(t,r)}static fromJson(t,r){return(new Mb).fromJson(t,r)}static fromJsonString(t,r){return(new Mb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mb,t,r)}static $(){return["RevokeTeamInviteLinksInternalResponse|1 revoked_invite_ids 9*|2 failures #0*",$b]}}class Ob extends T{constructor(t){super(),this.inviteId="",this.email="",this.role=it.UNSPECIFIED,this.expiresAt=n.protoInt64.zero,this.purchaseState=Dr.UNSPECIFIED,this.canResend=!1,this.recipientJoined=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ob).fromBinary(t,r)}static fromJson(t,r){return(new Ob).fromJson(t,r)}static fromJsonString(t,r){return(new Ob).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ob,t,r)}static $(){return["TeamPendingInvite|1 invite_id 9|2 email 9|3 role #0|4 billing_tier #1?|5 invited_by_email 9?|6 created_at 3?|7 expires_at 3|8 purchase_state #2|9 purchase_attempt 5?|10 can_resend 8|11 recipient_joined 8|12 merged_seat_tier #3?",it,ot,Dr,at]}}class Db extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Db).fromBinary(t,r)}static fromJson(t,r){return(new Db).fromJson(t,r)}static fromJsonString(t,r){return(new Db).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Db,t,r)}static $(){return["ListTeamPendingInvitesRequest|1 team_id 5"]}}class Nb extends T{constructor(t){super(),this.invites=[],this.membershipManaged=!1,this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nb).fromBinary(t,r)}static fromJson(t,r){return(new Nb).fromJson(t,r)}static fromJsonString(t,r){return(new Nb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nb,t,r)}static $(){return["ListTeamPendingInvitesResponse|1 invites #0*|2 membership_managed 8|3 truncated 8",Ob]}}class Gb extends T{constructor(t){super(),this.teamId=0,this.inviteId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gb).fromBinary(t,r)}static fromJson(t,r){return(new Gb).fromJson(t,r)}static fromJsonString(t,r){return(new Gb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gb,t,r)}static $(){return["RevokeTeamPendingInviteRequest|1 team_id 5|2 invite_id 9"]}}class Lb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lb).fromBinary(t,r)}static fromJson(t,r){return(new Lb).fromJson(t,r)}static fromJsonString(t,r){return(new Lb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lb,t,r)}static $(){return["RevokeTeamPendingInviteResponse"]}}class Fb extends T{constructor(t){super(),this.teamId=0,this.inviteId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fb).fromBinary(t,r)}static fromJson(t,r){return(new Fb).fromJson(t,r)}static fromJsonString(t,r){return(new Fb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fb,t,r)}static $(){return["ResendTeamPendingInviteRequest|1 team_id 5|2 invite_id 9|3 castle_request_token 9?"]}}class Kb extends T{constructor(t){super(),this.expiresAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kb).fromBinary(t,r)}static fromJson(t,r){return(new Kb).fromJson(t,r)}static fromJsonString(t,r){return(new Kb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kb,t,r)}static $(){return["ResendTeamPendingInviteResponse|1 expires_at 3"]}}class zb extends T{constructor(t){super(),this.requestId=n.protoInt64.zero,this.requesterUserId=0,this.requesterName="",this.requesterEmail="",this.requestedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zb).fromBinary(t,r)}static fromJson(t,r){return(new zb).fromJson(t,r)}static fromJsonString(t,r){return(new zb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zb,t,r)}static $(){return["TeamJoinRequest|1 request_id 3|2 requester_user_id 5|3 requester_name 9|4 requester_email 9|5 requested_at 3"]}}class jb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jb).fromBinary(t,r)}static fromJson(t,r){return(new jb).fromJson(t,r)}static fromJsonString(t,r){return(new jb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jb,t,r)}static $(){return["ListTeamJoinRequestsRequest|1 team_id 5"]}}class Hb extends T{constructor(t){super(),this.requests=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hb).fromBinary(t,r)}static fromJson(t,r){return(new Hb).fromJson(t,r)}static fromJsonString(t,r){return(new Hb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hb,t,r)}static $(){return["ListTeamJoinRequestsResponse|1 requests #0*|2 truncated 8",zb]}}class Wb extends T{constructor(t){super(),this.teamId=0,this.requestId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wb).fromBinary(t,r)}static fromJson(t,r){return(new Wb).fromJson(t,r)}static fromJsonString(t,r){return(new Wb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wb,t,r)}static $(){return["ApproveTeamJoinRequestRequest|1 team_id 5|2 request_id 3"]}}class Qb extends T{constructor(t){super(),this.waitingForSeat=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qb).fromBinary(t,r)}static fromJson(t,r){return(new Qb).fromJson(t,r)}static fromJsonString(t,r){return(new Qb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qb,t,r)}static $(){return["ApproveTeamJoinRequestResponse|1 waiting_for_seat 8"]}}class Vb extends T{constructor(t){super(),this.teamId=0,this.requestId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vb).fromBinary(t,r)}static fromJson(t,r){return(new Vb).fromJson(t,r)}static fromJsonString(t,r){return(new Vb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vb,t,r)}static $(){return["DenyTeamJoinRequestRequest|1 team_id 5|2 request_id 3"]}}class Xb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xb).fromBinary(t,r)}static fromJson(t,r){return(new Xb).fromJson(t,r)}static fromJsonString(t,r){return(new Xb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xb,t,r)}static $(){return["DenyTeamJoinRequestResponse"]}}class Yb extends T{constructor(t){super(),this.teamId=0,this.requiresApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yb).fromBinary(t,r)}static fromJson(t,r){return(new Yb).fromJson(t,r)}static fromJsonString(t,r){return(new Yb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yb,t,r)}static $(){return["UpdateTeamInviteLinkJoinApprovalSettingRequest|1 team_id 5|2 requires_approval 8"]}}class Zb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zb).fromBinary(t,r)}static fromJson(t,r){return(new Zb).fromJson(t,r)}static fromJsonString(t,r){return(new Zb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zb,t,r)}static $(){return["UpdateTeamInviteLinkJoinApprovalSettingResponse"]}}class tR extends T{constructor(t){super(),this.firstName="",this.lastName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tR).fromBinary(t,r)}static fromJson(t,r){return(new tR).fromJson(t,r)}static fromJsonString(t,r){return(new tR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tR,t,r)}static $(){return["UpdateUserNameRequest|1 first_name 9|2 last_name 9"]}}class rR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rR).fromBinary(t,r)}static fromJson(t,r){return(new rR).fromJson(t,r)}static fromJsonString(t,r){return(new rR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rR,t,r)}static $(){return["UpdateUserNameResponse"]}}class eR extends T{constructor(t){super(),this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eR).fromBinary(t,r)}static fromJson(t,r){return(new eR).fromJson(t,r)}static fromJsonString(t,r){return(new eR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eR,t,r)}static $(){return["UploadUserProfilePictureRequest|1 content_type 9|2 bytes 12"]}}class nR extends T{constructor(t){super(),this.profilePictureUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nR).fromBinary(t,r)}static fromJson(t,r){return(new nR).fromJson(t,r)}static fromJsonString(t,r){return(new nR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nR,t,r)}static $(){return["UploadUserProfilePictureResponse|1 profile_picture_url 9"]}}class sR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sR).fromBinary(t,r)}static fromJson(t,r){return(new sR).fromJson(t,r)}static fromJsonString(t,r){return(new sR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sR,t,r)}static $(){return["UpdateUserProfilePictureRequest|1 profile_picture_url 9?"]}}class iR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iR).fromBinary(t,r)}static fromJson(t,r){return(new iR).fromJson(t,r)}static fromJsonString(t,r){return(new iR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iR,t,r)}static $(){return["UpdateUserProfilePictureResponse|1 profile_picture_url 9?"]}}class oR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oR).fromBinary(t,r)}static fromJson(t,r){return(new oR).fromJson(t,r)}static fromJsonString(t,r){return(new oR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oR,t,r)}static $(){return["ListInvoicesRequest|1 team_id 5?|2 page 5?|3 page_size 5?|4 status 9?"]}}class aR extends T{constructor(t){super(),this.invoiceId="",this.date=n.protoInt64.zero,this.amountCents=0,this.currency="",this.status="",this.hostedInvoiceUrl="",this.refundAmount=0,this.description="",this.isMidMonthInvoice=!1,this.invoicePdfUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aR).fromBinary(t,r)}static fromJson(t,r){return(new aR).fromJson(t,r)}static fromJsonString(t,r){return(new aR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aR,t,r)}static $(){return["InvoiceInfo|1 invoice_id 9|2 date 3|3 amount_cents 5|4 currency 9|5 status 9|6 hosted_invoice_url 9|7 refund_amount 5|8 description 9|9 is_mid_month_invoice 8|10 invoice_pdf_url 9"]}}class uR extends T{constructor(t){super(),this.invoices=[],this.total=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uR).fromBinary(t,r)}static fromJson(t,r){return(new uR).fromJson(t,r)}static fromJsonString(t,r){return(new uR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uR,t,r)}static $(){return["ListInvoicesResponse|1 invoices #0*|2 total 5|3 total_pages 5|4 has_more 8?",aR]}}class cR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cR).fromBinary(t,r)}static fromJson(t,r){return(new cR).fromJson(t,r)}static fromJsonString(t,r){return(new cR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cR,t,r)}static $(){return["GetComplatCreditBalanceRequest|1 team_id 5?"]}}class lR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lR).fromBinary(t,r)}static fromJson(t,r){return(new lR).fromJson(t,r)}static fromJsonString(t,r){return(new lR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lR,t,r)}static $(){return["GetComplatCreditBalanceResponse|1 usd_remaining_cents 3?|2 cursor_credit_pending_cents 3?|3 cursor_credit_refund_requested_cents 3?|4 cursor_credit_in_flight_cents 3?"]}}class mR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mR).fromBinary(t,r)}static fromJson(t,r){return(new mR).fromJson(t,r)}static fromJsonString(t,r){return(new mR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mR,t,r)}static $(){return["ListBlockingCheckoutInvoicesRequest"]}}class fR extends T{constructor(t){super(),this.invoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fR).fromBinary(t,r)}static fromJson(t,r){return(new fR).fromJson(t,r)}static fromJsonString(t,r){return(new fR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fR,t,r)}static $(){return["ListBlockingCheckoutInvoicesResponse|1 invoices #0*",aR]}}class dR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dR).fromBinary(t,r)}static fromJson(t,r){return(new dR).fromJson(t,r)}static fromJsonString(t,r){return(new dR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dR,t,r)}static $(){return["ListPayableTeamInvoicesRequest"]}}class pR extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.subscriptionStatus="",this.invoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pR).fromBinary(t,r)}static fromJson(t,r){return(new pR).fromJson(t,r)}static fromJsonString(t,r){return(new pR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pR,t,r)}static $(){return["PayableTeamInvoices|1 team_id 5|2 team_name 9|3 subscription_status 9|4 invoices #0*",aR]}}class hR extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hR).fromBinary(t,r)}static fromJson(t,r){return(new hR).fromJson(t,r)}static fromJsonString(t,r){return(new hR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hR,t,r)}static $(){return["ListPayableTeamInvoicesResponse|1 teams #0*",pR]}}class gR extends T{constructor(t){super(),this.inferredPrivacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gR).fromBinary(t,r)}static fromJson(t,r){return(new gR).fromJson(t,r)}static fromJsonString(t,r){return(new gR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gR,t,r)}static $(){return["GetUserPrivacyModeRequest|1 inferred_privacy_mode #0|2 team_id 5?",s.Y]}}class _R extends T{constructor(t){super(),this.privacyMode=s.Y.UNSPECIFIED,this.hoursRemainingInGracePeriod=0,this.isEnforcedByTeam=!1,this.isNotMigratedToServerSourceOfTruth=!1,this.partnerDataShare=!1,this.hasAcknowledgedGracePeriodDisclaimer=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _R).fromBinary(t,r)}static fromJson(t,r){return(new _R).fromJson(t,r)}static fromJsonString(t,r){return(new _R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_R,t,r)}static $(){return["GetUserPrivacyModeResponse|1 privacy_mode #0|2 hours_remaining_in_grace_period 5|3 is_enforced_by_team 8|4 is_not_migrated_to_server_source_of_truth 8|5 partner_data_share 8|6 has_acknowledged_grace_period_disclaimer 8|7 account_privacy_mode #0?",s.Y]}}class JR extends T{constructor(t){super(),this.privacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JR).fromBinary(t,r)}static fromJson(t,r){return(new JR).fromJson(t,r)}static fromJsonString(t,r){return(new JR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JR,t,r)}static $(){return["SetUserPrivacyModeRequest|1 privacy_mode #0",s.Y]}}class wR extends T{constructor(t){super(),this.usageResetPerformed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wR).fromBinary(t,r)}static fromJson(t,r){return(new wR).fromJson(t,r)}static fromJsonString(t,r){return(new wR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wR,t,r)}static $(){return["SetUserPrivacyModeResponse|1 usage_reset_performed 8"]}}class yR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yR).fromBinary(t,r)}static fromJson(t,r){return(new yR).fromJson(t,r)}static fromJsonString(t,r){return(new yR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yR,t,r)}static $(){return["WebAcknowledgeGracePeriodDisclaimerRequest"]}}class SR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SR).fromBinary(t,r)}static fromJson(t,r){return(new SR).fromJson(t,r)}static fromJsonString(t,r){return(new SR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SR,t,r)}static $(){return["WebAcknowledgeGracePeriodDisclaimerResponse"]}}class qR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qR).fromBinary(t,r)}static fromJson(t,r){return(new qR).fromJson(t,r)}static fromJsonString(t,r){return(new qR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qR,t,r)}static $(){return["SkipPrivacyModeGracePeriodRequest"]}}class BR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BR).fromBinary(t,r)}static fromJson(t,r){return(new BR).fromJson(t,r)}static fromJsonString(t,r){return(new BR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BR,t,r)}static $(){return["SkipPrivacyModeGracePeriodResponse"]}}class IR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IR).fromBinary(t,r)}static fromJson(t,r){return(new IR).fromJson(t,r)}static fromJsonString(t,r){return(new IR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IR,t,r)}static $(){return["NeedsPrivacyModeMigrationRequest"]}}class PR extends T{constructor(t){super(),this.needsMigration=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PR).fromBinary(t,r)}static fromJson(t,r){return(new PR).fromJson(t,r)}static fromJsonString(t,r){return(new PR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PR,t,r)}static $(){return["NeedsPrivacyModeMigrationResponse|1 needs_migration 8"]}}class bR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bR).fromBinary(t,r)}static fromJson(t,r){return(new bR).fromJson(t,r)}static fromJsonString(t,r){return(new bR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bR,t,r)}static $(){return["GetRemainingRefundsRequest"]}}class RR extends T{constructor(t){super(),this.remainingRefunds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RR).fromBinary(t,r)}static fromJson(t,r){return(new RR).fromJson(t,r)}static fromJsonString(t,r){return(new RR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RR,t,r)}static $(){return["GetRemainingRefundsResponse|1 remaining_refunds 5"]}}class vR extends T{constructor(t){super(),this.serviceType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vR).fromBinary(t,r)}static fromJson(t,r){return(new vR).fromJson(t,r)}static fromJsonString(t,r){return(new vR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vR,t,r)}static $(){return["GetServiceAccountSpendLimitRequest|1 team_id 5?|2 service_type 9|3 service_account_id 9?"]}}class xR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xR).fromBinary(t,r)}static fromJson(t,r){return(new xR).fromJson(t,r)}static fromJsonString(t,r){return(new xR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xR,t,r)}static $(){return["GetServiceAccountSpendLimitResponse|1 spend_limit_cents 5?|2 current_spend_cents 5?|3 is_in_free_trial 8?|4 free_trial_expires_at 3?"]}}class kR extends T{constructor(t){super(),this.serviceType="",this.spendLimitCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kR).fromBinary(t,r)}static fromJson(t,r){return(new kR).fromJson(t,r)}static fromJsonString(t,r){return(new kR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kR,t,r)}static $(){return["SetServiceAccountSpendLimitRequest|1 team_id 5?|2 service_type 9|3 spend_limit_cents 5|4 service_account_id 9?|5 clear_spend_limit 8?"]}}class ER extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ER).fromBinary(t,r)}static fromJson(t,r){return(new ER).fromJson(t,r)}static fromJsonString(t,r){return(new ER).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ER,t,r)}static $(){return["SetServiceAccountSpendLimitResponse|1 success 8"]}}class CR extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.hardLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CR).fromBinary(t,r)}static fromJson(t,r){return(new CR).fromJson(t,r)}static fromJsonString(t,r){return(new CR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CR,t,r)}static $(){return["SetUserHardLimitRequest|1 team_id 5|2 user_id 5|3 hard_limit_dollars 5"]}}class TR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TR).fromBinary(t,r)}static fromJson(t,r){return(new TR).fromJson(t,r)}static fromJsonString(t,r){return(new TR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TR,t,r)}static $(){return["SetUserHardLimitResponse"]}}class UR extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.monthlyLimitDollars=0,this.clearFirstPartyModelsAdditionalBudgetDollars=!1,this.clearFirstPartyModelsAdditionalBudgetUnlimited=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UR).fromBinary(t,r)}static fromJson(t,r){return(new UR).fromJson(t,r)}static fromJsonString(t,r){return(new UR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UR,t,r)}static $(){return["SetUserMonthlyLimitRequest|1 team_id 5|2 user_id 5|3 monthly_limit_dollars 5|4 first_party_models_additional_budget_dollars 5?|5 clear_first_party_models_additional_budget_dollars 8|6 first_party_models_additional_budget_unlimited 8?|7 clear_first_party_models_additional_budget_unlimited 8"]}}class AR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AR).fromBinary(t,r)}static fromJson(t,r){return(new AR).fromJson(t,r)}static fromJsonString(t,r){return(new AR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AR,t,r)}static $(){return["SetUserMonthlyLimitResponse"]}}class $R extends T{constructor(t){super(),this.teamId=0,this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $R).fromBinary(t,r)}static fromJson(t,r){return(new $R).fromJson(t,r)}static fromJsonString(t,r){return(new $R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($R,t,r)}static $(){return["SetTeamNoZdrModelConsentRequest|1 team_id 5|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class MR extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MR).fromBinary(t,r)}static fromJson(t,r){return(new MR).fromJson(t,r)}static fromJsonString(t,r){return(new MR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MR,t,r)}static $(){return["SetTeamNoZdrModelConsentResponse|1 consented 8"]}}class OR extends T{constructor(t){super(),this.organizationId="",this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OR).fromBinary(t,r)}static fromJson(t,r){return(new OR).fromJson(t,r)}static fromJsonString(t,r){return(new OR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OR,t,r)}static $(){return["SetOrganizationNoZdrModelConsentRequest|1 organization_id 9|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class DR extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DR).fromBinary(t,r)}static fromJson(t,r){return(new DR).fromJson(t,r)}static fromJsonString(t,r){return(new DR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DR,t,r)}static $(){return["SetOrganizationNoZdrModelConsentResponse|1 consented 8"]}}class NR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NR).fromBinary(t,r)}static fromJson(t,r){return(new NR).fromJson(t,r)}static fromJsonString(t,r){return(new NR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NR,t,r)}static $(){return["GetOrganizationOnDemandSpendDisabledRequest|1 organization_id 9"]}}class GR extends T{constructor(t){super(),this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GR).fromBinary(t,r)}static fromJson(t,r){return(new GR).fromJson(t,r)}static fromJsonString(t,r){return(new GR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GR,t,r)}static $(){return["GetOrganizationOnDemandSpendDisabledResponse|1 disabled 8"]}}class LR extends T{constructor(t){super(),this.organizationId="",this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LR).fromBinary(t,r)}static fromJson(t,r){return(new LR).fromJson(t,r)}static fromJsonString(t,r){return(new LR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LR,t,r)}static $(){return["SetOrganizationOnDemandSpendDisabledRequest|1 organization_id 9|2 disabled 8"]}}class FR extends T{constructor(t){super(),this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FR).fromBinary(t,r)}static fromJson(t,r){return(new FR).fromJson(t,r)}static fromJsonString(t,r){return(new FR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FR,t,r)}static $(){return["SetOrganizationOnDemandSpendDisabledResponse|1 disabled 8"]}}class KR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KR).fromBinary(t,r)}static fromJson(t,r){return(new KR).fromJson(t,r)}static fromJsonString(t,r){return(new KR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KR,t,r)}static $(){return["GetOrganizationCreditRequestButtonHiddenRequest|1 organization_id 9"]}}class zR extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zR).fromBinary(t,r)}static fromJson(t,r){return(new zR).fromJson(t,r)}static fromJsonString(t,r){return(new zR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zR,t,r)}static $(){return["GetOrganizationCreditRequestButtonHiddenResponse|1 hidden 8"]}}class jR extends T{constructor(t){super(),this.organizationId="",this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jR).fromBinary(t,r)}static fromJson(t,r){return(new jR).fromJson(t,r)}static fromJsonString(t,r){return(new jR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jR,t,r)}static $(){return["SetOrganizationCreditRequestButtonHiddenRequest|1 organization_id 9|2 hidden 8"]}}class HR extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HR).fromBinary(t,r)}static fromJson(t,r){return(new HR).fromJson(t,r)}static fromJsonString(t,r){return(new HR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HR,t,r)}static $(){return["SetOrganizationCreditRequestButtonHiddenResponse|1 hidden 8"]}}class WR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WR).fromBinary(t,r)}static fromJson(t,r){return(new WR).fromJson(t,r)}static fromJsonString(t,r){return(new WR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WR,t,r)}static $(){return["GetOrganizationSsoJitAutoEnrollmentRequest|1 organization_id 9"]}}class QR extends T{constructor(t){super(),this.enabled=!1,this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QR).fromBinary(t,r)}static fromJson(t,r){return(new QR).fromJson(t,r)}static fromJsonString(t,r){return(new QR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QR,t,r)}static $(){return["GetOrganizationSsoJitAutoEnrollmentResponse|1 enabled 8|2 configured 8"]}}class VR extends T{constructor(t){super(),this.organizationId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VR).fromBinary(t,r)}static fromJson(t,r){return(new VR).fromJson(t,r)}static fromJsonString(t,r){return(new VR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VR,t,r)}static $(){return["SetOrganizationSsoJitAutoEnrollmentRequest|1 organization_id 9|2 enabled 8"]}}class XR extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XR).fromBinary(t,r)}static fromJson(t,r){return(new XR).fromJson(t,r)}static fromJsonString(t,r){return(new XR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XR,t,r)}static $(){return["SetOrganizationSsoJitAutoEnrollmentResponse|1 enabled 8"]}}class YR extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YR).fromBinary(t,r)}static fromJson(t,r){return(new YR).fromJson(t,r)}static fromJsonString(t,r){return(new YR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YR,t,r)}static $(){return["GetTeamSsoJitAutoEnrollmentRequest|1 team_id 5"]}}class ZR extends T{constructor(t){super(),this.enabled=!1,this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZR).fromBinary(t,r)}static fromJson(t,r){return(new ZR).fromJson(t,r)}static fromJsonString(t,r){return(new ZR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZR,t,r)}static $(){return["GetTeamSsoJitAutoEnrollmentResponse|1 enabled 8|2 available 8"]}}class tv extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tv).fromBinary(t,r)}static fromJson(t,r){return(new tv).fromJson(t,r)}static fromJsonString(t,r){return(new tv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tv,t,r)}static $(){return["SetTeamSsoJitAutoEnrollmentRequest|1 team_id 5|2 enabled 8"]}}class rv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rv).fromBinary(t,r)}static fromJson(t,r){return(new rv).fromJson(t,r)}static fromJsonString(t,r){return(new rv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rv,t,r)}static $(){return["SetTeamSsoJitAutoEnrollmentResponse|1 enabled 8"]}}class ev extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ev).fromBinary(t,r)}static fromJson(t,r){return(new ev).fromJson(t,r)}static fromJsonString(t,r){return(new ev).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ev,t,r)}static $(){return["GetTeamXAccountLinkingRequest|1 team_id 5"]}}class nv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nv).fromBinary(t,r)}static fromJson(t,r){return(new nv).fromJson(t,r)}static fromJsonString(t,r){return(new nv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nv,t,r)}static $(){return["SetTeamXAccountLinkingRequest|1 team_id 5|2 allowed 8?"]}}class sv extends T{constructor(t){super(),this.available=!1,this.editable=!1,this.allowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sv).fromBinary(t,r)}static fromJson(t,r){return(new sv).fromJson(t,r)}static fromJsonString(t,r){return(new sv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sv,t,r)}static $(){return["TeamXAccountLinking|1 available 8|2 editable 8|3 allowed 8"]}}class iv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iv).fromBinary(t,r)}static fromJson(t,r){return(new iv).fromJson(t,r)}static fromJsonString(t,r){return(new iv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iv,t,r)}static $(){return["GetOrganizationRemoteControlSettingsRequest|1 organization_id 9"]}}class ov extends T{constructor(t){super(),this.isEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ov).fromBinary(t,r)}static fromJson(t,r){return(new ov).fromJson(t,r)}static fromJsonString(t,r){return(new ov).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ov,t,r)}static $(){return["GetOrganizationRemoteControlSettingsResponse|1 settings #0|2 is_enterprise 8",d]}}class av extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new av).fromBinary(t,r)}static fromJson(t,r){return(new av).fromJson(t,r)}static fromJsonString(t,r){return(new av).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(av,t,r)}static $(){return["UpdateOrganizationRemoteControlSettingsRequest|1 organization_id 9|2 enabled 8?|3 automatic_registration_enabled 8?"]}}class uv extends T{constructor(t){super(),this.isEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uv).fromBinary(t,r)}static fromJson(t,r){return(new uv).fromJson(t,r)}static fromJsonString(t,r){return(new uv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uv,t,r)}static $(){return["UpdateOrganizationRemoteControlSettingsResponse|1 settings #0|2 is_enterprise 8",d]}}class cv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cv).fromBinary(t,r)}static fromJson(t,r){return(new cv).fromJson(t,r)}static fromJsonString(t,r){return(new cv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cv,t,r)}static $(){return["GetOrganizationSlackManagedWorkspacesRequest|1 organization_id 9"]}}class lv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lv).fromBinary(t,r)}static fromJson(t,r){return(new lv).fromJson(t,r)}static fromJsonString(t,r){return(new lv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lv,t,r)}static $(){return["GetOrganizationSlackManagedWorkspacesResponse|1 managed_workspaces #0|2 enabled 8",xJ]}}class mv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mv).fromBinary(t,r)}static fromJson(t,r){return(new mv).fromJson(t,r)}static fromJsonString(t,r){return(new mv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mv,t,r)}static $(){return["UpdateOrganizationSlackManagedWorkspacesRequest|1 organization_id 9|2 managed_workspaces #0",xJ]}}class fv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fv).fromBinary(t,r)}static fromJson(t,r){return(new fv).fromJson(t,r)}static fromJsonString(t,r){return(new fv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fv,t,r)}static $(){return["UpdateOrganizationSlackManagedWorkspacesResponse|1 managed_workspaces #0|2 enabled 8",xJ]}}class dv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dv).fromBinary(t,r)}static fromJson(t,r){return(new dv).fromJson(t,r)}static fromJsonString(t,r){return(new dv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dv,t,r)}static $(){return["GetOrganizationSlackInboundInstallPolicyRequest|1 organization_id 9"]}}class pv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pv).fromBinary(t,r)}static fromJson(t,r){return(new pv).fromJson(t,r)}static fromJsonString(t,r){return(new pv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pv,t,r)}static $(){return["GetOrganizationSlackInboundInstallPolicyResponse|1 inbound_install_policy #0|2 enabled 8",kJ]}}class hv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hv).fromBinary(t,r)}static fromJson(t,r){return(new hv).fromJson(t,r)}static fromJsonString(t,r){return(new hv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hv,t,r)}static $(){return["UpdateOrganizationSlackInboundInstallPolicyRequest|1 organization_id 9|2 inbound_install_policy #0",kJ]}}class gv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gv).fromBinary(t,r)}static fromJson(t,r){return(new gv).fromJson(t,r)}static fromJsonString(t,r){return(new gv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gv,t,r)}static $(){return["UpdateOrganizationSlackInboundInstallPolicyResponse|1 inbound_install_policy #0|2 enabled 8",kJ]}}class _v extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _v).fromBinary(t,r)}static fromJson(t,r){return(new _v).fromJson(t,r)}static fromJsonString(t,r){return(new _v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_v,t,r)}static $(){return["GetOrganizationGoogleDriveBlockedSharedDrivesRequest|1 organization_id 9"]}}class Jv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jv).fromBinary(t,r)}static fromJson(t,r){return(new Jv).fromJson(t,r)}static fromJsonString(t,r){return(new Jv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jv,t,r)}static $(){return["GetOrganizationGoogleDriveBlockedSharedDrivesResponse|1 blocked_shared_drives #0|2 enabled 8",CJ]}}class wv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wv).fromBinary(t,r)}static fromJson(t,r){return(new wv).fromJson(t,r)}static fromJsonString(t,r){return(new wv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wv,t,r)}static $(){return["UpdateOrganizationGoogleDriveBlockedSharedDrivesRequest|1 organization_id 9|2 blocked_shared_drives #0",CJ]}}class yv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yv).fromBinary(t,r)}static fromJson(t,r){return(new yv).fromJson(t,r)}static fromJsonString(t,r){return(new yv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yv,t,r)}static $(){return["UpdateOrganizationGoogleDriveBlockedSharedDrivesResponse|1 blocked_shared_drives #0|2 enabled 8",CJ]}}class Sv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sv).fromBinary(t,r)}static fromJson(t,r){return(new Sv).fromJson(t,r)}static fromJsonString(t,r){return(new Sv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sv,t,r)}static $(){return["GetOrganizationConnectorAccountOwnershipRequest|1 organization_id 9"]}}class qv extends T{constructor(t){super(),this.google=[],this.microsoft=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qv).fromBinary(t,r)}static fromJson(t,r){return(new qv).fromJson(t,r)}static fromJsonString(t,r){return(new qv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qv,t,r)}static $(){return["ConnectorAccountMembersOnlyDomains|1 google 9*|2 microsoft 9*"]}}class Bv extends T{constructor(t){super(),this.enabled=!1,this.verifiedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bv).fromBinary(t,r)}static fromJson(t,r){return(new Bv).fromJson(t,r)}static fromJsonString(t,r){return(new Bv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bv,t,r)}static $(){return["GetOrganizationConnectorAccountOwnershipResponse|2 enabled 8|3 verified_domains 9*|4 members_only_domains #0",qv]}}class Iv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iv).fromBinary(t,r)}static fromJson(t,r){return(new Iv).fromJson(t,r)}static fromJsonString(t,r){return(new Iv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iv,t,r)}static $(){return["UpdateOrganizationConnectorAccountOwnershipRequest|1 organization_id 9|3 members_only_domains #0",qv]}}class Pv extends T{constructor(t){super(),this.enabled=!1,this.verifiedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pv).fromBinary(t,r)}static fromJson(t,r){return(new Pv).fromJson(t,r)}static fromJsonString(t,r){return(new Pv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pv,t,r)}static $(){return["UpdateOrganizationConnectorAccountOwnershipResponse|2 enabled 8|3 verified_domains 9*|4 members_only_domains #0",qv]}}class bv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bv).fromBinary(t,r)}static fromJson(t,r){return(new bv).fromJson(t,r)}static fromJsonString(t,r){return(new bv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bv,t,r)}static $(){return["GetTeamRemoteControlSettingsRequest|1 team_id 5"]}}class Rv extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rv).fromBinary(t,r)}static fromJson(t,r){return(new Rv).fromJson(t,r)}static fromJsonString(t,r){return(new Rv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rv,t,r)}static $(){return["GetTeamRemoteControlSettingsResponse|1 settings #0|2 available 8|3 devices_available 8?",d]}}class vv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vv).fromBinary(t,r)}static fromJson(t,r){return(new vv).fromJson(t,r)}static fromJsonString(t,r){return(new vv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vv,t,r)}static $(){return["UpdateTeamRemoteControlSettingsRequest|1 team_id 5|2 enabled 8?|3 automatic_registration_enabled 8?"]}}class xv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xv).fromBinary(t,r)}static fromJson(t,r){return(new xv).fromJson(t,r)}static fromJsonString(t,r){return(new xv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xv,t,r)}static $(){return["UpdateTeamRemoteControlSettingsResponse|1 settings #0",d]}}class kv extends T{constructor(t){super(),this.organizationId="",this.search="",this.cursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kv).fromBinary(t,r)}static fromJson(t,r){return(new kv).fromJson(t,r)}static fromJsonString(t,r){return(new kv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kv,t,r)}static $(){return["ListOrganizationRemoteControlDevicesRequest|1 organization_id 9|2 search 9|3 cursor 9|4 page_size 5?"]}}class Ev extends T{constructor(t){super(),this.teamId=0,this.search="",this.cursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ev).fromBinary(t,r)}static fromJson(t,r){return(new Ev).fromJson(t,r)}static fromJsonString(t,r){return(new Ev).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ev,t,r)}static $(){return["ListTeamRemoteControlDevicesRequest|1 team_id 5|2 search 9|3 cursor 9|4 page_size 5?"]}}class Cv extends T{constructor(t){super(),this.computers=[],this.nextCursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cv).fromBinary(t,r)}static fromJson(t,r){return(new Cv).fromJson(t,r)}static fromJsonString(t,r){return(new Cv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cv,t,r)}static $(){return["ListRemoteControlDevicesResponse|1 computers #0*|2 next_cursor 9",Tv]}}class Tv extends T{constructor(t){super(),this.memberUserId=0,this.memberEmail="",this.memberName="",this.computerId="",this.computerName="",this.pairedDevices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tv).fromBinary(t,r)}static fromJson(t,r){return(new Tv).fromJson(t,r)}static fromJsonString(t,r){return(new Tv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tv,t,r)}static $(){return["RemoteControlComputerRow|1 member_user_id 5|2 member_email 9|3 member_name 9|4 computer_id 9|5 computer_name 9|6 last_used_at_ms 3?|7 paired_devices #0*",Uv]}}class Uv extends T{constructor(t){super(),this.thumbprint="",this.label="",this.pairedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uv).fromBinary(t,r)}static fromJson(t,r){return(new Uv).fromJson(t,r)}static fromJsonString(t,r){return(new Uv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uv,t,r)}static $(){return["RemoteControlPairedDevice|1 thumbprint 9|2 label 9|3 paired_at_ms 3|4 last_used_at_ms 3?"]}}class Av extends T{constructor(t){super(),this.organizationId="",this.memberUserId=0,this.device={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Av).fromBinary(t,r)}static fromJson(t,r){return(new Av).fromJson(t,r)}static fromJsonString(t,r){return(new Av).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Av,t,r)}static $(){return["RevokeOrganizationRemoteControlDeviceRequest|1 organization_id 9|2 member_user_id 5|3 computer_id 9 device|4 controller_thumbprint 9 device|5 all_devices 8 device"]}}class $v extends T{constructor(t){super(),this.teamId=0,this.memberUserId=0,this.device={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $v).fromBinary(t,r)}static fromJson(t,r){return(new $v).fromJson(t,r)}static fromJsonString(t,r){return(new $v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($v,t,r)}static $(){return["RevokeTeamRemoteControlDeviceRequest|1 team_id 5|2 member_user_id 5|3 computer_id 9 device|4 controller_thumbprint 9 device|5 all_devices 8 device"]}}class Mv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mv).fromBinary(t,r)}static fromJson(t,r){return(new Mv).fromJson(t,r)}static fromJsonString(t,r){return(new Mv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mv,t,r)}static $(){return["RevokeRemoteControlDeviceResponse"]}}class Ov extends T{constructor(t){super(),this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ov).fromBinary(t,r)}static fromJson(t,r){return(new Ov).fromJson(t,r)}static fromJsonString(t,r){return(new Ov).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ov,t,r)}static $(){return["SetUserNoZdrModelConsentRequest|1 model_id 9|2 enabled 8|3 acknowledged 8|4 consent_version 9"]}}class Dv extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dv).fromBinary(t,r)}static fromJson(t,r){return(new Dv).fromJson(t,r)}static fromJsonString(t,r){return(new Dv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dv,t,r)}static $(){return["SetUserNoZdrModelConsentResponse|1 consented 8"]}}class Nv extends T{constructor(t){super(),this.teamId=0,this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nv).fromBinary(t,r)}static fromJson(t,r){return(new Nv).fromJson(t,r)}static fromJsonString(t,r){return(new Nv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nv,t,r)}static $(){return["SetTeamMemberNoZdrModelConsentRequest|1 team_id 5|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class Gv extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gv).fromBinary(t,r)}static fromJson(t,r){return(new Gv).fromJson(t,r)}static fromJsonString(t,r){return(new Gv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gv,t,r)}static $(){return["SetTeamMemberNoZdrModelConsentResponse|1 consented 8"]}}class Lv extends T{constructor(t){super(),this.scope=Fv.UNSPECIFIED,this.teamId=0,this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lv).fromBinary(t,r)}static fromJson(t,r){return(new Lv).fromJson(t,r)}static fromJsonString(t,r){return(new Lv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lv,t,r)}static $(){return["GetNoZdrModelConsentStatusRequest|1 scope #0|2 team_id 5|3 organization_id 9",Fv]}}var Fv=(0,a.QT)(n.proto3,C,"GetNoZdrModelConsentStatusRequest.Scope",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"TEAM_MEMBER"],[3,"USER"],[4,"ORGANIZATION"]],1);class Kv extends T{constructor(t){super(),this.modelId="",this.consentVersion="",this.acceptedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kv).fromBinary(t,r)}static fromJson(t,r){return(new Kv).fromJson(t,r)}static fromJsonString(t,r){return(new Kv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kv,t,r)}static $(){return["NoZdrModelConsentStatusEntry|1 model_id 9|2 consent_version 9|3 accepted_at 9"]}}class zv extends T{constructor(t){super(),this.modelId="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zv).fromBinary(t,r)}static fromJson(t,r){return(new zv).fromJson(t,r)}static fromJsonString(t,r){return(new zv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zv,t,r)}static $(){return["NoZdrRestrictedModel|1 model_id 9|2 display_name 9"]}}class jv extends T{constructor(t){super(),this.consents=[],this.restrictedModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jv).fromBinary(t,r)}static fromJson(t,r){return(new jv).fromJson(t,r)}static fromJsonString(t,r){return(new jv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jv,t,r)}static $(){return["GetNoZdrModelConsentStatusResponse|1 consents #0*|2 restricted_models #1*",Kv,zv]}}class Hv extends T{constructor(t){super(),this.optOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hv).fromBinary(t,r)}static fromJson(t,r){return(new Hv).fromJson(t,r)}static fromJsonString(t,r){return(new Hv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hv,t,r)}static $(){return["ToggleMarketingEmailOptRequest|1 opt_out 8"]}}class Wv extends T{constructor(t){super(),this.optedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wv).fromBinary(t,r)}static fromJson(t,r){return(new Wv).fromJson(t,r)}static fromJsonString(t,r){return(new Wv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wv,t,r)}static $(){return["ToggleMarketingEmailOptResponse|1 opted_out 8"]}}class Qv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qv).fromBinary(t,r)}static fromJson(t,r){return(new Qv).fromJson(t,r)}static fromJsonString(t,r){return(new Qv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qv,t,r)}static $(){return["GetMarketingEmailOptRequest"]}}class Vv extends T{constructor(t){super(),this.optedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vv).fromBinary(t,r)}static fromJson(t,r){return(new Vv).fromJson(t,r)}static fromJsonString(t,r){return(new Vv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vv,t,r)}static $(){return["GetMarketingEmailOptResponse|1 opted_out 8"]}}class Xv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xv).fromBinary(t,r)}static fromJson(t,r){return(new Xv).fromJson(t,r)}static fromJsonString(t,r){return(new Xv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xv,t,r)}static $(){return["GetGlobalLeaderboardOptInRequest"]}}class Yv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yv).fromBinary(t,r)}static fromJson(t,r){return(new Yv).fromJson(t,r)}static fromJsonString(t,r){return(new Yv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yv,t,r)}static $(){return["GetGlobalLeaderboardOptInResponse|1 opted_in 8?"]}}class Zv extends T{constructor(t){super(),this.optedIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zv).fromBinary(t,r)}static fromJson(t,r){return(new Zv).fromJson(t,r)}static fromJsonString(t,r){return(new Zv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zv,t,r)}static $(){return["SetGlobalLeaderboardOptInRequest|1 opted_in 8"]}}class tx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tx).fromBinary(t,r)}static fromJson(t,r){return(new tx).fromJson(t,r)}static fromJsonString(t,r){return(new tx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tx,t,r)}static $(){return["SetGlobalLeaderboardOptInResponse"]}}class rx extends T{constructor(t){super(),this.teamId=0,this.newName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rx).fromBinary(t,r)}static fromJson(t,r){return(new rx).fromJson(t,r)}static fromJsonString(t,r){return(new rx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rx,t,r)}static $(){return["UpdateTeamNameRequest|1 team_id 5|2 new_name 9"]}}class ex extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ex).fromBinary(t,r)}static fromJson(t,r){return(new ex).fromJson(t,r)}static fromJsonString(t,r){return(new ex).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ex,t,r)}static $(){return["UpdateTeamNameResponse"]}}class nx extends T{constructor(t){super(),this.teamId=0,this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nx).fromBinary(t,r)}static fromJson(t,r){return(new nx).fromJson(t,r)}static fromJsonString(t,r){return(new nx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nx,t,r)}static $(){return["UploadTeamIconRequest|1 team_id 5|2 content_type 9|3 bytes 12"]}}class sx extends T{constructor(t){super(),this.iconUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sx).fromBinary(t,r)}static fromJson(t,r){return(new sx).fromJson(t,r)}static fromJsonString(t,r){return(new sx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sx,t,r)}static $(){return["UploadTeamIconResponse|1 icon_url 9"]}}class ix extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ix).fromBinary(t,r)}static fromJson(t,r){return(new ix).fromJson(t,r)}static fromJsonString(t,r){return(new ix).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ix,t,r)}static $(){return["UpdateTeamIconRequest|1 team_id 5|2 icon_url 9?"]}}class ox extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ox).fromBinary(t,r)}static fromJson(t,r){return(new ox).fromJson(t,r)}static fromJsonString(t,r){return(new ox).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ox,t,r)}static $(){return["UpdateTeamIconResponse|1 icon_url 9?"]}}class ax extends T{constructor(t){super(),this.teamId=0,this.dashboardAnalyticsRequiresAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ax).fromBinary(t,r)}static fromJson(t,r){return(new ax).fromJson(t,r)}static fromJsonString(t,r){return(new ax).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ax,t,r)}static $(){return["UpdateTeamDashboardAnalyticsSettingRequest|1 team_id 5|2 dashboard_analytics_requires_admin 8"]}}class ux extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ux).fromBinary(t,r)}static fromJson(t,r){return(new ux).fromJson(t,r)}static fromJsonString(t,r){return(new ux).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ux,t,r)}static $(){return["UpdateTeamDashboardAnalyticsSettingResponse"]}}class cx extends T{constructor(t){super(),this.teamId=0,this.originDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cx).fromBinary(t,r)}static fromJson(t,r){return(new cx).fromJson(t,r)}static fromJsonString(t,r){return(new cx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cx,t,r)}static $(){return["UpdateTeamOriginSettingRequest|1 team_id 5|2 origin_disabled 8|3 origin_allow_public_repos 8?"]}}class lx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lx).fromBinary(t,r)}static fromJson(t,r){return(new lx).fromJson(t,r)}static fromJsonString(t,r){return(new lx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lx,t,r)}static $(){return["UpdateTeamOriginSettingResponse"]}}class mx extends T{constructor(t){super(),this.teamId=0,this.scimRequireUserDirectory=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mx).fromBinary(t,r)}static fromJson(t,r){return(new mx).fromJson(t,r)}static fromJsonString(t,r){return(new mx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mx,t,r)}static $(){return["UpdateTeamScimRequireUserDirectorySettingRequest|1 team_id 5|2 scim_require_user_directory 8"]}}class fx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fx).fromBinary(t,r)}static fromJson(t,r){return(new fx).fromJson(t,r)}static fromJsonString(t,r){return(new fx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fx,t,r)}static $(){return["UpdateTeamScimRequireUserDirectorySettingResponse"]}}class dx extends T{constructor(t){super(),this.actor=Nr.UNSPECIFIED,this.usePortalCallback=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dx).fromBinary(t,r)}static fromJson(t,r){return(new dx).fromJson(t,r)}static fromJsonString(t,r){return(new dx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dx,t,r)}static $(){return["GetLinearAuthUrlRequest|1 actor #0|2 use_portal_callback 8",Nr]}}class px extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new px).fromBinary(t,r)}static fromJson(t,r){return(new px).fromJson(t,r)}static fromJsonString(t,r){return(new px).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(px,t,r)}static $(){return["GetLinearAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class hx extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hx).fromBinary(t,r)}static fromJson(t,r){return(new hx).fromJson(t,r)}static fromJsonString(t,r){return(new hx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hx,t,r)}static $(){return["ConnectLinearCallbackRequest|1 code 9|2 state 9"]}}class gx extends T{constructor(t){super(),this.successType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gx).fromBinary(t,r)}static fromJson(t,r){return(new gx).fromJson(t,r)}static fromJsonString(t,r){return(new gx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gx,t,r)}static $(){return["ConnectLinearCallbackResponse|1 success_type 9"]}}class _x extends T{constructor(t){super(),this.linkId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _x).fromBinary(t,r)}static fromJson(t,r){return(new _x).fromJson(t,r)}static fromJsonString(t,r){return(new _x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_x,t,r)}static $(){return["GetMicrosoftTeamsLinkContextRequest|1 link_id 9"]}}class Jx extends T{constructor(t){super(),this.linkState=Gr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jx).fromBinary(t,r)}static fromJson(t,r){return(new Jx).fromJson(t,r)}static fromJsonString(t,r){return(new Jx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jx,t,r)}static $(){return["GetMicrosoftTeamsLinkContextResponse|1 team_name 9?|2 user_name 9?|3 link_state #0",Gr]}}class wx extends T{constructor(t){super(),this.linkId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wx).fromBinary(t,r)}static fromJson(t,r){return(new wx).fromJson(t,r)}static fromJsonString(t,r){return(new wx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wx,t,r)}static $(){return["SetMicrosoftTeamsAuthRequest|1 link_id 9"]}}class yx extends T{constructor(t){super(),this.successType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yx).fromBinary(t,r)}static fromJson(t,r){return(new yx).fromJson(t,r)}static fromJsonString(t,r){return(new yx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yx,t,r)}static $(){return["SetMicrosoftTeamsAuthResponse|1 success_type 9"]}}class Sx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sx).fromBinary(t,r)}static fromJson(t,r){return(new Sx).fromJson(t,r)}static fromJsonString(t,r){return(new Sx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sx,t,r)}static $(){return["GetLinearStatusRequest"]}}class qx extends T{constructor(t){super(),this.status="",this.autodraftingEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qx).fromBinary(t,r)}static fromJson(t,r){return(new qx).fromJson(t,r)}static fromJsonString(t,r){return(new qx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qx,t,r)}static $(){return["GetLinearStatusResponse|1 status 9|2 autodrafting_enabled 8"]}}class Bx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bx).fromBinary(t,r)}static fromJson(t,r){return(new Bx).fromJson(t,r)}static fromJsonString(t,r){return(new Bx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bx,t,r)}static $(){return["DisconnectLinearRequest"]}}class Ix extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ix).fromBinary(t,r)}static fromJson(t,r){return(new Ix).fromJson(t,r)}static fromJsonString(t,r){return(new Ix).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ix,t,r)}static $(){return["DisconnectLinearResponse"]}}class Px extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Px).fromBinary(t,r)}static fromJson(t,r){return(new Px).fromJson(t,r)}static fromJsonString(t,r){return(new Px).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Px,t,r)}static $(){return["GetXaiTeamLinkStatusRequest|1 organization_id 9"]}}class bx extends T{constructor(t){super(),this.enabled=!1,this.linked=!1,this.xaiTeamId="",this.hasPendingProposal=!1,this.proposedXaiTeamId="",this.canConfirmProposal=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bx).fromBinary(t,r)}static fromJson(t,r){return(new bx).fromJson(t,r)}static fromJsonString(t,r){return(new bx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bx,t,r)}static $(){return["GetXaiTeamLinkStatusResponse|1 enabled 8|2 linked 8|3 xai_team_id 9|4 linked_at_ms 3?|5 has_pending_proposal 8|6 proposed_xai_team_id 9|7 proposal_expires_at_ms 3?|8 can_confirm_proposal 8"]}}class Rx extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rx).fromBinary(t,r)}static fromJson(t,r){return(new Rx).fromJson(t,r)}static fromJsonString(t,r){return(new Rx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rx,t,r)}static $(){return["StartXaiTeamLinkRequest|1 organization_id 9"]}}class vx extends T{constructor(t){super(),this.connectUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vx).fromBinary(t,r)}static fromJson(t,r){return(new vx).fromJson(t,r)}static fromJsonString(t,r){return(new vx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vx,t,r)}static $(){return["StartXaiTeamLinkResponse|1 connect_url 9"]}}class xx extends T{constructor(t){super(),this.organizationId="",this.xaiTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xx).fromBinary(t,r)}static fromJson(t,r){return(new xx).fromJson(t,r)}static fromJsonString(t,r){return(new xx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xx,t,r)}static $(){return["ConfirmXaiTeamLinkRequest|1 organization_id 9|2 xai_team_id 9"]}}class kx extends T{constructor(t){super(),this.linked=!1,this.xaiTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kx).fromBinary(t,r)}static fromJson(t,r){return(new kx).fromJson(t,r)}static fromJsonString(t,r){return(new kx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kx,t,r)}static $(){return["ConfirmXaiTeamLinkResponse|1 linked 8|2 xai_team_id 9"]}}class Ex extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ex).fromBinary(t,r)}static fromJson(t,r){return(new Ex).fromJson(t,r)}static fromJsonString(t,r){return(new Ex).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ex,t,r)}static $(){return["CancelXaiTeamLinkProposalRequest|1 organization_id 9"]}}class Cx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cx).fromBinary(t,r)}static fromJson(t,r){return(new Cx).fromJson(t,r)}static fromJsonString(t,r){return(new Cx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cx,t,r)}static $(){return["CancelXaiTeamLinkProposalResponse"]}}class Tx extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tx).fromBinary(t,r)}static fromJson(t,r){return(new Tx).fromJson(t,r)}static fromJsonString(t,r){return(new Tx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tx,t,r)}static $(){return["UnlinkXaiTeamRequest|1 organization_id 9"]}}class Ux extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ux).fromBinary(t,r)}static fromJson(t,r){return(new Ux).fromJson(t,r)}static fromJsonString(t,r){return(new Ux).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ux,t,r)}static $(){return["UnlinkXaiTeamResponse"]}}class Ax extends T{constructor(t){super(),this.organizationId="",this.amountCents=n.protoInt64.zero,this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ax).fromBinary(t,r)}static fromJson(t,r){return(new Ax).fromJson(t,r)}static fromJsonString(t,r){return(new Ax).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ax,t,r)}static $(){return["TransferXaiCreditsRequest|1 organization_id 9|2 amount_cents 3|3 transfer_id 9"]}}class $x extends T{constructor(t){super(),this.outcome=Lr.UNSPECIFIED,this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $x).fromBinary(t,r)}static fromJson(t,r){return(new $x).fromJson(t,r)}static fromJsonString(t,r){return(new $x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($x,t,r)}static $(){return["TransferXaiCreditsResponse|1 outcome #0|2 transfer_id 9",Lr]}}class Mx extends T{constructor(t){super(),this.organizationId="",this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mx).fromBinary(t,r)}static fromJson(t,r){return(new Mx).fromJson(t,r)}static fromJsonString(t,r){return(new Mx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mx,t,r)}static $(){return["GetXaiCreditTransferStatusRequest|1 organization_id 9|2 transfer_id 9"]}}class Ox extends T{constructor(t){super(),this.organizationId="",this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ox).fromBinary(t,r)}static fromJson(t,r){return(new Ox).fromJson(t,r)}static fromJsonString(t,r){return(new Ox).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ox,t,r)}static $(){return["ListXaiCreditTransfersRequest|1 organization_id 9|2 page_size 5"]}}class Dx extends T{constructor(t){super(),this.transferId="",this.createdAtMs=n.protoInt64.zero,this.amountCents=n.protoInt64.zero,this.status="",this.outcome=Lr.UNSPECIFIED,this.requestedByUserDisplayName="",this.requestedByUserEmail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dx).fromBinary(t,r)}static fromJson(t,r){return(new Dx).fromJson(t,r)}static fromJsonString(t,r){return(new Dx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dx,t,r)}static $(){return["XaiCreditTransfer|1 transfer_id 9|2 created_at_ms 3|3 amount_cents 3|4 status 9|5 outcome #0|6 requested_by_user_id 5?|7 requested_by_user_display_name 9|8 requested_by_user_email 9",Lr]}}class Nx extends T{constructor(t){super(),this.transfers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nx).fromBinary(t,r)}static fromJson(t,r){return(new Nx).fromJson(t,r)}static fromJsonString(t,r){return(new Nx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nx,t,r)}static $(){return["ListXaiCreditTransfersResponse|1 transfers #0*",Dx]}}class Gx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gx).fromBinary(t,r)}static fromJson(t,r){return(new Gx).fromJson(t,r)}static fromJsonString(t,r){return(new Gx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gx,t,r)}static $(){return["GetLinearTeamsRequest"]}}class Lx extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lx).fromBinary(t,r)}static fromJson(t,r){return(new Lx).fromJson(t,r)}static fromJsonString(t,r){return(new Lx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lx,t,r)}static $(){return["GetLinearTeamsResponse|1 teams #0*|2 error 9?",Fx]}}class Fx extends T{constructor(t){super(),this.id="",this.key="",this.name="",this.displayName="",this.projects=[],this.labels=[],this.states=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fx).fromBinary(t,r)}static fromJson(t,r){return(new Fx).fromJson(t,r)}static fromJsonString(t,r){return(new Fx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fx,t,r)}static $(){return["LinearTeam|1 id 9|2 key 9|3 name 9|4 display_name 9|5 description 9?|6 projects #0*|7 labels #1*|8 states #2*",zx,tk,Kx]}}class Kx extends T{constructor(t){super(),this.id="",this.name="",this.type="",this.position=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kx).fromBinary(t,r)}static fromJson(t,r){return(new Kx).fromJson(t,r)}static fromJsonString(t,r){return(new Kx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kx,t,r)}static $(){return["LinearWorkflowState|1 id 9|2 name 9|3 color 9?|4 type 9|5 position 1"]}}class zx extends T{constructor(t){super(),this.id="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zx).fromBinary(t,r)}static fromJson(t,r){return(new zx).fromJson(t,r)}static fromJsonString(t,r){return(new zx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zx,t,r)}static $(){return["LinearProject|1 id 9|2 name 9"]}}class jx extends T{constructor(t){super(),this.projectId="",this.runOption=Fr.UNSPECIFIED,this.conditions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jx).fromBinary(t,r)}static fromJson(t,r){return(new jx).fromJson(t,r)}static fromJsonString(t,r){return(new jx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jx,t,r)}static $(){return["LinearProjectSettings|1 project_id 9|2 run_option #0|3 conditions 9",Fr]}}class Hx extends T{constructor(t){super(),this.linearTeamId="",this.defaultRunOption=Fr.UNSPECIFIED,this.projectSettings=[],this.defaultConditions="",this.labelFilterMode=Kr.UNSPECIFIED,this.requiredLabelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hx).fromBinary(t,r)}static fromJson(t,r){return(new Hx).fromJson(t,r)}static fromJsonString(t,r){return(new Hx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hx,t,r)}static $(){return["LinearTeamSettings|1 linear_team_id 9|2 default_run_option #0|3 project_settings #1*|4 default_conditions 9|5 label_filter_mode #2|6 required_label_ids 9*|7 autorun_as_user_id 5?",Fr,jx,Kr]}}class Wx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wx).fromBinary(t,r)}static fromJson(t,r){return(new Wx).fromJson(t,r)}static fromJsonString(t,r){return(new Wx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wx,t,r)}static $(){return["GetLinearSettingsRequest|1 team_id 5?"]}}class Qx extends T{constructor(t){super(),this.teamSettings=[],this.isTeamSettings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qx).fromBinary(t,r)}static fromJson(t,r){return(new Qx).fromJson(t,r)}static fromJsonString(t,r){return(new Qx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qx,t,r)}static $(){return["GetLinearSettingsResponse|1 team_settings #0*|2 is_team_settings 8",Hx]}}class Vx extends T{constructor(t){super(),this.linearTeamId="",this.defaultRunOption=Fr.UNSPECIFIED,this.defaultConditions="",this.labelFilterMode=Kr.UNSPECIFIED,this.requiredLabelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vx).fromBinary(t,r)}static fromJson(t,r){return(new Vx).fromJson(t,r)}static fromJsonString(t,r){return(new Vx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vx,t,r)}static $(){return["UpdateLinearTeamSettingRequest|1 team_id 5?|2 linear_team_id 9|3 default_run_option #0|4 default_conditions 9|5 label_filter_mode #1|6 required_label_ids 9*|7 autorun_as_user_id 5?",Fr,Kr]}}class Xx extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xx).fromBinary(t,r)}static fromJson(t,r){return(new Xx).fromJson(t,r)}static fromJsonString(t,r){return(new Xx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xx,t,r)}static $(){return["UpdateLinearTeamSettingResponse|1 success 8"]}}class Yx extends T{constructor(t){super(),this.linearTeamId="",this.projectId="",this.runOption=Fr.UNSPECIFIED,this.conditions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yx).fromBinary(t,r)}static fromJson(t,r){return(new Yx).fromJson(t,r)}static fromJsonString(t,r){return(new Yx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yx,t,r)}static $(){return["UpdateLinearProjectSettingRequest|1 team_id 5?|2 linear_team_id 9|3 project_id 9|4 run_option #0|5 conditions 9",Fr]}}class Zx extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zx).fromBinary(t,r)}static fromJson(t,r){return(new Zx).fromJson(t,r)}static fromJsonString(t,r){return(new Zx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zx,t,r)}static $(){return["UpdateLinearProjectSettingResponse|1 success 8"]}}class tk extends T{constructor(t){super(),this.id="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tk).fromBinary(t,r)}static fromJson(t,r){return(new tk).fromJson(t,r)}static fromJsonString(t,r){return(new tk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tk,t,r)}static $(){return["LinearLabel|1 id 9|2 name 9|3 color 9?"]}}class rk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rk).fromBinary(t,r)}static fromJson(t,r){return(new rk).fromJson(t,r)}static fromJsonString(t,r){return(new rk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rk,t,r)}static $(){return["GetLinearLabelsRequest|1 team_id 5?"]}}class ek extends T{constructor(t){super(),this.labels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ek).fromBinary(t,r)}static fromJson(t,r){return(new ek).fromJson(t,r)}static fromJsonString(t,r){return(new ek).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ek,t,r)}static $(){return["GetLinearLabelsResponse|1 labels #0*|2 error 9?",tk]}}class nk extends T{constructor(t){super(),this.orderBy=zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nk).fromBinary(t,r)}static fromJson(t,r){return(new nk).fromJson(t,r)}static fromJsonString(t,r){return(new nk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nk,t,r)}static $(){return["GetLinearIssuesRequest|1 team_id 5?|2 linear_team_id 9?|3 search_query 9?|4 include_completed 8?|5 include_archived 8?|6 first 5?|7 after 9?|8 order_by #0|9 assigned_to_me_only 8?",zr]}}class sk extends T{constructor(t){super(),this.issues=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sk).fromBinary(t,r)}static fromJson(t,r){return(new sk).fromJson(t,r)}static fromJsonString(t,r){return(new sk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sk,t,r)}static $(){return["GetLinearIssuesResponse|1 issues #0*|2 next_cursor 9?|3 has_more 8|4 error 9?",ik]}}class ik extends T{constructor(t){super(),this.id="",this.identifier="",this.title="",this.labelIds=[],this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ik).fromBinary(t,r)}static fromJson(t,r){return(new ik).fromJson(t,r)}static fromJsonString(t,r){return(new ik).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ik,t,r)}static $(){return["LinearIssue|1 id 9|2 identifier 9|3 title 9|4 description 9?|5 state_id 9?|6 state_name 9?|7 state_type 9?|8 team_id 9?|9 project_id 9?|10 project_name 9?|11 assignee_id 9?|12 assignee_name 9?|13 label_ids 9*|14 priority 5?|15 archived 8|16 created_at 3?|17 updated_at 3?|18 url 9?|19 due_date 9?"]}}class ok extends T{constructor(t){super(),this.workspaceUrlKey="",this.identifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ok).fromBinary(t,r)}static fromJson(t,r){return(new ok).fromJson(t,r)}static fromJsonString(t,r){return(new ok).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ok,t,r)}static $(){return["BatchGetLinearIssueSummariesRequest|1 workspace_url_key 9|2 identifiers 9*|3 team_id 5?"]}}class ak extends T{constructor(t){super(),this.identifier="",this.title="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ak).fromBinary(t,r)}static fromJson(t,r){return(new ak).fromJson(t,r)}static fromJsonString(t,r){return(new ak).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ak,t,r)}static $(){return["LinearIssueSummary|1 identifier 9|2 title 9|3 url 9|4 state_name 9?|5 state_type 9?|6 state_color 9?|7 assignee_name 9?|8 assignee_avatar_url 9?|9 project_name 9?|10 team_name 9?|11 priority 5?|12 priority_label 9?|13 updated_at 3?"]}}class uk extends T{constructor(t){super(),this.issues=[],this.missingIdentifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uk).fromBinary(t,r)}static fromJson(t,r){return(new uk).fromJson(t,r)}static fromJsonString(t,r){return(new uk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uk,t,r)}static $(){return["BatchGetLinearIssueSummariesResponse|1 issues #0*|2 missing_identifiers 9*|3 unavailable_reason #1?|4 retry_after_ms 3?",ak,jr]}}class ck extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ck).fromBinary(t,r)}static fromJson(t,r){return(new ck).fromJson(t,r)}static fromJsonString(t,r){return(new ck).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ck,t,r)}static $(){return["GetPagerDutyAuthUrlRequest"]}}class lk extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lk).fromBinary(t,r)}static fromJson(t,r){return(new lk).fromJson(t,r)}static fromJsonString(t,r){return(new lk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lk,t,r)}static $(){return["GetPagerDutyAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class mk extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mk).fromBinary(t,r)}static fromJson(t,r){return(new mk).fromJson(t,r)}static fromJsonString(t,r){return(new mk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mk,t,r)}static $(){return["ConnectPagerDutyCallbackRequest|1 code 9|2 state 9"]}}class fk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fk).fromBinary(t,r)}static fromJson(t,r){return(new fk).fromJson(t,r)}static fromJsonString(t,r){return(new fk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fk,t,r)}static $(){return["ConnectPagerDutyCallbackResponse|1 success 8"]}}class dk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dk).fromBinary(t,r)}static fromJson(t,r){return(new dk).fromJson(t,r)}static fromJsonString(t,r){return(new dk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dk,t,r)}static $(){return["GetPagerDutyStatusRequest"]}}class pk extends T{constructor(t){super(),this.isConnected=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pk).fromBinary(t,r)}static fromJson(t,r){return(new pk).fromJson(t,r)}static fromJsonString(t,r){return(new pk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pk,t,r)}static $(){return["GetPagerDutyStatusResponse|1 is_connected 8|2 account_name 9?|3 subdomain 9?"]}}class hk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hk).fromBinary(t,r)}static fromJson(t,r){return(new hk).fromJson(t,r)}static fromJsonString(t,r){return(new hk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hk,t,r)}static $(){return["GetPagerDutyServicesRequest"]}}class gk extends T{constructor(t){super(),this.services=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gk).fromBinary(t,r)}static fromJson(t,r){return(new gk).fromJson(t,r)}static fromJsonString(t,r){return(new gk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gk,t,r)}static $(){return["GetPagerDutyServicesResponse|1 services #0*",_k]}}class _k extends T{constructor(t){super(),this.id="",this.name="",this.description="",this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _k).fromBinary(t,r)}static fromJson(t,r){return(new _k).fromJson(t,r)}static fromJsonString(t,r){return(new _k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_k,t,r)}static $(){return["PagerDutyServiceInfo|1 id 9|2 name 9|3 description 9|4 status 9"]}}class Jk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jk).fromBinary(t,r)}static fromJson(t,r){return(new Jk).fromJson(t,r)}static fromJsonString(t,r){return(new Jk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jk,t,r)}static $(){return["DisconnectPagerDutyRequest"]}}class wk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wk).fromBinary(t,r)}static fromJson(t,r){return(new wk).fromJson(t,r)}static fromJsonString(t,r){return(new wk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wk,t,r)}static $(){return["DisconnectPagerDutyResponse|1 success 8"]}}class yk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yk).fromBinary(t,r)}static fromJson(t,r){return(new yk).fromJson(t,r)}static fromJsonString(t,r){return(new yk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yk,t,r)}static $(){return["GetSlackUserSettingsRequest|1 team_id 5"]}}class Sk extends T{constructor(t){super(),this.hasSlackAuth=!1,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.canShow=!1,this.openPrByDefault=!1,this.ciFailureFollowupEnabled=!1,this.branchPrefix="",this.slackCursorTeamLocked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sk).fromBinary(t,r)}static fromJson(t,r){return(new Sk).fromJson(t,r)}static fromJsonString(t,r){return(new Sk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sk,t,r)}static $(){return["GetSlackUserSettingsResponse|1 has_slack_auth 8|2 default_repo 9|3 default_branch 9|4 default_model 9|5 can_show 8|6 open_pr_by_default 8|7 use_github_app_for_auto_draft_prs 8?|8 ci_failure_followup_enabled 8|9 branch_prefix 9|10 default_model_selection #0?|11 slack_cursor_team_id 5?|12 slack_effective_cursor_team_id 5?|13 slack_cursor_team_locked 8|14 default_environment_public_id 9?|15 origin_link_unfurls_enabled 8?",o.M6]}}class qk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qk).fromBinary(t,r)}static fromJson(t,r){return(new qk).fromJson(t,r)}static fromJsonString(t,r){return(new qk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qk,t,r)}static $(){return["ListSlackConnectedWorkspacesRequest|1 team_id 5"]}}class Bk extends T{constructor(t){super(),this.slackTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bk).fromBinary(t,r)}static fromJson(t,r){return(new Bk).fromJson(t,r)}static fromJsonString(t,r){return(new Bk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bk,t,r)}static $(){return["SlackConnectedWorkspace|1 slack_team_id 9|2 slack_enterprise_id 9?|3 linked_at #0|4 connected_by_team_id 5?|5 display_name 9?",n.Timestamp]}}class Ik extends T{constructor(t){super(),this.workspaces=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ik).fromBinary(t,r)}static fromJson(t,r){return(new Ik).fromJson(t,r)}static fromJsonString(t,r){return(new Ik).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ik,t,r)}static $(){return["ListSlackConnectedWorkspacesResponse|1 workspaces #0*|2 truncated 8",Bk]}}class Pk extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pk).fromBinary(t,r)}static fromJson(t,r){return(new Pk).fromJson(t,r)}static fromJsonString(t,r){return(new Pk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pk,t,r)}static $(){return["ListOrganizationSlackConnectedWorkspacesRequest|1 organization_id 9"]}}class bk extends T{constructor(t){super(),this.workspaces=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bk).fromBinary(t,r)}static fromJson(t,r){return(new bk).fromJson(t,r)}static fromJsonString(t,r){return(new bk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bk,t,r)}static $(){return["ListOrganizationSlackConnectedWorkspacesResponse|1 workspaces #0*|2 truncated 8",Bk]}}class Rk extends T{constructor(t){super(),this.allWorkspaces=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rk).fromBinary(t,r)}static fromJson(t,r){return(new Rk).fromJson(t,r)}static fromJsonString(t,r){return(new Rk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rk,t,r)}static $(){return["UnlinkSlackAccessRequest|1 slack_team_id 9?|2 all_workspaces 8"]}}class vk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vk).fromBinary(t,r)}static fromJson(t,r){return(new vk).fromJson(t,r)}static fromJsonString(t,r){return(new vk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vk,t,r)}static $(){return["UnlinkSlackAccessResponse|1 success 8"]}}class xk extends T{constructor(t){super(),this.slackTeamId="",this.displayName="",this.linkedAtMs=n.protoInt64.zero,this.status=Hr.UNSPECIFIED,this.sandAutomationCount=0,this.sandAutomationCountTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xk).fromBinary(t,r)}static fromJson(t,r){return(new xk).fromJson(t,r)}static fromJsonString(t,r){return(new xk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xk,t,r)}static $(){return["SlackLinkedWorkspace|1 slack_team_id 9|2 display_name 9|3 linked_at_ms 3|4 status #0|5 sand_automation_count 5|6 sand_automation_count_truncated 8",Hr]}}class kk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kk).fromBinary(t,r)}static fromJson(t,r){return(new kk).fromJson(t,r)}static fromJsonString(t,r){return(new kk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kk,t,r)}static $(){return["ListSlackLinkedWorkspacesRequest"]}}class Ek extends T{constructor(t){super(),this.workspaces=[],this.canLinkAnotherWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ek).fromBinary(t,r)}static fromJson(t,r){return(new Ek).fromJson(t,r)}static fromJsonString(t,r){return(new Ek).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ek,t,r)}static $(){return["ListSlackLinkedWorkspacesResponse|1 workspaces #0*|2 can_link_another_workspace 8",xk]}}class Ck extends T{constructor(t){super(),this.slackTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ck).fromBinary(t,r)}static fromJson(t,r){return(new Ck).fromJson(t,r)}static fromJsonString(t,r){return(new Ck).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ck,t,r)}static $(){return["GetSlackLinkPreviewRequest|1 slack_team_id 9"]}}class Tk extends T{constructor(t){super(),this.replacesWorkspaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tk).fromBinary(t,r)}static fromJson(t,r){return(new Tk).fromJson(t,r)}static fromJsonString(t,r){return(new Tk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tk,t,r)}static $(){return["GetSlackLinkPreviewResponse|1 replaces_workspaces #0*",xk]}}class Uk extends T{constructor(t){super(),this.teamId=0,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.openPrByDefault=!1,this.ciFailureFollowupEnabled=!1,this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uk).fromBinary(t,r)}static fromJson(t,r){return(new Uk).fromJson(t,r)}static fromJsonString(t,r){return(new Uk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uk,t,r)}static $(){return["UpdateSlackUserSettingsRequest|1 team_id 5|2 default_repo 9|3 default_branch 9|4 default_model 9|5 open_pr_by_default 8|6 use_github_app_for_auto_draft_prs 8?|7 ci_failure_followup_enabled 8|8 branch_prefix 9|9 default_model_selection #0?|10 default_environment_public_id 9?|11 origin_link_unfurls_enabled 8?",o.M6]}}class Ak extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ak).fromBinary(t,r)}static fromJson(t,r){return(new Ak).fromJson(t,r)}static fromJsonString(t,r){return(new Ak).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ak,t,r)}static $(){return["UpdateSlackUserSettingsResponse"]}}class $k extends T{constructor(t){super(),this.id=0,this.pattern="",this.repo="",this.isTeamRule=!1,this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $k).fromBinary(t,r)}static fromJson(t,r){return(new $k).fromJson(t,r)}static fromJsonString(t,r){return(new $k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($k,t,r)}static $(){return["SlackRepoRoutingRule|1 id 5|2 pattern 9|3 repo 9|4 is_team_rule 8|5 target_type #0|6 environment_public_id 9?",Wr]}}class Mk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mk).fromBinary(t,r)}static fromJson(t,r){return(new Mk).fromJson(t,r)}static fromJsonString(t,r){return(new Mk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mk,t,r)}static $(){return["GetSlackRepoRoutingRulesRequest|1 team_id 5"]}}class Ok extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ok).fromBinary(t,r)}static fromJson(t,r){return(new Ok).fromJson(t,r)}static fromJsonString(t,r){return(new Ok).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ok,t,r)}static $(){return["GetSlackRepoRoutingRulesResponse|1 rules #0*",$k]}}class Dk extends T{constructor(t){super(),this.teamId=0,this.pattern="",this.repo="",this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dk).fromBinary(t,r)}static fromJson(t,r){return(new Dk).fromJson(t,r)}static fromJsonString(t,r){return(new Dk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dk,t,r)}static $(){return["CreateSlackRepoRoutingRuleRequest|1 team_id 5|2 pattern 9|3 repo 9|4 target_type #0|5 environment_public_id 9?",Wr]}}class Nk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nk).fromBinary(t,r)}static fromJson(t,r){return(new Nk).fromJson(t,r)}static fromJsonString(t,r){return(new Nk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nk,t,r)}static $(){return["CreateSlackRepoRoutingRuleResponse|1 rule #0",$k]}}class Gk extends T{constructor(t){super(),this.teamId=0,this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gk).fromBinary(t,r)}static fromJson(t,r){return(new Gk).fromJson(t,r)}static fromJsonString(t,r){return(new Gk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gk,t,r)}static $(){return["DeleteSlackRepoRoutingRuleRequest|1 team_id 5|2 rule_id 9"]}}class Lk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lk).fromBinary(t,r)}static fromJson(t,r){return(new Lk).fromJson(t,r)}static fromJsonString(t,r){return(new Lk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lk,t,r)}static $(){return["DeleteSlackRepoRoutingRuleResponse"]}}class Fk extends T{constructor(t){super(),this.teamId=0,this.ruleId="",this.pattern="",this.repo="",this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fk).fromBinary(t,r)}static fromJson(t,r){return(new Fk).fromJson(t,r)}static fromJsonString(t,r){return(new Fk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fk,t,r)}static $(){return["UpdateSlackRepoRoutingRuleRequest|1 team_id 5|2 rule_id 9|3 pattern 9|4 repo 9|5 target_type #0|6 environment_public_id 9?",Wr]}}class Kk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kk).fromBinary(t,r)}static fromJson(t,r){return(new Kk).fromJson(t,r)}static fromJsonString(t,r){return(new Kk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kk,t,r)}static $(){return["UpdateSlackRepoRoutingRuleResponse|1 rule #0",$k]}}class zk extends T{constructor(t){super(),this.id=0,this.repo="",this.workerName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zk).fromBinary(t,r)}static fromJson(t,r){return(new zk).fromJson(t,r)}static fromJsonString(t,r){return(new zk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zk,t,r)}static $(){return["SlackDefaultWorkerRule|1 id 5|2 repo 9|3 worker_name 9"]}}class jk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jk).fromBinary(t,r)}static fromJson(t,r){return(new jk).fromJson(t,r)}static fromJsonString(t,r){return(new jk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jk,t,r)}static $(){return["GetSlackDefaultWorkerRulesRequest"]}}class Hk extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hk).fromBinary(t,r)}static fromJson(t,r){return(new Hk).fromJson(t,r)}static fromJsonString(t,r){return(new Hk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hk,t,r)}static $(){return["GetSlackDefaultWorkerRulesResponse|1 rules #0*",zk]}}class Wk extends T{constructor(t){super(),this.repo="",this.workerName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wk).fromBinary(t,r)}static fromJson(t,r){return(new Wk).fromJson(t,r)}static fromJsonString(t,r){return(new Wk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wk,t,r)}static $(){return["SetSlackDefaultWorkerRuleRequest|1 repo 9|2 worker_name 9"]}}class Qk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qk).fromBinary(t,r)}static fromJson(t,r){return(new Qk).fromJson(t,r)}static fromJsonString(t,r){return(new Qk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qk,t,r)}static $(){return["SetSlackDefaultWorkerRuleResponse|1 rule #0",zk]}}class Vk extends T{constructor(t){super(),this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vk).fromBinary(t,r)}static fromJson(t,r){return(new Vk).fromJson(t,r)}static fromJsonString(t,r){return(new Vk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vk,t,r)}static $(){return["DeleteSlackDefaultWorkerRuleRequest|1 repo 9"]}}class Xk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xk).fromBinary(t,r)}static fromJson(t,r){return(new Xk).fromJson(t,r)}static fromJsonString(t,r){return(new Xk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xk,t,r)}static $(){return["DeleteSlackDefaultWorkerRuleResponse"]}}class Yk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yk).fromBinary(t,r)}static fromJson(t,r){return(new Yk).fromJson(t,r)}static fromJsonString(t,r){return(new Yk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yk,t,r)}static $(){return["IsOnNewPricingRequest"]}}class Zk extends T{constructor(t){super(),this.isOnNewPricing=!1,this.isOptedOut=!1,this.hasAutoSpillover=!1,this.hasTieredSelfServeTeamSpillover=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zk).fromBinary(t,r)}static fromJson(t,r){return(new Zk).fromJson(t,r)}static fromJsonString(t,r){return(new Zk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zk,t,r)}static $(){return["IsOnNewPricingResponse|1 is_on_new_pricing 8|2 is_opted_out 8|3 has_auto_spillover 8|4 dashboard_user_id 5?|5 has_tiered_self_serve_team_spillover 8"]}}class tE extends T{constructor(t){super(),this.checkpoints={},this.isTeamAdmin=!1,this.isLoading=!1,this.isPrivacyModeLoading=!1,this.isGithubLoading=!1,this.isUsagePricingLoading=!1,this.triggeredByGithubConnect=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tE).fromBinary(t,r)}static fromJson(t,r){return(new tE).fromJson(t,r)}static fromJsonString(t,r){return(new tE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tE,t,r)}static $(){return["LogSlackbotAuthConversionFunnelRequest|1 checkpoints 9,8|2 privacy_mode #0?|3 is_team_admin 8|4 is_loading 8|5 is_privacy_mode_loading 8|6 is_github_loading 8|7 is_usage_pricing_loading 8|8 triggered_by_github_connect 8|9 scm_provider 9?",s.Y]}}class rE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rE).fromBinary(t,r)}static fromJson(t,r){return(new rE).fromJson(t,r)}static fromJsonString(t,r){return(new rE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rE,t,r)}static $(){return["LogSlackbotAuthConversionFunnelResponse"]}}class eE extends T{constructor(t){super(),this.origin=nE.UNSPECIFIED,this.skipSetupFlow=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eE).fromBinary(t,r)}static fromJson(t,r){return(new eE).fromJson(t,r)}static fromJsonString(t,r){return(new eE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eE,t,r)}static $(){return["LogClickedConnectSlackRequest|1 origin #0|2 skip_setup_flow 8",nE]}}var nE=(0,a.QT)(n.proto3,C,"LogClickedConnectSlackRequest.Origin",[[0,"UNSPECIFIED"],[1,"APP"],[2,"WEBSITE"],[3,"SLACK"],[4,"PUBLIC_URL"]],1);class sE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sE).fromBinary(t,r)}static fromJson(t,r){return(new sE).fromJson(t,r)}static fromJsonString(t,r){return(new sE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sE,t,r)}static $(){return["LogClickedConnectSlackResponse"]}}class iE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iE).fromBinary(t,r)}static fromJson(t,r){return(new iE).fromJson(t,r)}static fromJsonString(t,r){return(new iE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iE,t,r)}static $(){return["CheckUserApiKeyAccessRequest"]}}class oE extends T{constructor(t){super(),this.hasAccess=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oE).fromBinary(t,r)}static fromJson(t,r){return(new oE).fromJson(t,r)}static fromJsonString(t,r){return(new oE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oE,t,r)}static $(){return["CheckUserApiKeyAccessResponse|1 has_access 8|2 personal_api_key_creation_allowed 8?"]}}class aE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aE).fromBinary(t,r)}static fromJson(t,r){return(new aE).fromJson(t,r)}static fromJsonString(t,r){return(new aE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aE,t,r)}static $(){return["IsAllowedFreeTrialUsageRequest"]}}class uE extends T{constructor(t){super(),this.isAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uE).fromBinary(t,r)}static fromJson(t,r){return(new uE).fromJson(t,r)}static fromJsonString(t,r){return(new uE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uE,t,r)}static $(){return["IsAllowedFreeTrialUsageResponse|1 is_allowed 8"]}}class cE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cE).fromBinary(t,r)}static fromJson(t,r){return(new cE).fromJson(t,r)}static fromJsonString(t,r){return(new cE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cE,t,r)}static $(){return["IsNextSetupRunFreeRequest|1 bc_id 9?"]}}class lE extends T{constructor(t){super(),this.isFree=!1,this.remainingRuns=0,this.isPromotionEnabled=!1,this.areFollowupsFree=!1,this.remainingFollowups=0,this.isCurrentRunFree=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lE).fromBinary(t,r)}static fromJson(t,r){return(new lE).fromJson(t,r)}static fromJsonString(t,r){return(new lE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lE,t,r)}static $(){return["IsNextSetupRunFreeResponse|1 is_free 8|2 remaining_runs 13|3 is_promotion_enabled 8|4 are_followups_free 8|5 remaining_followups 13|6 is_current_run_free 8"]}}class mE extends T{constructor(t){super(),this.name="",this.id=0,this.memberCount=0,this.hardLimitPerUserDollars=0,this.externalId="",this.perUserMonthlyLimitDollars=0,this.canonicalGroupPublicId="",this.owningTeamId=0,this.firstMcpRuleAddsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mE).fromBinary(t,r)}static fromJson(t,r){return(new mE).fromJson(t,r)}static fromJsonString(t,r){return(new mE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mE,t,r)}static $(){return["DirectoryGroup|1 name 9|2 id 5|3 member_count 5|4 hard_limit_per_user_dollars 5|5 auto_run_controls #0|6 external_id 9|7 per_user_monthly_limit_dollars 5|8 allowed_mcp_configuration #1|9 canonical_group_public_id 9|10 owning_team_id 5|11 first_mcp_rule_adds_grok_connectors_rule 8|12 cloud_drops_grok_connector_rules 8",j_,V_]}}class fE extends T{constructor(t){super(),this.teamId=0,this.unmigratedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fE).fromBinary(t,r)}static fromJson(t,r){return(new fE).fromJson(t,r)}static fromJsonString(t,r){return(new fE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fE,t,r)}static $(){return["GetDirectoryGroupsRequest|1 team_id 5|2 unmigrated_only 8"]}}class dE extends T{constructor(t){super(),this.directoryGroups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dE).fromBinary(t,r)}static fromJson(t,r){return(new dE).fromJson(t,r)}static fromJsonString(t,r){return(new dE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dE,t,r)}static $(){return["GetDirectoryGroupsResponse|1 directory_groups #0*",mE]}}class pE extends T{constructor(t){super(),this.directoryGroupId=0,this.perUserMonthlyLimitDollars=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pE).fromBinary(t,r)}static fromJson(t,r){return(new pE).fromJson(t,r)}static fromJsonString(t,r){return(new pE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pE,t,r)}static $(){return["UpdateDirectoryGroupSettingsRequest|1 directory_group_id 5|2 hard_limit_per_user_dollars 5?|4 per_user_monthly_limit_dollars 5|3 auto_run_controls #0|5 team_id 5|6 allowed_mcp_configuration #1?",j_,V_]}}class hE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hE).fromBinary(t,r)}static fromJson(t,r){return(new hE).fromJson(t,r)}static fromJsonString(t,r){return(new hE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hE,t,r)}static $(){return["UpdateDirectoryGroupSettingsResponse"]}}class gE extends T{constructor(t){super(),this.day=n.protoInt64.zero,this.spendCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gE).fromBinary(t,r)}static fromJson(t,r){return(new gE).fromJson(t,r)}static fromJsonString(t,r){return(new gE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gE,t,r)}static $(){return["DailySpendPoint|1 day 3|2 spend_cents 5"]}}class _E extends T{constructor(t){super(),this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,this.groupBy=Vr.UNSPECIFIED,this.products=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _E).fromBinary(t,r)}static fromJson(t,r){return(new _E).fromJson(t,r)}static fromJsonString(t,r){return(new _E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_E,t,r)}static $(){return["GetDailySpendByCategoryRequest|1 team_id 5?|2 user_id 5?|3 period_start_ms 3|4 period_end_ms 3|5 group_by #0|6 spend_type #1?|7 service_account_id 9?|8 cloud_agent_id 9?|9 automation_id 9?|10 automation_managed_type 9?|11 client_type 9?|12 products 9*|13 include_credit_usage 8?|14 ranking_metric #2?",Vr,Yr,Xr]}}class JE extends T{constructor(t){super(),this.day=n.protoInt64.zero,this.category="",this.spendCents=0,this.totalTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JE).fromBinary(t,r)}static fromJson(t,r){return(new JE).fromJson(t,r)}static fromJsonString(t,r){return(new JE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JE,t,r)}static $(){return["DailySpendByCategory|1 day 3|2 category 9|3 spend_cents 5|4 total_tokens 3"]}}class wE extends T{constructor(t){super(),this.dailySpend=[],this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wE).fromBinary(t,r)}static fromJson(t,r){return(new wE).fromJson(t,r)}static fromJsonString(t,r){return(new wE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wE,t,r)}static $(){return["GetDailySpendByCategoryResponse|1 daily_spend #0*|2 categories 9*|3 effective_limit_cents 5?",JE]}}class yE extends T{constructor(t){super(),this.organizationId="",this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,this.groupBy=Vr.UNSPECIFIED,this.products=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yE).fromBinary(t,r)}static fromJson(t,r){return(new yE).fromJson(t,r)}static fromJsonString(t,r){return(new yE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yE,t,r)}static $(){return["GetOrgDailySpendByCategoryRequest|1 organization_id 9|2 period_start_ms 3|3 period_end_ms 3|4 group_by #0|5 spend_type #1?|6 team_id 5?|7 service_account_id 9?|8 cloud_agent_id 9?|9 automation_id 9?|10 automation_managed_type 9?|11 client_type 9?|12 products 9*|13 user_id 5?|14 ranking_metric #2?",Vr,Yr,Xr]}}class SE extends T{constructor(t){super(),this.id=0,this.name="",this.teamId=0,this.memberCount=0,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.type=Qr.UNSPECIFIED,this.members=[],this.formerMembers=[],this.dailySpend=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SE).fromBinary(t,r)}static fromJson(t,r){return(new SE).fromJson(t,r)}static fromJsonString(t,r){return(new SE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SE,t,r)}static $(){return["Group|1 id 5|2 name 9|3 team_id 5|4 directory_group_id 5?|5 member_count 5|6 created_at 3|7 updated_at 3|8 type #0|9 members #1*|10 spend_cents 5?|11 directory_group_name 9?|12 former_members #1*|13 daily_spend #2*",Qr,qE,gE]}}class qE extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.joinedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qE).fromBinary(t,r)}static fromJson(t,r){return(new qE).fromJson(t,r)}static fromJsonString(t,r){return(new qE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qE,t,r)}static $(){return["GroupMember|1 user_id 5|2 name 9|3 email 9|4 joined_at 3|5 spend_cents 5?|6 left_at 3?|7 effective_per_user_limit_dollars 5?"]}}class BE extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.spendCents=0,this.dailySpend=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BE).fromBinary(t,r)}static fromJson(t,r){return(new BE).fromJson(t,r)}static fromJsonString(t,r){return(new BE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BE,t,r)}static $(){return["ServiceAccountSpendInfo|1 service_account_id 9|2 name 9|3 service_type 9|4 spend_cents 5|5 daily_spend #0*|6 creator_name 9?|7 created_at 3?",gE]}}class IE extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IE).fromBinary(t,r)}static fromJson(t,r){return(new IE).fromJson(t,r)}static fromJsonString(t,r){return(new IE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IE,t,r)}static $(){return["GetGroupsRequest|1 team_id 5|2 type #0?|3 reference_date 3?",Qr]}}class PE extends T{constructor(t){super(),this.groups=[],this.unassignedMembers=[],this.teamDailySpend=[],this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PE).fromBinary(t,r)}static fromJson(t,r){return(new PE).fromJson(t,r)}static fromJsonString(t,r){return(new PE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PE,t,r)}static $(){return["GetGroupsResponse|1 groups #0*|2 unassigned_members #1*|3 unassigned_group #0?|4 cycle_start 3?|5 cycle_end 3?|6 team_daily_spend #2*|7 service_accounts #3*",SE,qE,gE,BE]}}class bE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bE).fromBinary(t,r)}static fromJson(t,r){return(new bE).fromJson(t,r)}static fromJsonString(t,r){return(new bE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bE,t,r)}static $(){return["GetGroupMembersRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class RE extends T{constructor(t){super(),this.members=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RE).fromBinary(t,r)}static fromJson(t,r){return(new RE).fromJson(t,r)}static fromJsonString(t,r){return(new RE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RE,t,r)}static $(){return["GetGroupMembersResponse|1 members #0*",qE]}}class vE extends T{constructor(t){super(),this.teamId=0,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vE).fromBinary(t,r)}static fromJson(t,r){return(new vE).fromJson(t,r)}static fromJsonString(t,r){return(new vE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vE,t,r)}static $(){return["CreateGroupRequest|1 team_id 5|2 name 9|3 directory_group_id 5?|4 type #0?",Qr]}}class xE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xE).fromBinary(t,r)}static fromJson(t,r){return(new xE).fromJson(t,r)}static fromJsonString(t,r){return(new xE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xE,t,r)}static $(){return["CreateGroupResponse|1 group #0",SE]}}class kE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kE).fromBinary(t,r)}static fromJson(t,r){return(new kE).fromJson(t,r)}static fromJsonString(t,r){return(new kE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kE,t,r)}static $(){return["UpdateGroupRequest|1 group_id 5|2 team_id 5|3 name 9?|4 type #0?|5 directory_group_id 5?",Qr]}}class EE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EE).fromBinary(t,r)}static fromJson(t,r){return(new EE).fromJson(t,r)}static fromJsonString(t,r){return(new EE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EE,t,r)}static $(){return["UpdateGroupResponse|1 group #0",SE]}}class CE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CE).fromBinary(t,r)}static fromJson(t,r){return(new CE).fromJson(t,r)}static fromJsonString(t,r){return(new CE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CE,t,r)}static $(){return["DeleteGroupRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class TE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TE).fromBinary(t,r)}static fromJson(t,r){return(new TE).fromJson(t,r)}static fromJsonString(t,r){return(new TE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TE,t,r)}static $(){return["DeleteGroupResponse"]}}class UE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UE).fromBinary(t,r)}static fromJson(t,r){return(new UE).fromJson(t,r)}static fromJsonString(t,r){return(new UE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UE,t,r)}static $(){return["AddGroupMembersRequest|1 group_id 5|2 team_id 5|3 user_ids 5*|4 type #0?",Qr]}}class AE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AE).fromBinary(t,r)}static fromJson(t,r){return(new AE).fromJson(t,r)}static fromJsonString(t,r){return(new AE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AE,t,r)}static $(){return["AddGroupMembersResponse|1 group #0",SE]}}class $E extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $E).fromBinary(t,r)}static fromJson(t,r){return(new $E).fromJson(t,r)}static fromJsonString(t,r){return(new $E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($E,t,r)}static $(){return["RemoveGroupMembersRequest|1 group_id 5|2 team_id 5|3 user_ids 5*|4 type #0?",Qr]}}class ME extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ME).fromBinary(t,r)}static fromJson(t,r){return(new ME).fromJson(t,r)}static fromJsonString(t,r){return(new ME).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ME,t,r)}static $(){return["RemoveGroupMembersResponse|1 group #0",SE]}}class OE extends T{constructor(t){super(),this.email="",this.groupName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OE).fromBinary(t,r)}static fromJson(t,r){return(new OE).fromJson(t,r)}static fromJsonString(t,r){return(new OE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OE,t,r)}static $(){return["GroupAssignment|1 email 9|2 group_name 9"]}}class DE extends T{constructor(t){super(),this.teamId=0,this.assignments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DE).fromBinary(t,r)}static fromJson(t,r){return(new DE).fromJson(t,r)}static fromJsonString(t,r){return(new DE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DE,t,r)}static $(){return["BulkAssignGroupMembersRequest|1 team_id 5|2 assignments #0*|3 type #1?",OE,Qr]}}class NE extends T{constructor(t){super(),this.email="",this.groupName="",this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NE).fromBinary(t,r)}static fromJson(t,r){return(new NE).fromJson(t,r)}static fromJsonString(t,r){return(new NE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NE,t,r)}static $(){return["AssignmentResult|1 email 9|2 group_name 9|3 success 8|4 error_message 9?"]}}class GE extends T{constructor(t){super(),this.createdGroups=[],this.results=[],this.successCount=0,this.errorCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GE).fromBinary(t,r)}static fromJson(t,r){return(new GE).fromJson(t,r)}static fromJsonString(t,r){return(new GE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GE,t,r)}static $(){return["BulkAssignGroupMembersResponse|1 created_groups 9*|2 results #0*|3 success_count 5|4 error_count 5",NE]}}class LE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.directoryGroupId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LE).fromBinary(t,r)}static fromJson(t,r){return(new LE).fromJson(t,r)}static fromJsonString(t,r){return(new LE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LE,t,r)}static $(){return["PreviewAttachGroupToDirectoryRequest|1 group_id 5|2 team_id 5|3 directory_group_id 5|4 type #0?",Qr]}}class FE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.changeType=Zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FE).fromBinary(t,r)}static fromJson(t,r){return(new FE).fromJson(t,r)}static fromJsonString(t,r){return(new FE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FE,t,r)}static $(){return["GroupMemberChange|1 user_id 5|2 email 9|3 name 9|4 change_type #0",Zr]}}class KE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.currentGroupId=0,this.currentGroupName="",this.isCurrentGroupScim=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KE).fromBinary(t,r)}static fromJson(t,r){return(new KE).fromJson(t,r)}static fromJsonString(t,r){return(new KE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KE,t,r)}static $(){return["ConflictedUser|1 user_id 5|2 email 9|3 name 9|4 current_group_id 5|5 current_group_name 9|6 is_current_group_scim 8"]}}class zE extends T{constructor(t){super(),this.changes=[],this.membersToAdd=0,this.membersToRemove=0,this.directoryGroupName="",this.membersSkippedDueToConflict=0,this.conflictedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zE).fromBinary(t,r)}static fromJson(t,r){return(new zE).fromJson(t,r)}static fromJsonString(t,r){return(new zE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zE,t,r)}static $(){return["PreviewAttachGroupToDirectoryResponse|1 changes #0*|2 members_to_add 5|3 members_to_remove 5|4 directory_group_name 9|5 members_skipped_due_to_conflict 5|6 conflicted_users #1*",FE,KE]}}class jE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jE).fromBinary(t,r)}static fromJson(t,r){return(new jE).fromJson(t,r)}static fromJsonString(t,r){return(new jE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jE,t,r)}static $(){return["DetachGroupFromDirectoryRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class HE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HE).fromBinary(t,r)}static fromJson(t,r){return(new HE).fromJson(t,r)}static fromJsonString(t,r){return(new HE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HE,t,r)}static $(){return["DetachGroupFromDirectoryResponse|1 group #0",SE]}}class WE extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WE).fromBinary(t,r)}static fromJson(t,r){return(new WE).fromJson(t,r)}static fromJsonString(t,r){return(new WE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WE,t,r)}static $(){return["GetScimConflictsRequest|1 team_id 5|2 type #0?",Qr]}}class QE extends T{constructor(t){super(),this.directoryGroupId=0,this.directoryGroupName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QE).fromBinary(t,r)}static fromJson(t,r){return(new QE).fromJson(t,r)}static fromJsonString(t,r){return(new QE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QE,t,r)}static $(){return["ScimConflictDirectoryGroup|1 directory_group_id 5|2 directory_group_name 9"]}}class VE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.directoryGroups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VE).fromBinary(t,r)}static fromJson(t,r){return(new VE).fromJson(t,r)}static fromJsonString(t,r){return(new VE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VE,t,r)}static $(){return["ScimConflictUser|1 user_id 5|2 email 9|3 name 9|4 directory_groups #0*|5 current_billing_group_id 5?|6 current_billing_group_name 9?|7 current_billing_group_directory_group_id 5?",QE]}}class XE extends T{constructor(t){super(),this.conflictedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XE).fromBinary(t,r)}static fromJson(t,r){return(new XE).fromJson(t,r)}static fromJsonString(t,r){return(new XE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XE,t,r)}static $(){return["GetScimConflictsResponse|1 conflicted_users #0*",VE]}}class YE extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.organizationId="",this.ownerId=n.protoInt64.zero,this.ownerType=te.UNSPECIFIED,this.scimDirectoryExternalId="",this.provider=re.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.identityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YE).fromBinary(t,r)}static fromJson(t,r){return(new YE).fromJson(t,r)}static fromJsonString(t,r){return(new YE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YE,t,r)}static $(){return["ScimDirectory|1 id 3|2 organization_id 9|3 owner_id 3|4 owner_type #0|5 scim_directory_external_id 9|6 provider #1|7 created_at 3|8 updated_at 3|9 sync_directory_users_to_root_team 8?|10 identity_provider_public_id 9",te,re]}}class ZE extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZE).fromBinary(t,r)}static fromJson(t,r){return(new ZE).fromJson(t,r)}static fromJsonString(t,r){return(new ZE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZE,t,r)}static $(){return["ListScimDirectoriesRequest|1 organization_id 9"]}}class tC extends T{constructor(t){super(),this.directories=[],this.multiSourceEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tC).fromBinary(t,r)}static fromJson(t,r){return(new tC).fromJson(t,r)}static fromJsonString(t,r){return(new tC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tC,t,r)}static $(){return["ListScimDirectoriesResponse|1 directories #0*|2 multi_source_enabled 8",YE]}}class rC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryExternalId="",this.provider=re.UNSPECIFIED,this.ownerType=te.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rC).fromBinary(t,r)}static fromJson(t,r){return(new rC).fromJson(t,r)}static fromJsonString(t,r){return(new rC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rC,t,r)}static $(){return["CreateScimDirectoryRequest|1 organization_id 9|2 scim_directory_external_id 9|3 provider #0|4 owner_type #1",re,te]}}class eC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eC).fromBinary(t,r)}static fromJson(t,r){return(new eC).fromJson(t,r)}static fromJsonString(t,r){return(new eC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eC,t,r)}static $(){return["CreateScimDirectoryResponse|1 directory #0",YE]}}class nC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nC).fromBinary(t,r)}static fromJson(t,r){return(new nC).fromJson(t,r)}static fromJsonString(t,r){return(new nC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nC,t,r)}static $(){return["UpdateScimDirectorySyncSettingsRequest|1 organization_id 9|2 scim_directory_id 3|3 sync_directory_users_to_root_team 8?"]}}class sC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sC).fromBinary(t,r)}static fromJson(t,r){return(new sC).fromJson(t,r)}static fromJsonString(t,r){return(new sC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sC,t,r)}static $(){return["UpdateScimDirectorySyncSettingsResponse|1 directory #0",YE]}}class iC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iC).fromBinary(t,r)}static fromJson(t,r){return(new iC).fromJson(t,r)}static fromJsonString(t,r){return(new iC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iC,t,r)}static $(){return["DeleteScimDirectoryRequest|1 organization_id 9|2 scim_directory_id 3"]}}class oC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oC).fromBinary(t,r)}static fromJson(t,r){return(new oC).fromJson(t,r)}static fromJsonString(t,r){return(new oC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oC,t,r)}static $(){return["DeleteScimDirectoryResponse"]}}class aC extends T{constructor(t){super(),this.scimGroupExternalId="",this.name="",this.workosGroupId="",this.idpId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aC).fromBinary(t,r)}static fromJson(t,r){return(new aC).fromJson(t,r)}static fromJsonString(t,r){return(new aC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aC,t,r)}static $(){return["ScimUpstreamGroup|1 scim_group_external_id 9|2 name 9|3 workos_group_id 9|4 idp_id 9"]}}class uC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uC).fromBinary(t,r)}static fromJson(t,r){return(new uC).fromJson(t,r)}static fromJsonString(t,r){return(new uC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uC,t,r)}static $(){return["ListScimGroupsFromUpstreamRequest|1 organization_id 9|2 scim_directory_id 3"]}}class cC extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cC).fromBinary(t,r)}static fromJson(t,r){return(new cC).fromJson(t,r)}static fromJsonString(t,r){return(new cC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cC,t,r)}static $(){return["ListScimGroupsFromUpstreamResponse|1 groups #0*",aC]}}class lC extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",this.targetId=n.protoInt64.zero,this.targetType=ee.UNSPECIFIED,this.syncState=ne.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.sourceType=se.UNSPECIFIED,this.role=ie.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lC).fromBinary(t,r)}static fromJson(t,r){return(new lC).fromJson(t,r)}static fromJsonString(t,r){return(new lC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lC,t,r)}static $(){return["ScimTargetMapping|1 id 3|2 scim_directory_id 3|3 scim_group_external_id 9|4 target_id 3|5 target_type #0|6 sync_state #1|7 last_synced_at 3?|8 created_at 3|9 updated_at 3|10 source_type #2|11 cursor_group_id 3?|12 role #3",ee,ne,se,ie]}}class mC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mC).fromBinary(t,r)}static fromJson(t,r){return(new mC).fromJson(t,r)}static fromJsonString(t,r){return(new mC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mC,t,r)}static $(){return["ListScimTargetMappingsRequest|1 organization_id 9|2 scim_directory_id 3"]}}class fC extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fC).fromBinary(t,r)}static fromJson(t,r){return(new fC).fromJson(t,r)}static fromJsonString(t,r){return(new fC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fC,t,r)}static $(){return["ListScimTargetMappingsResponse|1 mappings #0*",lC]}}class dC extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dC).fromBinary(t,r)}static fromJson(t,r){return(new dC).fromJson(t,r)}static fromJsonString(t,r){return(new dC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dC,t,r)}static $(){return["ListOrganizationGroupTargetMappingsRequest|1 organization_id 9"]}}class pC extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pC).fromBinary(t,r)}static fromJson(t,r){return(new pC).fromJson(t,r)}static fromJsonString(t,r){return(new pC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pC,t,r)}static $(){return["ListOrganizationGroupTargetMappingsResponse|1 mappings #0*",lC]}}class hC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",this.targetId=n.protoInt64.zero,this.targetType=ee.UNSPECIFIED,this.role=ie.UNSPECIFIED,this.sourceType=se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hC).fromBinary(t,r)}static fromJson(t,r){return(new hC).fromJson(t,r)}static fromJsonString(t,r){return(new hC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hC,t,r)}static $(){return["CreateScimTargetMappingRequest|1 organization_id 9|2 scim_directory_id 3|3 scim_group_external_id 9|4 target_id 3|5 target_type #0|6 cursor_group_id 3?|7 role #1|8 source_type #2",ee,ie,se]}}class gC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gC).fromBinary(t,r)}static fromJson(t,r){return(new gC).fromJson(t,r)}static fromJsonString(t,r){return(new gC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gC,t,r)}static $(){return["CreateScimTargetMappingResponse|1 mapping #0",lC]}}class _C extends T{constructor(t){super(),this.organizationId="",this.scimTargetMappingId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _C).fromBinary(t,r)}static fromJson(t,r){return(new _C).fromJson(t,r)}static fromJsonString(t,r){return(new _C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_C,t,r)}static $(){return["DeleteScimTargetMappingRequest|1 organization_id 9|2 scim_target_mapping_id 3"]}}class JC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JC).fromBinary(t,r)}static fromJson(t,r){return(new JC).fromJson(t,r)}static fromJsonString(t,r){return(new JC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JC,t,r)}static $(){return["DeleteScimTargetMappingResponse"]}}class wC extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wC).fromBinary(t,r)}static fromJson(t,r){return(new wC).fromJson(t,r)}static fromJsonString(t,r){return(new wC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wC,t,r)}static $(){return["NotifyTeamAdminsRepo|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9"]}}class yC extends T{constructor(t){super(),this.teamId=0,this.requestType=oe.UNSPECIFIED,this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yC).fromBinary(t,r)}static fromJson(t,r){return(new yC).fromJson(t,r)}static fromJsonString(t,r){return(new yC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yC,t,r)}static $(){return["NotifyTeamAdminsRequest|1 team_id 5|2 request_type #0|3 repos #1*|4 ghe_application 9?",oe,wC]}}class SC extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SC).fromBinary(t,r)}static fromJson(t,r){return(new SC).fromJson(t,r)}static fromJsonString(t,r){return(new SC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SC,t,r)}static $(){return["NotifyTeamAdminsResponse|1 success 8|2 error_message 9?"]}}class qC extends T{constructor(t){super(),this.teamId=0,this.requestType=oe.UNSPECIFIED,this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qC).fromBinary(t,r)}static fromJson(t,r){return(new qC).fromJson(t,r)}static fromJsonString(t,r){return(new qC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qC,t,r)}static $(){return["GetAdminNotificationStatusRequest|1 team_id 5|2 request_type #0|3 repos #1*|4 ghe_application 9?",oe,wC]}}class BC extends T{constructor(t){super(),this.canSend=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BC).fromBinary(t,r)}static fromJson(t,r){return(new BC).fromJson(t,r)}static fromJsonString(t,r){return(new BC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BC,t,r)}static $(){return["GetAdminNotificationStatusResponse|1 can_send 8|2 last_sent_timestamp 3?"]}}class IC extends T{constructor(t){super(),this.slackTeamId="",this.slackUserId="",this.setupPrerequisitesComplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IC).fromBinary(t,r)}static fromJson(t,r){return(new IC).fromJson(t,r)}static fromJsonString(t,r){return(new IC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IC,t,r)}static $(){return["CompletedLinkSlackAccountRequest|1 slack_team_id 9|2 slack_user_id 9|3 setup_prerequisites_complete 8"]}}class PC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PC).fromBinary(t,r)}static fromJson(t,r){return(new PC).fromJson(t,r)}static fromJsonString(t,r){return(new PC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PC,t,r)}static $(){return["CompletedLinkSlackAccountResponse"]}}class bC extends T{constructor(t){super(),this.optIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bC).fromBinary(t,r)}static fromJson(t,r){return(new bC).fromJson(t,r)}static fromJsonString(t,r){return(new bC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bC,t,r)}static $(){return["OptOutNewPricingRequest|1 opt_in 8"]}}class RC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RC).fromBinary(t,r)}static fromJson(t,r){return(new RC).fromJson(t,r)}static fromJsonString(t,r){return(new RC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RC,t,r)}static $(){return["OptOutNewPricingResponse"]}}class vC extends T{constructor(t){super(),this.teamId=0,this.optOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vC).fromBinary(t,r)}static fromJson(t,r){return(new vC).fromJson(t,r)}static fromJsonString(t,r){return(new vC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vC,t,r)}static $(){return["UpdateTeamPrivacyModeMigrationOptOutRequest|1 team_id 5|2 opt_out 8"]}}class xC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xC).fromBinary(t,r)}static fromJson(t,r){return(new xC).fromJson(t,r)}static fromJsonString(t,r){return(new xC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xC,t,r)}static $(){return["UpdateTeamPrivacyModeMigrationOptOutResponse"]}}class kC extends T{constructor(t){super(),this.message="",this.version="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kC).fromBinary(t,r)}static fromJson(t,r){return(new kC).fromJson(t,r)}static fromJsonString(t,r){return(new kC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kC,t,r)}static $(){return["SubmitFeedbackRequest|1 message 9|2 version 9|3 last_agent_req_id 9?|4 os 9?|5 terminal 9?|6 shell 9?|7 model 9?|8 update_channel 9?|9 agent_mode 9?"]}}class EC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EC).fromBinary(t,r)}static fromJson(t,r){return(new EC).fromJson(t,r)}static fromJsonString(t,r){return(new EC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EC,t,r)}static $(){return["SubmitFeedbackResponse"]}}class CC extends T{constructor(t){super(),this.token="",this.remotesText="",this.commitsText="",this.claimantCompanyName="",this.claimantContactEmail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CC).fromBinary(t,r)}static fromJson(t,r){return(new CC).fromJson(t,r)}static fromJsonString(t,r){return(new CC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CC,t,r)}static $(){return["SubmitRepositoryProtectionClaimRequest|1 token 9|2 remotes_text 9|3 commits_text 9|4 claimant_company_name 9|5 claimant_contact_email 9"]}}class TC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TC).fromBinary(t,r)}static fromJson(t,r){return(new TC).fromJson(t,r)}static fromJsonString(t,r){return(new TC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TC,t,r)}static $(){return["SubmitRepositoryProtectionClaimResponse"]}}class UC extends T{constructor(t){super(),this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UC).fromBinary(t,r)}static fromJson(t,r){return(new UC).fromJson(t,r)}static fromJsonString(t,r){return(new UC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UC,t,r)}static $(){return["ActivateRepositoryProtectionInviteRequest|1 id 9"]}}class AC extends T{constructor(t){super(),this.activated=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AC).fromBinary(t,r)}static fromJson(t,r){return(new AC).fromJson(t,r)}static fromJsonString(t,r){return(new AC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AC,t,r)}static $(){return["ActivateRepositoryProtectionInviteResponse|1 activated 5"]}}class $C extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $C).fromBinary(t,r)}static fromJson(t,r){return(new $C).fromJson(t,r)}static fromJsonString(t,r){return(new $C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($C,t,r)}static $(){return["GetTeamBugbotSettingsRequest|1 team_id 5"]}}class MC extends T{constructor(t){super(),this.githubUsername="",this.firstReviewTimestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MC).fromBinary(t,r)}static fromJson(t,r){return(new MC).fromJson(t,r)}static fromJsonString(t,r){return(new MC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MC,t,r)}static $(){return["BugbotLicenseUsage|1 github_username 9|2 first_review_timestamp 3|3 github_user_node_id 9?"]}}class OC extends T{constructor(t){super(),this.bugbotLicensesHardLimit=0,this.bugbotPlanEnabled=!1,this.allowlist=[],this.currentCycleUniqueUsers=0,this.bugbotLicenseCount=0,this.allowlistConfig=Tr.UNSPECIFIED,this.bugbotWasEnabledInThisBillingCycle=!1,this.licenseUsage=[],this.bugbotUsageTier=$r.UNSPECIFIED,this.bugbotGloballyDisabled=!1,this.mcpServerNames=[],this.bugbotBillingMode=Mr.UNSPECIFIED,this.bugbotUsageBasedOnEnable=!1,this.canMigrateToUsageBased=!1,this.seatLicenseCount=0,this.bugbotMigrationCreditAlreadyGranted=!1,this.isIncrementalReviewEnabled=!1,this.mergedPrScanOptedOut=!1,this.coverExternalPublicContributors=!1,this.repoAutoEnablePolicy=Or.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OC).fromBinary(t,r)}static fromJson(t,r){return(new OC).fromJson(t,r)}static fromJsonString(t,r){return(new OC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OC,t,r)}static $(){return["GetTeamBugbotSettingsResponse|1 bugbot_licenses_hard_limit 5|2 bugbot_plan_enabled 8|3 allowlist 9*|4 current_cycle_unique_users 5|5 bugbot_license_count 5|6 allowlist_config #0|7 bugbot_was_enabled_in_this_billing_cycle 8|8 license_usage #1*|9 bugbot_usage_tier #2|10 bugbot_globally_disabled 8|11 mcp_server_names 9*|12 bugbot_billing_mode #3|13 bugbot_usage_based_on_enable 8|14 can_migrate_to_usage_based 8|15 seat_license_count 5|16 bugbot_migration_credit_already_granted 8|17 is_incremental_review_enabled 8|18 merged_pr_scan_opted_out 8|23 cover_external_public_contributors 8|24 repo_auto_enable_policy #4",Tr,MC,$r,Mr,Or]}}class DC extends T{constructor(t){super(),this.teamId=0,this.allowlist=[],this.mcpServerNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DC).fromBinary(t,r)}static fromJson(t,r){return(new DC).fromJson(t,r)}static fromJsonString(t,r){return(new DC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DC,t,r)}static $(){return["UpdateTeamBugbotSettingsRequest|1 team_id 5|2 bugbot_licenses_hard_limit 5?|3 bugbot_plan_enabled 8?|4 allowlist 9*|5 allowlist_config #0?|6 bugbot_globally_disabled 8?|7 mcp_server_names 9*|8 is_incremental_review_enabled 8?|9 merged_pr_scan_opt_out 8?|10 apply_onboarding_high_effort_learning_defaults 8?|14 cover_external_public_contributors 8?|15 repo_auto_enable_policy #1?",Tr,Or]}}class NC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NC).fromBinary(t,r)}static fromJson(t,r){return(new NC).fromJson(t,r)}static fromJsonString(t,r){return(new NC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NC,t,r)}static $(){return["UpdateTeamBugbotSettingsResponse"]}}class GC extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GC).fromBinary(t,r)}static fromJson(t,r){return(new GC).fromJson(t,r)}static fromJsonString(t,r){return(new GC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GC,t,r)}static $(){return["MigrateTeamBugbotToUsageBasedBillingRequest|1 team_id 5|2 keep_high_effort_default 8?"]}}class LC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LC).fromBinary(t,r)}static fromJson(t,r){return(new LC).fromJson(t,r)}static fromJsonString(t,r){return(new LC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LC,t,r)}static $(){return["MigrateTeamBugbotToUsageBasedBillingResponse"]}}class FC extends T{constructor(t){super(),this.values={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FC).fromBinary(t,r)}static fromJson(t,r){return(new FC).fromJson(t,r)}static fromJsonString(t,r){return(new FC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FC,t,r)}static $(){return["TeamCustomerTelemetryDestinationHeaders|1 values 9,9"]}}class KC extends T{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KC).fromBinary(t,r)}static fromJson(t,r){return(new KC).fromJson(t,r)}static fromJsonString(t,r){return(new KC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KC,t,r)}static $(){return["TeamCustomerTelemetryDestinationFamilyList|1 ids 9*"]}}class zC extends T{constructor(t){super(),this.id="",this.displayName="",this.description="",this.metrics=!1,this.logs=!1,this.requiresExplicitEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zC).fromBinary(t,r)}static fromJson(t,r){return(new zC).fromJson(t,r)}static fromJsonString(t,r){return(new zC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zC,t,r)}static $(){return["TeamCustomerTelemetryDestinationFamily|1 id 9|2 display_name 9|3 description 9|4 metrics 8|5 logs 8|6 requires_explicit_enable 8"]}}class jC extends T{constructor(t){super(),this.id="",this.kind=ae.UNSPECIFIED,this.endpointUrl="",this.enabled=!1,this.metricsEnabled=!1,this.logsEnabled=!1,this.hasCredentials=!1,this.activatedAtEpochMillis=n.protoInt64.zero,this.createdAtEpochMillis=n.protoInt64.zero,this.updatedAtEpochMillis=n.protoInt64.zero,this.credentialHeaderNames=[],this.disabledFamilies=[],this.enabledFamilies=[],this.autoEnableNewFamilies=!1,this.contentPromptsEnabled=!1,this.contentResponsesEnabled=!1,this.contentToolIoEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jC).fromBinary(t,r)}static fromJson(t,r){return(new jC).fromJson(t,r)}static fromJsonString(t,r){return(new jC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jC,t,r)}static $(){return["TeamCustomerTelemetryDestination|1 id 9|2 kind #0|3 endpoint_url 9|4 enabled 8|5 metrics_enabled 8|6 logs_enabled 8|7 has_credentials 8|8 activated_at_epoch_millis 3|9 created_at_epoch_millis 3|10 updated_at_epoch_millis 3|11 credential_header_names 9*|12 disabled_families 9*|13 enabled_families 9*|14 auto_enable_new_families 8|15 content_prompts_enabled 8|16 content_responses_enabled 8|17 content_tool_io_enabled 8",ae]}}class HC extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HC).fromBinary(t,r)}static fromJson(t,r){return(new HC).fromJson(t,r)}static fromJsonString(t,r){return(new HC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HC,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationsRequest|1 team_id 5"]}}class WC extends T{constructor(t){super(),this.destinations=[],this.availableFamilies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WC).fromBinary(t,r)}static fromJson(t,r){return(new WC).fromJson(t,r)}static fromJsonString(t,r){return(new WC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WC,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationsResponse|1 destinations #0*|2 available_families #1*",jC,zC]}}class QC extends T{constructor(t){super(),this.teamId=0,this.endpointUrl="",this.metricsEnabled=!1,this.logsEnabled=!1,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QC).fromBinary(t,r)}static fromJson(t,r){return(new QC).fromJson(t,r)}static fromJsonString(t,r){return(new QC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QC,t,r)}static $(){return["CreateTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 endpoint_url 9|3 headers #0?|4 metrics_enabled 8|5 logs_enabled 8|6 enabled 8|7 disabled_families #1?|8 enabled_families #1?|9 auto_enable_new_families 8?|10 content_prompts_enabled 8?|11 content_responses_enabled 8?|12 content_tool_io_enabled 8?",FC,KC]}}class VC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VC).fromBinary(t,r)}static fromJson(t,r){return(new VC).fromJson(t,r)}static fromJsonString(t,r){return(new VC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VC,t,r)}static $(){return["CreateTeamCustomerTelemetryDestinationResponse|1 destination #0",jC]}}class XC extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XC).fromBinary(t,r)}static fromJson(t,r){return(new XC).fromJson(t,r)}static fromJsonString(t,r){return(new XC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XC,t,r)}static $(){return["UpdateTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 destination_id 9|3 endpoint_url 9?|4 headers #0?|5 metrics_enabled 8?|6 logs_enabled 8?|7 enabled 8?|8 disabled_families #1?|9 enabled_families #1?|10 auto_enable_new_families 8?|11 content_prompts_enabled 8?|12 content_responses_enabled 8?|13 content_tool_io_enabled 8?",FC,KC]}}class YC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YC).fromBinary(t,r)}static fromJson(t,r){return(new YC).fromJson(t,r)}static fromJsonString(t,r){return(new YC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YC,t,r)}static $(){return["UpdateTeamCustomerTelemetryDestinationResponse|1 destination #0",jC]}}class ZC extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZC).fromBinary(t,r)}static fromJson(t,r){return(new ZC).fromJson(t,r)}static fromJsonString(t,r){return(new ZC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZC,t,r)}static $(){return["DeleteTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 destination_id 9"]}}class tT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tT).fromBinary(t,r)}static fromJson(t,r){return(new tT).fromJson(t,r)}static fromJsonString(t,r){return(new tT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tT,t,r)}static $(){return["DeleteTeamCustomerTelemetryDestinationResponse"]}}class rT extends T{constructor(t){super(),this.teamId=0,this.endpointUrl="",this.signal=ue.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rT).fromBinary(t,r)}static fromJson(t,r){return(new rT).fromJson(t,r)}static fromJsonString(t,r){return(new rT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rT,t,r)}static $(){return["TestTeamCustomerTelemetryDestinationConnectionRequest|1 team_id 5|2 endpoint_url 9|3 headers #0?|4 signal #1",FC,ue]}}class eT extends T{constructor(t){super(),this.ok=!1,this.outcome=ce.UNSPECIFIED,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eT).fromBinary(t,r)}static fromJson(t,r){return(new eT).fromJson(t,r)}static fromJsonString(t,r){return(new eT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eT,t,r)}static $(){return["TestTeamCustomerTelemetryDestinationConnectionResponse|1 ok 8|2 outcome #0|3 status_code 5?|4 latency_ms 3?|5 message 9",ce]}}class nT extends T{constructor(t){super(),this.bucketStartEpochMillis=n.protoInt64.zero,this.exported=n.protoInt64.zero,this.failed=n.protoInt64.zero,this.dropped=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nT).fromBinary(t,r)}static fromJson(t,r){return(new nT).fromJson(t,r)}static fromJsonString(t,r){return(new nT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nT,t,r)}static $(){return["TeamCustomerTelemetryDestinationHealthBucket|1 bucket_start_epoch_millis 3|2 exported 3|3 failed 3|4 dropped 3"]}}class sT extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.errorClass="",this.signal="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sT).fromBinary(t,r)}static fromJson(t,r){return(new sT).fromJson(t,r)}static fromJsonString(t,r){return(new sT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sT,t,r)}static $(){return["TeamCustomerTelemetryDestinationRecentError|1 at_epoch_millis 3|2 error_class 9|3 status_code 5?|4 signal 9"]}}class iT extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iT).fromBinary(t,r)}static fromJson(t,r){return(new iT).fromJson(t,r)}static fromJsonString(t,r){return(new iT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iT,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationHealthRequest|1 team_id 5|2 destination_id 9"]}}class oT extends T{constructor(t){super(),this.status=le.UNSPECIFIED,this.buckets=[],this.lastErrorClass="",this.queueDepth=n.protoInt64.zero,this.breakerState="",this.oldestBatchAgeMs=n.protoInt64.zero,this.recentErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oT).fromBinary(t,r)}static fromJson(t,r){return(new oT).fromJson(t,r)}static fromJsonString(t,r){return(new oT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oT,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationHealthResponse|1 status #0|2 buckets #1*|3 last_success_at_epoch_millis 3?|4 last_error_at_epoch_millis 3?|5 last_error_class 9|6 last_error_status 5?|7 queue_depth 3|8 breaker_state 9|9 oldest_batch_age_ms 3|10 recent_errors #2*",le,nT,sT]}}class aT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aT).fromBinary(t,r)}static fromJson(t,r){return(new aT).fromJson(t,r)}static fromJsonString(t,r){return(new aT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aT,t,r)}static $(){return["GetTeamCustomerTelemetryContentExportOptInRequest|1 team_id 5"]}}class uT extends T{constructor(t){super(),this.enabled=!1,this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uT).fromBinary(t,r)}static fromJson(t,r){return(new uT).fromJson(t,r)}static fromJsonString(t,r){return(new uT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uT,t,r)}static $(){return["GetTeamCustomerTelemetryContentExportOptInResponse|1 enabled 8|2 available 8"]}}class cT extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cT).fromBinary(t,r)}static fromJson(t,r){return(new cT).fromJson(t,r)}static fromJsonString(t,r){return(new cT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cT,t,r)}static $(){return["UpdateTeamCustomerTelemetryContentExportOptInRequest|1 team_id 5|2 enabled 8"]}}class lT extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lT).fromBinary(t,r)}static fromJson(t,r){return(new lT).fromJson(t,r)}static fromJsonString(t,r){return(new lT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lT,t,r)}static $(){return["UpdateTeamCustomerTelemetryContentExportOptInResponse|1 enabled 8"]}}class mT extends T{constructor(t){super(),this.id="",this.name="",this.prompt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mT).fromBinary(t,r)}static fromJson(t,r){return(new mT).fromJson(t,r)}static fromJsonString(t,r){return(new mT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mT,t,r)}static $(){return["InferenceHookDecisionQuestion|1 id 9|2 name 9|3 prompt 9"]}}class fT extends T{constructor(t){super(),this.questionId="",this.operator=pe.UNSPECIFIED,this.confidencePercent=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fT).fromBinary(t,r)}static fromJson(t,r){return(new fT).fromJson(t,r)}static fromJsonString(t,r){return(new fT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fT,t,r)}static $(){return["InferenceHookDecisionRuleCondition|1 question_id 9|2 operator #0|3 confidence_percent 5",pe]}}class dT extends T{constructor(t){super(),this.id="",this.name="",this.enabled=!1,this.events=[],this.conditions=[],this.mode=he.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dT).fromBinary(t,r)}static fromJson(t,r){return(new dT).fromJson(t,r)}static fromJsonString(t,r){return(new dT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dT,t,r)}static $(){return["InferenceHookDecisionRule|1 id 9|2 name 9|5 enabled 8|6 events #0*|7 deny_reason 9?|8 conditions #1*|9 mode #2",Je,fT,he]}}class pT extends T{constructor(t){super(),this.rules=[],this.questions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pT).fromBinary(t,r)}static fromJson(t,r){return(new pT).fromJson(t,r)}static fromJsonString(t,r){return(new pT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pT,t,r)}static $(){return["InferenceHookDecisionRuleSet|1 rules #0*|2 questions #1*",dT,mT]}}class hT extends T{constructor(t){super(),this.values={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hT).fromBinary(t,r)}static fromJson(t,r){return(new hT).fromJson(t,r)}static fromJsonString(t,r){return(new hT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hT,t,r)}static $(){return["InferenceHookHeaders|1 values 9,9"]}}class gT extends T{constructor(t){super(),this.surfaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gT).fromBinary(t,r)}static fromJson(t,r){return(new gT).fromJson(t,r)}static fromJsonString(t,r){return(new gT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gT,t,r)}static $(){return["InferenceHookSurfaceList|1 surfaces #0*",fe]}}class _T extends T{constructor(t){super(),this.enforceVerdicts=!1,this.mode=me.UNSPECIFIED,this.endpointUrl="",this.headerNames=[],this.hasHeaderValues=!1,this.hasSigningSecret=!1,this.verdictTimeoutMs=0,this.rolloutPercent=0,this.enabledSurfaces=[],this.blockedMessageEnabled=!1,this.configVersion=n.protoInt64.zero,this.createdAtEpochMillis=n.protoInt64.zero,this.updatedAtEpochMillis=n.protoInt64.zero,this.validateToolCalls=!1,this.hookKind=de.UNSPECIFIED,this.purviewTenantId="",this.decisionRules=[],this.decisionQuestions=[],this.refuseLocalLoopTurns=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _T).fromBinary(t,r)}static fromJson(t,r){return(new _T).fromJson(t,r)}static fromJsonString(t,r){return(new _T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_T,t,r)}static $(){return["TeamInferenceHookConfig|1 enforce_verdicts 8|2 mode #0|3 endpoint_url 9|4 header_names 9*|5 has_header_values 8|6 has_signing_secret 8|7 signing_secret_created_at_epoch_millis 3?|8 verdict_timeout_ms 5|9 rollout_percent 5|10 enabled_surfaces #1*|11 blocked_message_enabled 8|12 blocked_message 9?|13 config_version 3|14 breaker_tripped_at_epoch_millis 3?|15 created_at_epoch_millis 3|16 updated_at_epoch_millis 3|17 validate_tool_calls 8|18 hook_kind #2|19 purview_tenant_id 9|20 sensitivity_label_policy #3|21 decision_rules #4*|22 decision_questions #5*|23 refuse_local_loop_turns 8",me,fe,de,JT,dT,mT]}}class JT extends T{constructor(t){super(),this.mode=ge.UNSPECIFIED,this.labelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JT).fromBinary(t,r)}static fromJson(t,r){return(new JT).fromJson(t,r)}static fromJsonString(t,r){return(new JT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JT,t,r)}static $(){return["InferenceHookSensitivityLabelPolicy|1 mode #0|2 label_ids 9*|3 default_label_id 9?",ge]}}class wT extends T{constructor(t){super(),this.id="",this.name="",this.priority=0,this.appliesEncryption=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wT).fromBinary(t,r)}static fromJson(t,r){return(new wT).fromJson(t,r)}static fromJsonString(t,r){return(new wT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wT,t,r)}static $(){return["InferenceHookSensitivityLabel|1 id 9|2 name 9|3 priority 5|4 applies_encryption 8"]}}class yT extends T{constructor(t){super(),this.available=!1,this.labels=[],this.defaultLabelAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yT).fromBinary(t,r)}static fromJson(t,r){return(new yT).fromJson(t,r)}static fromJsonString(t,r){return(new yT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yT,t,r)}static $(){return["InferenceHookSensitivityLabelCatalog|1 available 8|2 labels #0*|3 default_label_available 8",wT]}}class ST extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ST).fromBinary(t,r)}static fromJson(t,r){return(new ST).fromJson(t,r)}static fromJsonString(t,r){return(new ST).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ST,t,r)}static $(){return["GetTeamInferenceHookConfigRequest|1 team_id 5"]}}class qT extends T{constructor(t){super(),this.availableSurfaces=[],this.effectiveMode=me.UNSPECIFIED,this.sourceIpRanges=[],this.defaultBlockedMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qT).fromBinary(t,r)}static fromJson(t,r){return(new qT).fromJson(t,r)}static fromJsonString(t,r){return(new qT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qT,t,r)}static $(){return["GetTeamInferenceHookConfigResponse|1 config #0|2 available_surfaces #1*|3 effective_mode #2|4 source_ip_ranges 9*|5 default_blocked_message 9|6 available 8?|7 tool_calls_available 8?|8 purview_available 8?|9 purview_client_id 9?|10 sensitivity_label_catalog #3?|11 decision_rules_available 8?",_T,fe,me,yT]}}class BT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BT).fromBinary(t,r)}static fromJson(t,r){return(new BT).fromJson(t,r)}static fromJsonString(t,r){return(new BT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BT,t,r)}static $(){return["UpdateTeamInferenceHookConfigRequest|1 team_id 5|2 enforce_verdicts 8?|3 mode #0?|4 endpoint_url 9?|5 headers #1|6 verdict_timeout_ms 5?|7 rollout_percent 5?|8 enabled_surfaces #2|9 blocked_message_enabled 8?|10 blocked_message 9?|11 expected_config_version 3?|12 validate_tool_calls 8?|13 hook_kind #3?|14 purview_tenant_id 9?|15 sensitivity_label_policy #4|16 decision_rules #5|17 refuse_local_loop_turns 8?",me,hT,gT,de,JT,pT]}}class IT extends T{constructor(t){super(),this.effectiveMode=me.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IT).fromBinary(t,r)}static fromJson(t,r){return(new IT).fromJson(t,r)}static fromJsonString(t,r){return(new IT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IT,t,r)}static $(){return["UpdateTeamInferenceHookConfigResponse|1 config #0|2 effective_mode #1|3 signing_secret 9?",_T,me]}}class PT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PT).fromBinary(t,r)}static fromJson(t,r){return(new PT).fromJson(t,r)}static fromJsonString(t,r){return(new PT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PT,t,r)}static $(){return["RotateTeamInferenceHookSigningSecretRequest|1 team_id 5"]}}class bT extends T{constructor(t){super(),this.signingSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bT).fromBinary(t,r)}static fromJson(t,r){return(new bT).fromJson(t,r)}static fromJsonString(t,r){return(new bT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bT,t,r)}static $(){return["RotateTeamInferenceHookSigningSecretResponse|1 config #0|2 signing_secret 9",_T]}}class RT extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.kind="",this.message="",this.eventType=Je.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RT).fromBinary(t,r)}static fromJson(t,r){return(new RT).fromJson(t,r)}static fromJsonString(t,r){return(new RT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RT,t,r)}static $(){return["InferenceHookRecentError|1 at_epoch_millis 3|2 kind 9|3 message 9|4 status_code 5?|5 event_type #0",Je]}}class vT extends T{constructor(t){super(),this.eventType=Je.UNSPECIFIED,this.failuresPerMinute=0,this.verdictsLast24h=n.protoInt64.zero,this.allowedUninspectedLast24h=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vT).fromBinary(t,r)}static fromJson(t,r){return(new vT).fromJson(t,r)}static fromJsonString(t,r){return(new vT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vT,t,r)}static $(){return["InferenceHookEventHealth|1 event_type #0|2 failures_per_minute 1|3 block_rate 1?|4 verdict_latency_p50_ms 3?|5 verdict_latency_p95_ms 3?|6 verdicts_last_24h 3|7 allowed_uninspected_last_24h 3",Je]}}class xT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xT).fromBinary(t,r)}static fromJson(t,r){return(new xT).fromJson(t,r)}static fromJsonString(t,r){return(new xT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xT,t,r)}static $(){return["GetTeamInferenceHookHealthRequest|1 team_id 5"]}}class kT extends T{constructor(t){super(),this.questionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kT).fromBinary(t,r)}static fromJson(t,r){return(new kT).fromJson(t,r)}static fromJsonString(t,r){return(new kT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kT,t,r)}static $(){return["InferenceHookDecisionQuestionScore|1 question_id 9|2 probability 1?"]}}class ET extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.surface=fe.UNSPECIFIED,this.eventType=Je.UNSPECIFIED,this.enforced=!1,this.toolCallIds=[],this.questionScores=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ET).fromBinary(t,r)}static fromJson(t,r){return(new ET).fromJson(t,r)}static fromJsonString(t,r){return(new ET).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ET,t,r)}static $(){return["InferenceHookRuleRecentMatch|1 at_epoch_millis 3|2 surface #0|3 event_type #1|4 enforced 8|5 conversation_id 9?|6 turn_id 9?|7 caller_request_id 9?|8 tool_call_ids 9*|9 question_scores #2*",fe,Je,kT]}}class CT extends T{constructor(t){super(),this.ruleId="",this.matchesLast24h=n.protoInt64.zero,this.recentMatches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CT).fromBinary(t,r)}static fromJson(t,r){return(new CT).fromJson(t,r)}static fromJsonString(t,r){return(new CT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CT,t,r)}static $(){return["InferenceHookDecisionRuleHealth|1 rule_id 9|2 matches_last_24h 3|3 recent_matches #0*",ET]}}class TT extends T{constructor(t){super(),this.status=_e.UNSPECIFIED,this.failuresPerMinute=0,this.recentErrors=[],this.verdictsLast24h=n.protoInt64.zero,this.allowedUninspectedLast24h=n.protoInt64.zero,this.eventHealth=[],this.ruleHealth=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TT).fromBinary(t,r)}static fromJson(t,r){return(new TT).fromJson(t,r)}static fromJsonString(t,r){return(new TT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TT,t,r)}static $(){return["GetTeamInferenceHookHealthResponse|1 status #0|2 failures_per_minute 1|3 block_rate 1?|4 breaker_tripped_at_epoch_millis 3?|5 recent_errors #1*|6 verdict_latency_p50_ms 3?|7 verdict_latency_p95_ms 3?|8 verdicts_last_24h 3|9 allowed_uninspected_last_24h 3|10 event_health #2*|11 rule_health #3*|12 unmatched_members_last_24h 3?",_e,RT,vT,CT]}}class UT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UT).fromBinary(t,r)}static fromJson(t,r){return(new UT).fromJson(t,r)}static fromJsonString(t,r){return(new UT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UT,t,r)}static $(){return["ResetTeamInferenceHookBreakerRequest|1 team_id 5"]}}class AT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AT).fromBinary(t,r)}static fromJson(t,r){return(new AT).fromJson(t,r)}static fromJsonString(t,r){return(new AT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AT,t,r)}static $(){return["ResetTeamInferenceHookBreakerResponse|1 config #0",_T]}}class $T extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $T).fromBinary(t,r)}static fromJson(t,r){return(new $T).fromJson(t,r)}static fromJsonString(t,r){return(new $T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($T,t,r)}static $(){return["GetBugbotMergedPrScanSummaryRequest|1 team_id 5"]}}class MT extends T{constructor(t){super(),this.hasScan=!1,this.scannedAtEpochMillis=n.protoInt64.zero,this.windowDays=0,this.prsSampled=0,this.prsWithFindings=0,this.bugsFound=0,this.findings=[],this.totalMergedPrs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MT).fromBinary(t,r)}static fromJson(t,r){return(new MT).fromJson(t,r)}static fromJsonString(t,r){return(new MT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MT,t,r)}static $(){return["GetBugbotMergedPrScanSummaryResponse|1 has_scan 8|2 scanned_at_epoch_millis 3|3 window_days 5|4 prs_sampled 5|5 prs_with_findings 5|6 bugs_found 5|7 findings #0*|8 total_merged_prs 5",OT]}}class OT extends T{constructor(t){super(),this.description="",this.severity="",this.category="",this.repoOwner="",this.repoName="",this.prNumber=0,this.prUrl="",this.file="",this.startLine=0,this.endLine=0,this.codeLines=[],this.installationId="",this.repoNodeId="",this.prMergedAtEpochMillis=n.protoInt64.zero,this.prTitle="",this.diffHunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OT).fromBinary(t,r)}static fromJson(t,r){return(new OT).fromJson(t,r)}static fromJsonString(t,r){return(new OT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OT,t,r)}static $(){return["GetBugbotMergedPrScanSummaryResponse.Finding|1 description 9|2 severity 9|3 category 9|4 repo_owner 9|5 repo_name 9|6 pr_number 5|7 pr_url 9|8 file 9|9 start_line 5|10 end_line 5|11 code_lines 9*|12 installation_id 9|13 repo_node_id 9|14 pr_merged_at_epoch_millis 3|15 pr_title 9|16 diff_hunk 9"]}}class DT extends T{constructor(t){super(),this.content="",this.sortOrder=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DT).fromBinary(t,r)}static fromJson(t,r){return(new DT).fromJson(t,r)}static fromJsonString(t,r){return(new DT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DT,t,r)}static $(){return["BugbotModePrompt|1 content 9|2 sort_order 5"]}}class NT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NT).fromBinary(t,r)}static fromJson(t,r){return(new NT).fromJson(t,r)}static fromJsonString(t,r){return(new NT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NT,t,r)}static $(){return["GetBugbotModeRequest"]}}class GT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GT).fromBinary(t,r)}static fromJson(t,r){return(new GT).fromJson(t,r)}static fromJsonString(t,r){return(new GT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GT,t,r)}static $(){return["GetBugbotModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class LT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LT).fromBinary(t,r)}static fromJson(t,r){return(new LT).fromJson(t,r)}static fromJsonString(t,r){return(new LT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LT,t,r)}static $(){return["UpdateBugbotModeRequest|1 mode #0|2 prompts #1*|4 team_id 5?",we,DT]}}class FT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FT).fromBinary(t,r)}static fromJson(t,r){return(new FT).fromJson(t,r)}static fromJsonString(t,r){return(new FT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FT,t,r)}static $(){return["UpdateBugbotModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class KT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KT).fromBinary(t,r)}static fromJson(t,r){return(new KT).fromJson(t,r)}static fromJsonString(t,r){return(new KT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KT,t,r)}static $(){return["GetBugBotProUserModeRequest"]}}class zT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zT).fromBinary(t,r)}static fromJson(t,r){return(new zT).fromJson(t,r)}static fromJsonString(t,r){return(new zT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zT,t,r)}static $(){return["GetBugBotProUserModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class jT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jT).fromBinary(t,r)}static fromJson(t,r){return(new jT).fromJson(t,r)}static fromJsonString(t,r){return(new jT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jT,t,r)}static $(){return["UpdateBugBotProUserModeRequest|1 mode #0|2 prompts #1*",we,DT]}}class HT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HT).fromBinary(t,r)}static fromJson(t,r){return(new HT).fromJson(t,r)}static fromJsonString(t,r){return(new HT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HT,t,r)}static $(){return["UpdateBugBotProUserModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class WT extends T{constructor(t){super(),this.teamId=0,this.newNumLicenses=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WT).fromBinary(t,r)}static fromJson(t,r){return(new WT).fromJson(t,r)}static fromJsonString(t,r){return(new WT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WT,t,r)}static $(){return["RevokeBugBotLicensesRequest|1 team_id 5|2 new_num_licenses 5"]}}class QT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QT).fromBinary(t,r)}static fromJson(t,r){return(new QT).fromJson(t,r)}static fromJsonString(t,r){return(new QT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QT,t,r)}static $(){return["RevokeBugBotLicensesResponse"]}}class VT extends T{constructor(t){super(),this.teamId=0,this.githubUserNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VT).fromBinary(t,r)}static fromJson(t,r){return(new VT).fromJson(t,r)}static fromJsonString(t,r){return(new VT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VT,t,r)}static $(){return["RevokeUserBugbotLicenseRequest|1 team_id 5|2 github_user_node_id 9"]}}class XT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XT).fromBinary(t,r)}static fromJson(t,r){return(new XT).fromJson(t,r)}static fromJsonString(t,r){return(new XT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XT,t,r)}static $(){return["RevokeUserBugbotLicenseResponse"]}}class YT extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YT).fromBinary(t,r)}static fromJson(t,r){return(new YT).fromJson(t,r)}static fromJsonString(t,r){return(new YT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YT,t,r)}static $(){return["RedeemGiftCodeRequest|1 code 9"]}}class ZT extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZT).fromBinary(t,r)}static fromJson(t,r){return(new ZT).fromJson(t,r)}static fromJsonString(t,r){return(new ZT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZT,t,r)}static $(){return["RedeemGiftCodeResponse|1 success 8|2 error_message 9?|3 credit_cents 5?|4 currency 9?|5 xpass_plan 9?|6 xpass_plan_ends_at_ms 3?|7 credits_expire_at_ms 3?"]}}class tU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tU).fromBinary(t,r)}static fromJson(t,r){return(new tU).fromJson(t,r)}static fromJsonString(t,r){return(new tU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tU,t,r)}static $(){return["GetGiftCodeInfoRequest|1 code 9"]}}class rU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rU).fromBinary(t,r)}static fromJson(t,r){return(new rU).fromJson(t,r)}static fromJsonString(t,r){return(new rU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rU,t,r)}static $(){return["GetGiftCodeInfoResponse|1 xpass_plan 9?|2 xpass_plan_days 5?|3 credit_cents 5?|4 currency 9?|5 credits_expire_after_days 5?"]}}class eU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eU).fromBinary(t,r)}static fromJson(t,r){return(new eU).fromJson(t,r)}static fromJsonString(t,r){return(new eU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eU,t,r)}static $(){return["GetEventCodeInfoRequest|1 code 9"]}}class nU extends T{constructor(t){super(),this.found=!1,this.eventName="",this.creditCents=n.protoInt64.zero,this.claimState=ye.UNSPECIFIED,this.claimStartsAtMs=n.protoInt64.zero,this.claimEndsAtMs=n.protoInt64.zero,this.creditTtlDays=0,this.creditDestination=Se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nU).fromBinary(t,r)}static fromJson(t,r){return(new nU).fromJson(t,r)}static fromJsonString(t,r){return(new nU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nU,t,r)}static $(){return["GetEventCodeInfoResponse|1 found 8|2 event_name 9|3 credit_cents 3|4 claim_state #0|5 claim_starts_at_ms 3|6 claim_ends_at_ms 3|7 credit_ttl_days 5|8 credit_destination #1",ye,Se]}}class sU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sU).fromBinary(t,r)}static fromJson(t,r){return(new sU).fromJson(t,r)}static fromJsonString(t,r){return(new sU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sU,t,r)}static $(){return["RedeemEventCodeRequest|1 code 9"]}}class iU extends T{constructor(t){super(),this.success=!1,this.claimState=ye.UNSPECIFIED,this.alreadyClaimed=!1,this.creditCents=n.protoInt64.zero,this.grantExpiresAtMs=n.protoInt64.zero,this.creditDestination=Se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iU).fromBinary(t,r)}static fromJson(t,r){return(new iU).fromJson(t,r)}static fromJsonString(t,r){return(new iU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iU,t,r)}static $(){return["RedeemEventCodeResponse|1 success 8|2 claim_state #0|3 already_claimed 8|4 credit_cents 3|5 grant_expires_at_ms 3|6 credit_destination #1",ye,Se]}}class oU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oU).fromBinary(t,r)}static fromJson(t,r){return(new oU).fromJson(t,r)}static fromJsonString(t,r){return(new oU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oU,t,r)}static $(){return["GetActiveOffboardingBannerRequest|1 team_id 5?"]}}class aU extends T{constructor(t){super(),this.hasBanner=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aU).fromBinary(t,r)}static fromJson(t,r){return(new aU).fromJson(t,r)}static fromJsonString(t,r){return(new aU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aU,t,r)}static $(){return["GetActiveOffboardingBannerResponse|1 has_banner 8|2 banner #0?",uU]}}class uU extends T{constructor(t){super(),this.id="",this.severity="",this.messageKey="",this.dismissible=!1,this.flowType="",this.phaseId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uU).fromBinary(t,r)}static fromJson(t,r){return(new uU).fromJson(t,r)}static fromJsonString(t,r){return(new uU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uU,t,r)}static $(){return["OffboardingBanner|1 id 9|2 severity 9|3 message_key 9|4 countdown_date_epoch_millis 3?|5 dismissible 8|6 flow_type 9|7 phase_id 9|8 action_url 9?"]}}class cU extends T{constructor(t){super(),this.action="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cU).fromBinary(t,r)}static fromJson(t,r){return(new cU).fromJson(t,r)}static fromJsonString(t,r){return(new cU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cU,t,r)}static $(){return["ClientActionRequest|1 action 9|2 args 9,9"]}}class lU extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lU).fromBinary(t,r)}static fromJson(t,r){return(new lU).fromJson(t,r)}static fromJsonString(t,r){return(new lU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lU,t,r)}static $(){return["ClientActionResponse|1 success 8|2 error_message 9?|3 info_message 9?|4 open_url 9?|5 confirmation #0?",mU]}}class mU extends T{constructor(t){super(),this.title="",this.message="",this.confirmLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mU).fromBinary(t,r)}static fromJson(t,r){return(new mU).fromJson(t,r)}static fromJsonString(t,r){return(new mU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mU,t,r)}static $(){return["ClientActionConfirmation|1 title 9|2 message 9|3 confirm_label 9|4 action #0",o.bV]}}class fU extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fU).fromBinary(t,r)}static fromJson(t,r){return(new fU).fromJson(t,r)}static fromJsonString(t,r){return(new fU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fU,t,r)}static $(){return["Rule|1 id 9|2 name 9|3 content 9|6 globs 9*|4 is_active 8|5 is_required 8|7 agent_type #0",qe]}}class dU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dU).fromBinary(t,r)}static fromJson(t,r){return(new dU).fromJson(t,r)}static fromJsonString(t,r){return(new dU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dU,t,r)}static $(){return["GetTeamRulesRequest|1 active_only 8?|2 team_id 5?|3 include_member_group_rules 8?"]}}class pU extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pU).fromBinary(t,r)}static fromJson(t,r){return(new pU).fromJson(t,r)}static fromJsonString(t,r){return(new pU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pU,t,r)}static $(){return["GetTeamRulesResponse|1 rules #0*",fU]}}class hU extends T{constructor(t){super(),this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hU).fromBinary(t,r)}static fromJson(t,r){return(new hU).fromJson(t,r)}static fromJsonString(t,r){return(new hU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hU,t,r)}static $(){return["CreateTeamRuleRequest|1 name 9|2 content 9|5 globs 9*|3 is_active 8|4 is_required 8|6 team_id 5?|7 agent_type #0",qe]}}class gU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gU).fromBinary(t,r)}static fromJson(t,r){return(new gU).fromJson(t,r)}static fromJsonString(t,r){return(new gU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gU,t,r)}static $(){return["CreateTeamRuleResponse|1 rule #0",fU]}}class _U extends T{constructor(t){super(),this.ruleId="",this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _U).fromBinary(t,r)}static fromJson(t,r){return(new _U).fromJson(t,r)}static fromJsonString(t,r){return(new _U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_U,t,r)}static $(){return["UpdateTeamRuleRequest|1 rule_id 9|2 name 9?|3 content 9?|6 globs 9*|4 is_active 8?|5 is_required 8?|7 team_id 5?|8 agent_type #0?|9 clear_globs 8?",qe]}}class JU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JU).fromBinary(t,r)}static fromJson(t,r){return(new JU).fromJson(t,r)}static fromJsonString(t,r){return(new JU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JU,t,r)}static $(){return["UpdateTeamRuleResponse|1 rule #0",fU]}}class wU extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wU).fromBinary(t,r)}static fromJson(t,r){return(new wU).fromJson(t,r)}static fromJsonString(t,r){return(new wU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wU,t,r)}static $(){return["DeleteTeamRuleRequest|1 rule_id 9|2 team_id 5?"]}}class yU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yU).fromBinary(t,r)}static fromJson(t,r){return(new yU).fromJson(t,r)}static fromJsonString(t,r){return(new yU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yU,t,r)}static $(){return["DeleteTeamRuleResponse"]}}class SU extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SU).fromBinary(t,r)}static fromJson(t,r){return(new SU).fromJson(t,r)}static fromJsonString(t,r){return(new SU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SU,t,r)}static $(){return["GetTeamGroupRulesRequest|1 team_id 5|2 group_public_id 9|3 active_only 8?"]}}class qU extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qU).fromBinary(t,r)}static fromJson(t,r){return(new qU).fromJson(t,r)}static fromJsonString(t,r){return(new qU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qU,t,r)}static $(){return["GetTeamGroupRulesResponse|1 rules #0*",fU]}}class BU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BU).fromBinary(t,r)}static fromJson(t,r){return(new BU).fromJson(t,r)}static fromJsonString(t,r){return(new BU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BU,t,r)}static $(){return["CreateTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 name 9|4 content 9|5 globs 9*|6 is_active 8|7 is_required 8|8 agent_type #0",qe]}}class IU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IU).fromBinary(t,r)}static fromJson(t,r){return(new IU).fromJson(t,r)}static fromJsonString(t,r){return(new IU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IU,t,r)}static $(){return["CreateTeamGroupRuleResponse|1 rule #0",fU]}}class PU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.ruleId="",this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PU).fromBinary(t,r)}static fromJson(t,r){return(new PU).fromJson(t,r)}static fromJsonString(t,r){return(new PU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PU,t,r)}static $(){return["UpdateTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 rule_id 9|4 name 9?|5 content 9?|6 globs 9*|7 is_active 8?|8 is_required 8?|9 agent_type #0?",qe]}}class bU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bU).fromBinary(t,r)}static fromJson(t,r){return(new bU).fromJson(t,r)}static fromJsonString(t,r){return(new bU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bU,t,r)}static $(){return["UpdateTeamGroupRuleResponse|1 rule #0",fU]}}class RU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RU).fromBinary(t,r)}static fromJson(t,r){return(new RU).fromJson(t,r)}static fromJsonString(t,r){return(new RU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RU,t,r)}static $(){return["DeleteTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 rule_id 9"]}}class vU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vU).fromBinary(t,r)}static fromJson(t,r){return(new vU).fromJson(t,r)}static fromJsonString(t,r){return(new vU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vU,t,r)}static $(){return["DeleteTeamGroupRuleResponse"]}}class xU extends T{constructor(t){super(),this.id=0,this.hookStep="",this.scriptName="",this.operatingSystems=[],this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xU).fromBinary(t,r)}static fromJson(t,r){return(new xU).fromJson(t,r)}static fromJsonString(t,r){return(new xU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xU,t,r)}static $(){return["TeamHook|1 id 5|2 hook_step 9|3 script_name 9|4 operating_systems 9*|5 is_active 8|6 script_content 9?|7 hook_type 9?|8 prompt_content 9?|9 prompt_model 9?"]}}class kU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kU).fromBinary(t,r)}static fromJson(t,r){return(new kU).fromJson(t,r)}static fromJsonString(t,r){return(new kU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kU,t,r)}static $(){return["GetTeamHooksRequest|1 active_only 8?|2 team_id 5?"]}}class EU extends T{constructor(t){super(),this.hooks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EU).fromBinary(t,r)}static fromJson(t,r){return(new EU).fromJson(t,r)}static fromJsonString(t,r){return(new EU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EU,t,r)}static $(){return["GetTeamHooksResponse|1 hooks #0*",xU]}}class CU extends T{constructor(t){super(),this.hookStep="",this.scriptName="",this.operatingSystems=[],this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CU).fromBinary(t,r)}static fromJson(t,r){return(new CU).fromJson(t,r)}static fromJsonString(t,r){return(new CU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CU,t,r)}static $(){return["CreateTeamHookRequest|1 hook_step 9|2 script_name 9|3 operating_systems 9*|4 is_active 8|5 script_content 9?|6 hook_type 9?|7 prompt_content 9?|8 prompt_model 9?|9 team_id 5?"]}}class TU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TU).fromBinary(t,r)}static fromJson(t,r){return(new TU).fromJson(t,r)}static fromJsonString(t,r){return(new TU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TU,t,r)}static $(){return["CreateTeamHookResponse|1 hook #0",xU]}}class UU extends T{constructor(t){super(),this.hookId="",this.operatingSystems=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UU).fromBinary(t,r)}static fromJson(t,r){return(new UU).fromJson(t,r)}static fromJsonString(t,r){return(new UU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UU,t,r)}static $(){return["UpdateTeamHookRequest|1 hook_id 9|2 script_name 9?|3 operating_systems 9*|4 is_active 8?|5 script_content 9?|6 hook_type 9?|7 prompt_content 9?|8 prompt_model 9?|9 team_id 5?|10 clear_prompt_model 8?"]}}class AU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AU).fromBinary(t,r)}static fromJson(t,r){return(new AU).fromJson(t,r)}static fromJsonString(t,r){return(new AU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AU,t,r)}static $(){return["UpdateTeamHookResponse|1 hook #0",xU]}}class $U extends T{constructor(t){super(),this.hookId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $U).fromBinary(t,r)}static fromJson(t,r){return(new $U).fromJson(t,r)}static fromJsonString(t,r){return(new $U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($U,t,r)}static $(){return["DeleteTeamHookRequest|1 hook_id 9|2 team_id 5?"]}}class MU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MU).fromBinary(t,r)}static fromJson(t,r){return(new MU).fromJson(t,r)}static fromJsonString(t,r){return(new MU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MU,t,r)}static $(){return["DeleteTeamHookResponse"]}}class OU extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OU).fromBinary(t,r)}static fromJson(t,r){return(new OU).fromJson(t,r)}static fromJsonString(t,r){return(new OU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OU,t,r)}static $(){return["TeamCommand|1 id 9|2 name 9|3 content 9|4 description 9?|5 is_active 8"]}}class DU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DU).fromBinary(t,r)}static fromJson(t,r){return(new DU).fromJson(t,r)}static fromJsonString(t,r){return(new DU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DU,t,r)}static $(){return["GetTeamCommandsRequest|1 active_only 8?|2 team_id 5?"]}}class NU extends T{constructor(t){super(),this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NU).fromBinary(t,r)}static fromJson(t,r){return(new NU).fromJson(t,r)}static fromJsonString(t,r){return(new NU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NU,t,r)}static $(){return["GetTeamCommandsResponse|1 commands #0*",OU]}}class GU extends T{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GU).fromBinary(t,r)}static fromJson(t,r){return(new GU).fromJson(t,r)}static fromJsonString(t,r){return(new GU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GU,t,r)}static $(){return["CreateTeamCommandRequest|1 name 9|2 content 9|3 description 9?|4 is_active 8?|5 team_id 5?"]}}class LU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LU).fromBinary(t,r)}static fromJson(t,r){return(new LU).fromJson(t,r)}static fromJsonString(t,r){return(new LU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LU,t,r)}static $(){return["CreateTeamCommandResponse|1 command #0",OU]}}class FU extends T{constructor(t){super(),this.commandId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FU).fromBinary(t,r)}static fromJson(t,r){return(new FU).fromJson(t,r)}static fromJsonString(t,r){return(new FU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FU,t,r)}static $(){return["UpdateTeamCommandRequest|1 command_id 9|2 name 9?|3 content 9?|4 description 9?|5 is_active 8?|6 team_id 5?"]}}class KU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KU).fromBinary(t,r)}static fromJson(t,r){return(new KU).fromJson(t,r)}static fromJsonString(t,r){return(new KU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KU,t,r)}static $(){return["UpdateTeamCommandResponse|1 command #0",OU]}}class zU extends T{constructor(t){super(),this.commandId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zU).fromBinary(t,r)}static fromJson(t,r){return(new zU).fromJson(t,r)}static fromJsonString(t,r){return(new zU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zU,t,r)}static $(){return["DeleteTeamCommandRequest|1 command_id 9|2 team_id 5?"]}}class jU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jU).fromBinary(t,r)}static fromJson(t,r){return(new jU).fromJson(t,r)}static fromJsonString(t,r){return(new jU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jU,t,r)}static $(){return["DeleteTeamCommandResponse"]}}class HU extends T{constructor(t){super(),this.name="",this.content="",this.availability=Be.UNSPECIFIED,this.disabledSurfaces=[],this.requiresAllWorkspaceFoldersAreGitRepos=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HU).fromBinary(t,r)}static fromJson(t,r){return(new HU).fromJson(t,r)}static fromJsonString(t,r){return(new HU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HU,t,r)}static $(){return["GlobalCommand|1 name 9|2 content 9|3 description 9?|4 availability #0|5 argument_hint 9?|6 disabled_surfaces #1*|7 requires_all_workspace_folders_are_git_repos 8",Be,Ie]}}class WU extends T{constructor(t){super(),this.surface=Ie.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WU).fromBinary(t,r)}static fromJson(t,r){return(new WU).fromJson(t,r)}static fromJsonString(t,r){return(new WU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WU,t,r)}static $(){return["GetGlobalCommandsRequest|1 surface #0",Ie]}}class QU extends T{constructor(t){super(),this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QU).fromBinary(t,r)}static fromJson(t,r){return(new QU).fromJson(t,r)}static fromJsonString(t,r){return(new QU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QU,t,r)}static $(){return["GetGlobalCommandsResponse|1 commands #0*",HU]}}class VU extends T{constructor(t){super(),this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VU).fromBinary(t,r)}static fromJson(t,r){return(new VU).fromJson(t,r)}static fromJsonString(t,r){return(new VU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VU,t,r)}static $(){return["GetRepoSlashCommandsRequest|1 repo_url 9|2 git_ref 9?|3 include_project_plugin_skills 8?"]}}class XU extends T{constructor(t){super(),this.skillNames=[],this.commandNames=[],this.skills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XU).fromBinary(t,r)}static fromJson(t,r){return(new XU).fromJson(t,r)}static fromJsonString(t,r){return(new XU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XU,t,r)}static $(){return["GetRepoSlashCommandsResponse|3 skill_names 9*|4 command_names 9*|5 skills #0*|6 repo_skills_omission #1?",wO,tA]}}class YU extends T{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YU).fromBinary(t,r)}static fromJson(t,r){return(new YU).fromJson(t,r)}static fromJsonString(t,r){return(new YU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YU,t,r)}static $(){return["GetBackgroundComposerSlashCommandsRequest|1 bc_id 9|2 repo_url 9?|3 git_ref 9?|4 supports_project_repo_commands 8?"]}}class ZU extends T{constructor(t){super(),this.skillNames=[],this.commandNames=[],this.skills=[],this.commands=[],this.projectRepoSkillsOmissions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZU).fromBinary(t,r)}static fromJson(t,r){return(new ZU).fromJson(t,r)}static fromJsonString(t,r){return(new ZU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZU,t,r)}static $(){return["GetBackgroundComposerSlashCommandsResponse|3 skill_names 9*|4 command_names 9*|5 skills #0*|6 commands #1*|8 machine_inventory_pending 8?|9 project_repo_skills_incomplete 8?|10 project_repo_skills_omissions #2*|11 project_repo_descriptions_pending 8?",wO,IO,tA]}}class tA extends T{constructor(t){super(),this.reason=Pe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tA).fromBinary(t,r)}static fromJson(t,r){return(new tA).fromJson(t,r)}static fromJsonString(t,r){return(new tA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tA,t,r)}static $(){return["ProjectRepoSkillsOmission|1 reason #0",Pe]}}class rA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rA).fromBinary(t,r)}static fromJson(t,r){return(new rA).fromJson(t,r)}static fromJsonString(t,r){return(new rA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rA,t,r)}static $(){return["GetCloudAgentPluginsSnapshotRequest|1 use_replica 8?|2 team_id 5?"]}}class eA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eA).fromBinary(t,r)}static fromJson(t,r){return(new eA).fromJson(t,r)}static fromJsonString(t,r){return(new eA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eA,t,r)}static $(){return["CloudAgentPluginSnapshot|1 effective_plugin #0|3 git_ref 9?",kN]}}class nA extends T{constructor(t){super(),this.snapshotToken="",this.plugins=[],this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nA).fromBinary(t,r)}static fromJson(t,r){return(new nA).fromJson(t,r)}static fromJsonString(t,r){return(new nA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nA,t,r)}static $(){return["GetCloudAgentPluginsSnapshotResponse|1 snapshot_token 9|2 plugins #0*|3 warnings 9*",eA]}}class sA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.isActive=!1,this.isRequired=!1,this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sA).fromBinary(t,r)}static fromJson(t,r){return(new sA).fromJson(t,r)}static fromJsonString(t,r){return(new sA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sA,t,r)}static $(){return["BugbotRule|1 id 9|2 name 9|3 content 9|4 is_active 8|5 is_required 8|6 created_at 9|7 updated_at 9"]}}class iA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iA).fromBinary(t,r)}static fromJson(t,r){return(new iA).fromJson(t,r)}static fromJsonString(t,r){return(new iA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iA,t,r)}static $(){return["GetBugbotTeamRulesRequest|1 active_only 8?|2 team_id 5?"]}}class oA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oA).fromBinary(t,r)}static fromJson(t,r){return(new oA).fromJson(t,r)}static fromJsonString(t,r){return(new oA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oA,t,r)}static $(){return["GetBugbotTeamRulesResponse|1 rules #0*",sA]}}class aA extends T{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aA).fromBinary(t,r)}static fromJson(t,r){return(new aA).fromJson(t,r)}static fromJsonString(t,r){return(new aA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aA,t,r)}static $(){return["CreateBugbotTeamRuleRequest|1 name 9|2 content 9|3 is_active 8?|4 is_required 8?|5 team_id 5?"]}}class uA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uA).fromBinary(t,r)}static fromJson(t,r){return(new uA).fromJson(t,r)}static fromJsonString(t,r){return(new uA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uA,t,r)}static $(){return["CreateBugbotTeamRuleResponse|1 rule #0",sA]}}class cA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cA).fromBinary(t,r)}static fromJson(t,r){return(new cA).fromJson(t,r)}static fromJsonString(t,r){return(new cA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cA,t,r)}static $(){return["UpdateBugbotTeamRuleRequest|1 rule_id 9|2 name 9?|3 content 9?|4 is_active 8?|5 is_required 8?|6 team_id 5?"]}}class lA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lA).fromBinary(t,r)}static fromJson(t,r){return(new lA).fromJson(t,r)}static fromJsonString(t,r){return(new lA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lA,t,r)}static $(){return["UpdateBugbotTeamRuleResponse|1 rule #0",sA]}}class mA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mA).fromBinary(t,r)}static fromJson(t,r){return(new mA).fromJson(t,r)}static fromJsonString(t,r){return(new mA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mA,t,r)}static $(){return["DeleteBugbotTeamRuleRequest|1 rule_id 9|2 team_id 5?"]}}class fA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fA).fromBinary(t,r)}static fromJson(t,r){return(new fA).fromJson(t,r)}static fromJsonString(t,r){return(new fA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fA,t,r)}static $(){return["DeleteBugbotTeamRuleResponse"]}}class dA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dA).fromBinary(t,r)}static fromJson(t,r){return(new dA).fromJson(t,r)}static fromJsonString(t,r){return(new dA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dA,t,r)}static $(){return["GetBugbotLearnedRulesRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id_filter 9?"]}}class pA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pA).fromBinary(t,r)}static fromJson(t,r){return(new pA).fromJson(t,r)}static fromJsonString(t,r){return(new pA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pA,t,r)}static $(){return["GetBugbotLearnedRulesResponse|1 rules #0*",hA]}}class hA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.repoNodeId="",this.repoName="",this.status="",this.createdAt="",this.updatedAt="",this.examplePrNumbers=[],this.repoOwner="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hA).fromBinary(t,r)}static fromJson(t,r){return(new hA).fromJson(t,r)}static fromJsonString(t,r){return(new hA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hA,t,r)}static $(){return["BugbotLearnedRule|1 id 9|2 name 9|3 content 9|4 repo_node_id 9|5 repo_name 9|6 status 9|7 created_at 9|8 updated_at 9|9 example_pr_numbers 5*|11 repo_owner 9|12 scoped_paths 9*"]}}class gA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gA).fromBinary(t,r)}static fromJson(t,r){return(new gA).fromJson(t,r)}static fromJsonString(t,r){return(new gA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gA,t,r)}static $(){return["UpdateBugbotLearnedRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?|4 name 9?|5 content 9?|6 status 9?|7 scoped_paths 9*"]}}class _A extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _A).fromBinary(t,r)}static fromJson(t,r){return(new _A).fromJson(t,r)}static fromJsonString(t,r){return(new _A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_A,t,r)}static $(){return["UpdateBugbotLearnedRuleResponse|1 rule #0",hA]}}class JA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JA).fromBinary(t,r)}static fromJson(t,r){return(new JA).fromJson(t,r)}static fromJsonString(t,r){return(new JA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JA,t,r)}static $(){return["DeleteBugbotLearnedRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?"]}}class wA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wA).fromBinary(t,r)}static fromJson(t,r){return(new wA).fromJson(t,r)}static fromJsonString(t,r){return(new wA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wA,t,r)}static $(){return["DeleteBugbotLearnedRuleResponse"]}}class yA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.repoNodeId="",this.repoName="",this.status="",this.createdAt="",this.updatedAt="",this.repoOwner="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yA).fromBinary(t,r)}static fromJson(t,r){return(new yA).fromJson(t,r)}static fromJsonString(t,r){return(new yA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yA,t,r)}static $(){return["BugbotManualRepositoryRule|1 id 9|2 name 9|3 content 9|4 repo_node_id 9|5 repo_name 9|6 status 9|7 created_at 9|8 updated_at 9|9 repo_owner 9|10 scoped_paths 9*"]}}class SA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.name="",this.content="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SA).fromBinary(t,r)}static fromJson(t,r){return(new SA).fromJson(t,r)}static fromJsonString(t,r){return(new SA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SA,t,r)}static $(){return["CreateBugbotManualRepositoryRuleRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id 9|4 name 9|5 content 9|6 status 9?|7 scoped_paths 9*"]}}class qA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qA).fromBinary(t,r)}static fromJson(t,r){return(new qA).fromJson(t,r)}static fromJsonString(t,r){return(new qA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qA,t,r)}static $(){return["CreateBugbotManualRepositoryRuleResponse|1 rule #0",yA]}}class BA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BA).fromBinary(t,r)}static fromJson(t,r){return(new BA).fromJson(t,r)}static fromJsonString(t,r){return(new BA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BA,t,r)}static $(){return["GetBugbotManualRepositoryRulesRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id_filter 9?"]}}class IA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IA).fromBinary(t,r)}static fromJson(t,r){return(new IA).fromJson(t,r)}static fromJsonString(t,r){return(new IA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IA,t,r)}static $(){return["GetBugbotManualRepositoryRulesResponse|1 rules #0*",yA]}}class PA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PA).fromBinary(t,r)}static fromJson(t,r){return(new PA).fromJson(t,r)}static fromJsonString(t,r){return(new PA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PA,t,r)}static $(){return["UpdateBugbotManualRepositoryRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?|4 name 9?|5 content 9?|6 status 9?|7 scoped_paths 9*"]}}class bA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bA).fromBinary(t,r)}static fromJson(t,r){return(new bA).fromJson(t,r)}static fromJsonString(t,r){return(new bA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bA,t,r)}static $(){return["UpdateBugbotManualRepositoryRuleResponse|1 rule #0",yA]}}class RA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RA).fromBinary(t,r)}static fromJson(t,r){return(new RA).fromJson(t,r)}static fromJsonString(t,r){return(new RA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RA,t,r)}static $(){return["DeleteBugbotManualRepositoryRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?"]}}class vA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vA).fromBinary(t,r)}static fromJson(t,r){return(new vA).fromJson(t,r)}static fromJsonString(t,r){return(new vA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vA,t,r)}static $(){return["DeleteBugbotManualRepositoryRuleResponse"]}}class xA extends T{constructor(t){super(),this.teamId=0,this.installationId=n.protoInt64.zero,this.graphiteWorkspaceId="",this.mode=be.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xA).fromBinary(t,r)}static fromJson(t,r){return(new xA).fromJson(t,r)}static fromJsonString(t,r){return(new xA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xA,t,r)}static $(){return["RunDiamondToBugbotMigrationRequest|1 team_id 5|2 installation_id 3|3 ghe_application 9?|4 graphite_workspace_id 9|5 mode #0|6 approved_preview_hash 9?|7 extracted_settings #1",be,n.Struct]}}class kA extends T{constructor(t){super(),this.status="",this.previewHash="",this.previewJson="",this.repositoryRulesJson="",this.applyPlanJson="",this.auditJson="",this.warnings=[],this.blockers=[],this.appliedOperationIds=[],this.skippedOperationIds=[],this.resolvedTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kA).fromBinary(t,r)}static fromJson(t,r){return(new kA).fromJson(t,r)}static fromJsonString(t,r){return(new kA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kA,t,r)}static $(){return["RunDiamondToBugbotMigrationResponse|1 status 9|2 preview_hash 9|3 preview_json 9|4 repository_rules_json 9|5 apply_plan_json 9|6 audit_json 9|7 warnings 9*|8 blockers 9*|9 applied_operation_ids 9*|10 skipped_operation_ids 9*|11 resolved_team_id 5"]}}class EA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EA).fromBinary(t,r)}static fromJson(t,r){return(new EA).fromJson(t,r)}static fromJsonString(t,r){return(new EA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EA,t,r)}static $(){return["GetBugbotRuleAnalyticsRequest|1 date_range_start 9?|2 date_range_end 9?|3 team_id 5?"]}}class CA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CA).fromBinary(t,r)}static fromJson(t,r){return(new CA).fromJson(t,r)}static fromJsonString(t,r){return(new CA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CA,t,r)}static $(){return["GetBugbotRuleAnalyticsResponse|1 rules #0*",TA]}}class TA extends T{constructor(t){super(),this.ruleId="",this.ruleType="",this.name="",this.content="",this.repositories=[],this.issuesFound=0,this.prsReviewed=0,this.acceptedIssues=0,this.acceptanceRate=0,this.upvoteRate=0,this.downvoteRate=0,this.status="",this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TA).fromBinary(t,r)}static fromJson(t,r){return(new TA).fromJson(t,r)}static fromJsonString(t,r){return(new TA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TA,t,r)}static $(){return["BugbotRuleAnalytics|1 rule_id 9|2 rule_type 9|3 name 9|4 content 9|5 repositories 9*|6 issues_found 5|7 prs_reviewed 5|8 accepted_issues 5|9 acceptance_rate 1|10 upvote_rate 1|11 downvote_rate 1|12 status 9|13 created_at 9"]}}class UA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UA).fromBinary(t,r)}static fromJson(t,r){return(new UA).fromJson(t,r)}static fromJsonString(t,r){return(new UA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UA,t,r)}static $(){return["GetBugbotRuleByIdRequest|1 rule_id 9|2 team_id 5?"]}}class AA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AA).fromBinary(t,r)}static fromJson(t,r){return(new AA).fromJson(t,r)}static fromJsonString(t,r){return(new AA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AA,t,r)}static $(){return["GetBugbotRuleByIdResponse|1 team_rule #0?|2 learned_rule #1?|3 analytics #2|4 manual_rule #3?",sA,hA,TA,yA]}}class $A extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $A).fromBinary(t,r)}static fromJson(t,r){return(new $A).fromJson(t,r)}static fromJsonString(t,r){return(new $A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($A,t,r)}static $(){return["SharedConversationCreator|1 user_id 5?|2 first_name 9?"]}}class MA extends T{constructor(t){super(),this.id="",this.title="",this.visibility=Re.UNSPECIFIED,this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MA).fromBinary(t,r)}static fromJson(t,r){return(new MA).fromJson(t,r)}static fromJsonString(t,r){return(new MA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MA,t,r)}static $(){return["SharedConversationMetadata|1 id 9|2 title 9|3 visibility #0|4 created_at 9|5 creator #1|6 conversation_id 9?",Re,$A]}}class OA extends T{constructor(t){super(),this.planId="",this.title="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OA).fromBinary(t,r)}static fromJson(t,r){return(new OA).fromJson(t,r)}static fromJsonString(t,r){return(new OA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OA,t,r)}static $(){return["SharedConversationLatestPlan|1 plan_id 9|2 title 9|3 content 9"]}}class DA extends T{constructor(t){super(),this.userId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DA).fromBinary(t,r)}static fromJson(t,r){return(new DA).fromJson(t,r)}static fromJsonString(t,r){return(new DA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DA,t,r)}static $(){return["SharedCanvasCreator|1 user_id 9|2 first_name 9?"]}}class NA extends T{constructor(t){super(),this.id="",this.title="",this.visibility=ve.UNSPECIFIED,this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NA).fromBinary(t,r)}static fromJson(t,r){return(new NA).fromJson(t,r)}static fromJsonString(t,r){return(new NA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NA,t,r)}static $(){return["SharedCanvasMetadata|1 id 9|2 title 9|3 visibility #0|4 created_at 9|5 creator #1|7 updated_at 9",ve,DA]}}class GA extends T{constructor(t){super(),this.title="",this.visibility=ve.UNSPECIFIED,this.appJs=new Uint8Array(0),this.dataJson=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GA).fromBinary(t,r)}static fromJson(t,r){return(new GA).fromJson(t,r)}static fromJsonString(t,r){return(new GA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GA,t,r)}static $(){return["ShareCanvasRequest|1 title 9|2 visibility #0|3 app_js 12|4 data_json 12|6 canvas_key 9?",ve]}}class LA extends T{constructor(t){super(),this.shareId="",this.shareUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LA).fromBinary(t,r)}static fromJson(t,r){return(new LA).fromJson(t,r)}static fromJsonString(t,r){return(new LA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LA,t,r)}static $(){return["ShareCanvasResponse|1 share_id 9|2 share_url 9"]}}class FA extends T{constructor(t){super(),this.shareId="",this.metadataOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FA).fromBinary(t,r)}static fromJson(t,r){return(new FA).fromJson(t,r)}static fromJsonString(t,r){return(new FA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FA,t,r)}static $(){return["GetSharedCanvasRequest|1 share_id 9|2 metadata_only 8"]}}class KA extends T{constructor(t){super(),this.appJs=new Uint8Array(0),this.dataJson=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KA).fromBinary(t,r)}static fromJson(t,r){return(new KA).fromJson(t,r)}static fromJsonString(t,r){return(new KA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KA,t,r)}static $(){return["GetSharedCanvasResponse|1 metadata #0|2 app_js 12|3 data_json 12",NA]}}class zA extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zA).fromBinary(t,r)}static fromJson(t,r){return(new zA).fromJson(t,r)}static fromJsonString(t,r){return(new zA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zA,t,r)}static $(){return["GetPublicSharedCanvasRequest|1 share_id 9"]}}class jA extends T{constructor(t){super(),this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jA).fromBinary(t,r)}static fromJson(t,r){return(new jA).fromJson(t,r)}static fromJsonString(t,r){return(new jA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jA,t,r)}static $(){return["PublicSharedCanvasPreview|1 title 9"]}}class HA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HA).fromBinary(t,r)}static fromJson(t,r){return(new HA).fromJson(t,r)}static fromJsonString(t,r){return(new HA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HA,t,r)}static $(){return["GetPublicSharedCanvasResponse|1 preview #0",jA]}}class WA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WA).fromBinary(t,r)}static fromJson(t,r){return(new WA).fromJson(t,r)}static fromJsonString(t,r){return(new WA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WA,t,r)}static $(){return["ListSharedCanvasesRequest|1 limit 13?|2 created_before 9?|3 creator_id 9?|4 team_id 9?|5 created_before_id 9?"]}}class QA extends T{constructor(t){super(),this.canvases=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QA).fromBinary(t,r)}static fromJson(t,r){return(new QA).fromJson(t,r)}static fromJsonString(t,r){return(new QA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QA,t,r)}static $(){return["ListSharedCanvasesResponse|1 canvases #0*|2 has_more 8",NA]}}class VA extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VA).fromBinary(t,r)}static fromJson(t,r){return(new VA).fromJson(t,r)}static fromJsonString(t,r){return(new VA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VA,t,r)}static $(){return["DeleteSharedCanvasRequest|1 share_id 9"]}}class XA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XA).fromBinary(t,r)}static fromJson(t,r){return(new XA).fromJson(t,r)}static fromJsonString(t,r){return(new XA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XA,t,r)}static $(){return["DeleteSharedCanvasResponse"]}}class YA extends T{constructor(t){super(),this.canvasKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YA).fromBinary(t,r)}static fromJson(t,r){return(new YA).fromJson(t,r)}static fromJsonString(t,r){return(new YA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YA,t,r)}static $(){return["LookupSharedCanvasByKeyRequest|1 canvas_key 9"]}}class ZA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZA).fromBinary(t,r)}static fromJson(t,r){return(new ZA).fromJson(t,r)}static fromJsonString(t,r){return(new ZA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZA,t,r)}static $(){return["LookupSharedCanvasByKeyResponse|1 share_id 9?|2 visibility #0?|3 share_url 9?|4 updated_at 9?",ve]}}class t$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.createdAt="",this.updatedAt="",this.grokBotContributorAgentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new t$).fromBinary(t,r)}static fromJson(t,r){return(new t$).fromJson(t,r)}static fromJsonString(t,r){return(new t$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(t$,t,r)}static $(){return["CloudCanvasMetadata|1 store_id 9|2 canvas_id 9|3 title 9?|4 created_at 9|5 updated_at 9|6 visibility #0?|7 can_share_to_team 8?|15 team_share_requires_access_list 8?|8 page_url 9?|9 page_slug 9?|10 can_share_public 8?|11 brand #1?|12 team_share_blocked_by_admin 8?|13 public_share_withheld_for_enterprise 8?|14 can_rename_page 8?|17 grok_bot_contributor_agent_ids 9*|18 project_share #2?",ke,xe,r$]}}class r$ extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new r$).fromBinary(t,r)}static fromJson(t,r){return(new r$).fromJson(t,r)}static fromJsonString(t,r){return(new r$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(r$,t,r)}static $(){return["CanvasProjectShare|1 name 9"]}}class e$ extends T{constructor(t){super(),this.pageSize=0,this.pageToken="",this.sharedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new e$).fromBinary(t,r)}static fromJson(t,r){return(new e$).fromJson(t,r)}static fromJsonString(t,r){return(new e$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(e$,t,r)}static $(){return["ListUserCanvasesRequest|1 page_size 5|2 page_token 9|3 shared_only 8"]}}class n$ extends T{constructor(t){super(),this.canvases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new n$).fromBinary(t,r)}static fromJson(t,r){return(new n$).fromJson(t,r)}static fromJsonString(t,r){return(new n$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(n$,t,r)}static $(){return["ListUserCanvasesResponse|1 store_id 9?|2 canvases #0*|3 next_page_token 9?",t$]}}class s$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new s$).fromBinary(t,r)}static fromJson(t,r){return(new s$).fromJson(t,r)}static fromJsonString(t,r){return(new s$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(s$,t,r)}static $(){return["GetCanvasMetadataRequest|1 store_id 9|2 canvas_id 9"]}}class i$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new i$).fromBinary(t,r)}static fromJson(t,r){return(new i$).fromJson(t,r)}static fromJsonString(t,r){return(new i$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(i$,t,r)}static $(){return["GetCanvasMetadataResponse|1 metadata #0",t$]}}class o$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o$).fromBinary(t,r)}static fromJson(t,r){return(new o$).fromJson(t,r)}static fromJsonString(t,r){return(new o$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o$,t,r)}static $(){return["GetCanvasPageBrandRequest|1 store_id 9|2 canvas_id 9"]}}class a$ extends T{constructor(t){super(),this.brand=xe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a$).fromBinary(t,r)}static fromJson(t,r){return(new a$).fromJson(t,r)}static fromJsonString(t,r){return(new a$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a$,t,r)}static $(){return["GetCanvasPageBrandResponse|1 brand #0",xe]}}class u$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u$).fromBinary(t,r)}static fromJson(t,r){return(new u$).fromJson(t,r)}static fromJsonString(t,r){return(new u$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u$,t,r)}static $(){return["GetCanvasPayloadRequest|1 store_id 9|2 canvas_id 9"]}}class c$ extends T{constructor(t){super(),this.name="",this.url="",this.expiresAtMs=n.protoInt64.zero,this.contentType="",this.sizeBytes=n.protoInt64.zero,this.expiresInMs=n.protoInt64.zero,this.width=0,this.height=0,this.placeholder="",this.etag="",this.previews=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c$).fromBinary(t,r)}static fromJson(t,r){return(new c$).fromJson(t,r)}static fromJsonString(t,r){return(new c$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c$,t,r)}static $(){return["CanvasPayloadAssetUrl|1 name 9|2 url 9|3 expires_at_ms 3|4 content_type 9|5 size_bytes 3|6 expires_in_ms 3|7 width 5|8 height 5|9 placeholder 9|10 etag 9|11 previews #0*",k]}}class l$ extends T{constructor(t){super(),this.renderBundleGzip=new Uint8Array(0),this.assets=[],this.visualizationRuntimes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l$).fromBinary(t,r)}static fromJson(t,r){return(new l$).fromJson(t,r)}static fromJsonString(t,r){return(new l$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l$,t,r)}static $(){return["GetCanvasPayloadResponse|1 metadata #0|2 render_bundle_gzip 12|3 data_json 12?|4 assets #1*|5 visualization_runtimes #2*",t$,c$,w]}}class m$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.sourceIds=[],this.now=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m$).fromBinary(t,r)}static fromJson(t,r){return(new m$).fromJson(t,r)}static fromJsonString(t,r){return(new m$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m$,t,r)}static $(){return["RefreshCanvasSourcesRequest|1 store_id 9|2 canvas_id 9|3 source_ids 9*|4 now 8"]}}class f$ extends T{constructor(t){super(),this.sourcesJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f$).fromBinary(t,r)}static fromJson(t,r){return(new f$).fromJson(t,r)}static fromJsonString(t,r){return(new f$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f$,t,r)}static $(){return["RefreshCanvasSourcesResponse|1 sources_json 9"]}}class d$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.connector="",this.tool="",this.slotId="",this.slotValueJson="",this.agentId="",this.pressId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d$).fromBinary(t,r)}static fromJson(t,r){return(new d$).fromJson(t,r)}static fromJsonString(t,r){return(new d$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d$,t,r)}static $(){return["RunCanvasConnectorActionRequest|1 store_id 9|2 canvas_id 9|3 connector 9|4 tool 9|5 args #0|6 slot_id 9|7 slot_value_json 9|8 agent_id 9|9 press_id 9",n.Struct]}}class p$ extends T{constructor(t){super(),this.outcome=h$.UNSPECIFIED,this.detail="",this.asOf="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p$).fromBinary(t,r)}static fromJson(t,r){return(new p$).fromJson(t,r)}static fromJsonString(t,r){return(new p$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p$,t,r)}static $(){return["RunCanvasConnectorActionResponse|1 outcome #0|2 detail 9|3 as_of 9",h$]}}var h$=(0,a.QT)(n.proto3,C,"RunCanvasConnectorActionResponse.Outcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"SENT_NOT_RECORDED"],[3,"FAILED"],[4,"NOT_CONNECTED"],[5,"REFUSED"],[6,"UNCONFIRMED"]],1);class g$ extends T{constructor(t){super(),this.storeId="",this.documentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g$).fromBinary(t,r)}static fromJson(t,r){return(new g$).fromJson(t,r)}static fromJsonString(t,r){return(new g$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g$,t,r)}static $(){return["GetDocumentPayloadRequest|1 store_id 9|2 document_id 9"]}}class _$ extends T{constructor(t){super(),this.name="",this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _$).fromBinary(t,r)}static fromJson(t,r){return(new _$).fromJson(t,r)}static fromJsonString(t,r){return(new _$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_$,t,r)}static $(){return["DocumentPayloadAssetUrl|1 name 9|2 url 9|3 expires_at_ms 3"]}}class J$ extends T{constructor(t){super(),this.content="",this.assets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J$).fromBinary(t,r)}static fromJson(t,r){return(new J$).fromJson(t,r)}static fromJsonString(t,r){return(new J$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J$,t,r)}static $(){return["GetDocumentPayloadResponse|1 content 9|2 assets #0*",_$]}}class w$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.visibility=ke.UNSPECIFIED,this.principals=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w$).fromBinary(t,r)}static fromJson(t,r){return(new w$).fromJson(t,r)}static fromJsonString(t,r){return(new w$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w$,t,r)}static $(){return["SetCanvasVisibilityRequest|1 store_id 9|2 canvas_id 9|3 visibility #0|4 open_to_team 8?|5 principals #1*",ke,S$]}}class y$ extends T{constructor(t){super(),this.visibility=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y$).fromBinary(t,r)}static fromJson(t,r){return(new y$).fromJson(t,r)}static fromJsonString(t,r){return(new y$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y$,t,r)}static $(){return["SetCanvasVisibilityResponse|1 visibility #0|2 page_url 9?|3 page_slug 9?",ke]}}class S$ extends T{constructor(t){super(),this.principal={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S$).fromBinary(t,r)}static fromJson(t,r){return(new S$).fromJson(t,r)}static fromJsonString(t,r){return(new S$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S$,t,r)}static $(){return["CanvasAccessPrincipal|1 user_id 5 principal|2 group_id 3 principal|3 team_id 5 principal"]}}class q$ extends T{constructor(t){super(),this.principals=[],this.openToTeam=!1,this.expectedStateToken="",this.owningTeamId=0,this.openToOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q$).fromBinary(t,r)}static fromJson(t,r){return(new q$).fromJson(t,r)}static fromJsonString(t,r){return(new q$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q$,t,r)}static $(){return["CanvasShareAccessState|1 principals #0*|2 open_to_team 8|3 expected_state_token 9|4 owning_team_id 5|5 open_to_organization 8|6 organization_audience #1?",S$,B$]}}class B$ extends T{constructor(t){super(),this.label="",this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B$).fromBinary(t,r)}static fromJson(t,r){return(new B$).fromJson(t,r)}static fromJsonString(t,r){return(new B$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B$,t,r)}static $(){return["CanvasShareOrganizationAudience|1 label 9|2 teams #0*",I$]}}class I$ extends T{constructor(t){super(),this.teamId=0,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I$).fromBinary(t,r)}static fromJson(t,r){return(new I$).fromJson(t,r)}static fromJsonString(t,r){return(new I$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I$,t,r)}static $(){return["CanvasShareAudienceTeam|1 team_id 5|2 name 9"]}}class P$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P$).fromBinary(t,r)}static fromJson(t,r){return(new P$).fromJson(t,r)}static fromJsonString(t,r){return(new P$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P$,t,r)}static $(){return["GetCanvasShareAccessRequest|1 store_id 9|2 canvas_id 9"]}}class b$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b$).fromBinary(t,r)}static fromJson(t,r){return(new b$).fromJson(t,r)}static fromJsonString(t,r){return(new b$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b$,t,r)}static $(){return["GetCanvasShareAccessResponse|1 state #0",q$]}}class R$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.principals=[],this.expectedStateToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R$).fromBinary(t,r)}static fromJson(t,r){return(new R$).fromJson(t,r)}static fromJsonString(t,r){return(new R$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R$,t,r)}static $(){return["UpdateCanvasShareAccessRequest|1 store_id 9|2 canvas_id 9|3 principals #0*|4 expected_state_token 9|5 open_to_team 8?|6 open_to_organization 8?",S$]}}class v$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v$).fromBinary(t,r)}static fromJson(t,r){return(new v$).fromJson(t,r)}static fromJsonString(t,r){return(new v$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v$,t,r)}static $(){return["UpdateCanvasShareAccessResponse|1 state #0",q$]}}class x$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x$).fromBinary(t,r)}static fromJson(t,r){return(new x$).fromJson(t,r)}static fromJsonString(t,r){return(new x$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x$,t,r)}static $(){return["DeleteCanvasRequest|1 store_id 9|2 canvas_id 9"]}}class k$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k$).fromBinary(t,r)}static fromJson(t,r){return(new k$).fromJson(t,r)}static fromJsonString(t,r){return(new k$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k$,t,r)}static $(){return["DeleteCanvasResponse"]}}class E$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E$).fromBinary(t,r)}static fromJson(t,r){return(new E$).fromJson(t,r)}static fromJsonString(t,r){return(new E$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E$,t,r)}static $(){return["RenameCanvasRequest|1 store_id 9|2 canvas_id 9|3 title 9"]}}class C$ extends T{constructor(t){super(),this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C$).fromBinary(t,r)}static fromJson(t,r){return(new C$).fromJson(t,r)}static fromJsonString(t,r){return(new C$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C$,t,r)}static $(){return["RenameCanvasResponse|1 title 9"]}}class T$ extends T{constructor(t){super(),this.conversationId="",this.title="",this.visibility=Re.UNSPECIFIED,this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T$).fromBinary(t,r)}static fromJson(t,r){return(new T$).fromJson(t,r)}static fromJsonString(t,r){return(new T$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T$,t,r)}static $(){return["ShareConversationRequest|1 conversation_id 9|2 title 9|3 visibility #0|4 messages #1*|5 latest_plan #2?",Re,_.hS,OA]}}class U$ extends T{constructor(t){super(),this.shareId="",this.shareUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U$).fromBinary(t,r)}static fromJson(t,r){return(new U$).fromJson(t,r)}static fromJsonString(t,r){return(new U$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U$,t,r)}static $(){return["ShareConversationResponse|1 share_id 9|2 share_url 9|3 redactions 5?"]}}class A$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A$).fromBinary(t,r)}static fromJson(t,r){return(new A$).fromJson(t,r)}static fromJsonString(t,r){return(new A$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A$,t,r)}static $(){return["GetSharedConversationRequest|1 share_id 9"]}}class $$ extends T{constructor(t){super(),this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $$).fromBinary(t,r)}static fromJson(t,r){return(new $$).fromJson(t,r)}static fromJsonString(t,r){return(new $$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($$,t,r)}static $(){return["GetSharedConversationResponse|1 metadata #0|2 messages #1*|3 latest_plan #2?",MA,_.hS,OA]}}class M$ extends T{constructor(t){super(),this.visibilities=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M$).fromBinary(t,r)}static fromJson(t,r){return(new M$).fromJson(t,r)}static fromJsonString(t,r){return(new M$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M$,t,r)}static $(){return["ListSharedConversationsRequest|1 visibility #0?|2 creator_id 5?|3 created_before 9?|4 visibilities #0*|5 team_id 5?|6 conversation_id 9?|7 created_before_id 9?",Re]}}class O$ extends T{constructor(t){super(),this.shares=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O$).fromBinary(t,r)}static fromJson(t,r){return(new O$).fromJson(t,r)}static fromJsonString(t,r){return(new O$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O$,t,r)}static $(){return["ListSharedConversationsResponse|1 shares #0*|2 has_more 8",MA]}}class D$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D$).fromBinary(t,r)}static fromJson(t,r){return(new D$).fromJson(t,r)}static fromJsonString(t,r){return(new D$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D$,t,r)}static $(){return["DeleteSharedConversationRequest|1 share_id 9"]}}class N$ extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N$).fromBinary(t,r)}static fromJson(t,r){return(new N$).fromJson(t,r)}static fromJsonString(t,r){return(new N$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N$,t,r)}static $(){return["DeleteSharedConversationResponse|1 success 8"]}}class G$ extends T{constructor(t){super(),this.shareId="",this.visibility=Re.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G$).fromBinary(t,r)}static fromJson(t,r){return(new G$).fromJson(t,r)}static fromJsonString(t,r){return(new G$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G$,t,r)}static $(){return["UpdateSharedConversationVisibilityRequest|1 share_id 9|2 visibility #0",Re]}}class L$ extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L$).fromBinary(t,r)}static fromJson(t,r){return(new L$).fromJson(t,r)}static fromJsonString(t,r){return(new L$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L$,t,r)}static $(){return["UpdateSharedConversationVisibilityResponse|1 success 8"]}}class F$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F$).fromBinary(t,r)}static fromJson(t,r){return(new F$).fromJson(t,r)}static fromJsonString(t,r){return(new F$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F$,t,r)}static $(){return["GetPublicSharedConversationRequest|1 share_id 9"]}}class K$ extends T{constructor(t){super(),this.messages=[],this.allowIndexing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K$).fromBinary(t,r)}static fromJson(t,r){return(new K$).fromJson(t,r)}static fromJsonString(t,r){return(new K$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K$,t,r)}static $(){return["GetPublicSharedConversationResponse|1 metadata #0|2 messages #1*|3 allow_indexing 8|4 latest_plan #2?",MA,_.hS,OA]}}class z$ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z$).fromBinary(t,r)}static fromJson(t,r){return(new z$).fromJson(t,r)}static fromJsonString(t,r){return(new z$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z$,t,r)}static $(){return["GetTeamSharedConversationSettingsRequest|1 team_id 5"]}}class j$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j$).fromBinary(t,r)}static fromJson(t,r){return(new j$).fromJson(t,r)}static fromJsonString(t,r){return(new j$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j$,t,r)}static $(){return["GetTeamSharedConversationSettingsResponse|1 settings #0",$J]}}class H$ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H$).fromBinary(t,r)}static fromJson(t,r){return(new H$).fromJson(t,r)}static fromJsonString(t,r){return(new H$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H$,t,r)}static $(){return["UpdateTeamSharedConversationSettingsRequest|1 team_id 5|2 settings #0",$J]}}class W$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W$).fromBinary(t,r)}static fromJson(t,r){return(new W$).fromJson(t,r)}static fromJsonString(t,r){return(new W$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W$,t,r)}static $(){return["UpdateTeamSharedConversationSettingsResponse"]}}class Q$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q$).fromBinary(t,r)}static fromJson(t,r){return(new Q$).fromJson(t,r)}static fromJsonString(t,r){return(new Q$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q$,t,r)}static $(){return["SmartAutoSettings|1 enabled 8?|2 optimize_for #0?|3 show_routed_model 8?|4 router_model_grants #1?|5 router_model_pool #2?",Y$,V$,X$]}}class V$ extends T{constructor(t){super(),this.mcids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V$).fromBinary(t,r)}static fromJson(t,r){return(new V$).fromJson(t,r)}static fromJsonString(t,r){return(new V$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V$,t,r)}static $(){return["RouterModelGrants|1 mcids 9*"]}}class X$ extends T{constructor(t){super(),this.type="",this.list=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X$).fromBinary(t,r)}static fromJson(t,r){return(new X$).fromJson(t,r)}static fromJsonString(t,r){return(new X$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X$,t,r)}static $(){return["RouterModelPool|1 type 9|2 list 9*"]}}class Y$ extends T{constructor(t){super(),this.allowedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y$).fromBinary(t,r)}static fromJson(t,r){return(new Y$).fromJson(t,r)}static fromJsonString(t,r){return(new Y$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y$,t,r)}static $(){return["SmartAutoOptimizeForSettings|1 allowed_values 9*"]}}class Z$ extends T{constructor(t){super(),this.model=Ee.UNSPECIFIED,this.mode=Ce.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z$).fromBinary(t,r)}static fromJson(t,r){return(new Z$).fromJson(t,r)}static fromJsonString(t,r){return(new Z$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z$,t,r)}static $(){return["ImposedModelPolicy|1 model #0|2 mode #1",Ee,Ce]}}class tM extends T{constructor(t){super(),this.modelId="",this.displayName="",this.severity=Te.UNSPECIFIED,this.blocked=!1,this.mcid="",this.routerGranted=!1,this.routerNickname="",this.routerProvider="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tM).fromBinary(t,r)}static fromJson(t,r){return(new tM).fromJson(t,r)}static fromJsonString(t,r){return(new tM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tM,t,r)}static $(){return["SmartAutoRequiredModel|1 model_id 9|2 display_name 9|3 severity #0|4 blocked 8|5 mcid 9|6 router_granted 8|7 router_nickname 9|8 router_provider 9",Te]}}class rM extends T{constructor(t){super(),this.teamNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rM).fromBinary(t,r)}static fromJson(t,r){return(new rM).fromJson(t,r)}static fromJsonString(t,r){return(new rM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rM,t,r)}static $(){return["SmartAutoMemberTeamConflict|1 model #0|2 team_names 9*",tM]}}class eM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eM).fromBinary(t,r)}static fromJson(t,r){return(new eM).fromJson(t,r)}static fromJsonString(t,r){return(new eM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eM,t,r)}static $(){return["GetTeamSmartAutoSettingsRequest|1 team_id 5"]}}class nM extends T{constructor(t){super(),this.canEnable=!1,this.requiredModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nM).fromBinary(t,r)}static fromJson(t,r){return(new nM).fromJson(t,r)}static fromJsonString(t,r){return(new nM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nM,t,r)}static $(){return["GetTeamSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 required_models #1*|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?|7 imposed_model_policy #2",Q$,tM,Z$]}}class sM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sM).fromBinary(t,r)}static fromJson(t,r){return(new sM).fromJson(t,r)}static fromJsonString(t,r){return(new sM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sM,t,r)}static $(){return["UpdateTeamSmartAutoSettingsRequest|1 team_id 5|2 settings #0|3 new_chat_nudge_all_to_smart_auto 8?|4 models_auto_only 8?|5 new_chat_nudge_all_to_smart_auto_optimize_for 9?|6 imposed_model_policy #1",Q$,Z$]}}class iM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iM).fromBinary(t,r)}static fromJson(t,r){return(new iM).fromJson(t,r)}static fromJsonString(t,r){return(new iM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iM,t,r)}static $(){return["UpdateTeamSmartAutoSettingsResponse"]}}class oM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oM).fromBinary(t,r)}static fromJson(t,r){return(new oM).fromJson(t,r)}static fromJsonString(t,r){return(new oM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oM,t,r)}static $(){return["GetTeamPromptCachingSettingsRequest|1 team_id 5"]}}class aM extends T{constructor(t){super(),this.claudeCacheTtl=Ue.UNSPECIFIED,this.canConfigure=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aM).fromBinary(t,r)}static fromJson(t,r){return(new aM).fromJson(t,r)}static fromJsonString(t,r){return(new aM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aM,t,r)}static $(){return["GetTeamPromptCachingSettingsResponse|1 claude_cache_ttl #0|2 can_configure 8",Ue]}}class uM extends T{constructor(t){super(),this.teamId=0,this.claudeCacheTtl=Ue.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uM).fromBinary(t,r)}static fromJson(t,r){return(new uM).fromJson(t,r)}static fromJsonString(t,r){return(new uM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uM,t,r)}static $(){return["UpdateTeamPromptCachingSettingsRequest|1 team_id 5|2 claude_cache_ttl #0",Ue]}}class cM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cM).fromBinary(t,r)}static fromJson(t,r){return(new cM).fromJson(t,r)}static fromJsonString(t,r){return(new cM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cM,t,r)}static $(){return["UpdateTeamPromptCachingSettingsResponse"]}}class lM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lM).fromBinary(t,r)}static fromJson(t,r){return(new lM).fromJson(t,r)}static fromJsonString(t,r){return(new lM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lM,t,r)}static $(){return["ResetTeamAgentRunModeToAutoReviewRequest|1 team_id 5"]}}class mM extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mM).fromBinary(t,r)}static fromJson(t,r){return(new mM).fromJson(t,r)}static fromJsonString(t,r){return(new mM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mM,t,r)}static $(){return["ResetTeamAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class fM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fM).fromBinary(t,r)}static fromJson(t,r){return(new fM).fromJson(t,r)}static fromJsonString(t,r){return(new fM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fM,t,r)}static $(){return["GetUserSmartAutoSettingsRequest"]}}class dM extends T{constructor(t){super(),this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dM).fromBinary(t,r)}static fromJson(t,r){return(new dM).fromJson(t,r)}static fromJsonString(t,r){return(new dM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dM,t,r)}static $(){return["GetUserSmartAutoSettingsResponse|1 settings #0|2 can_enable 8",Q$]}}class pM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pM).fromBinary(t,r)}static fromJson(t,r){return(new pM).fromJson(t,r)}static fromJsonString(t,r){return(new pM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pM,t,r)}static $(){return["UpdateUserSmartAutoSettingsRequest|1 settings #0",Q$]}}class hM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hM).fromBinary(t,r)}static fromJson(t,r){return(new hM).fromJson(t,r)}static fromJsonString(t,r){return(new hM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hM,t,r)}static $(){return["UpdateUserSmartAutoSettingsResponse|1 settings #0",Q$]}}class gM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gM).fromBinary(t,r)}static fromJson(t,r){return(new gM).fromJson(t,r)}static fromJsonString(t,r){return(new gM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gM,t,r)}static $(){return["GetTeamSharedCanvasSettingsRequest|1 team_id 5"]}}class _M extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _M).fromBinary(t,r)}static fromJson(t,r){return(new _M).fromJson(t,r)}static fromJsonString(t,r){return(new _M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_M,t,r)}static $(){return["GetTeamSharedCanvasSettingsResponse|1 settings #0",MJ]}}class JM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JM).fromBinary(t,r)}static fromJson(t,r){return(new JM).fromJson(t,r)}static fromJsonString(t,r){return(new JM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JM,t,r)}static $(){return["UpdateTeamSharedCanvasSettingsRequest|1 team_id 5|2 settings #0",MJ]}}class wM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wM).fromBinary(t,r)}static fromJson(t,r){return(new wM).fromJson(t,r)}static fromJsonString(t,r){return(new wM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wM,t,r)}static $(){return["UpdateTeamSharedCanvasSettingsResponse"]}}class yM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yM).fromBinary(t,r)}static fromJson(t,r){return(new yM).fromJson(t,r)}static fromJsonString(t,r){return(new yM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yM,t,r)}static $(){return["GetTeamProjectsSettingsRequest|1 team_id 5"]}}class SM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SM).fromBinary(t,r)}static fromJson(t,r){return(new SM).fromJson(t,r)}static fromJsonString(t,r){return(new SM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SM,t,r)}static $(){return["GetTeamProjectsSettingsResponse|1 settings #0",NJ]}}class qM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qM).fromBinary(t,r)}static fromJson(t,r){return(new qM).fromJson(t,r)}static fromJsonString(t,r){return(new qM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qM,t,r)}static $(){return["UpdateTeamProjectsSettingsRequest|1 team_id 5|2 settings #0",NJ]}}class BM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BM).fromBinary(t,r)}static fromJson(t,r){return(new BM).fromJson(t,r)}static fromJsonString(t,r){return(new BM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BM,t,r)}static $(){return["UpdateTeamProjectsSettingsResponse"]}}class IM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IM).fromBinary(t,r)}static fromJson(t,r){return(new IM).fromJson(t,r)}static fromJsonString(t,r){return(new IM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IM,t,r)}static $(){return["GetTeamAppsSettingsRequest|1 team_id 5"]}}class PM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PM).fromBinary(t,r)}static fromJson(t,r){return(new PM).fromJson(t,r)}static fromJsonString(t,r){return(new PM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PM,t,r)}static $(){return["GetTeamAppsSettingsResponse|1 settings #0|2 terms #1",GJ,bM]}}class bM extends T{constructor(t){super(),this.covered=!1,this.blockedPapered=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bM).fromBinary(t,r)}static fromJson(t,r){return(new bM).fromJson(t,r)}static fromJsonString(t,r){return(new bM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bM,t,r)}static $(){return["TeamAppsTerms|1 covered 8|2 terms_to_accept #0|3 blocked_papered 8",b]}}class RM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RM).fromBinary(t,r)}static fromJson(t,r){return(new RM).fromJson(t,r)}static fromJsonString(t,r){return(new RM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RM,t,r)}static $(){return["UpdateTeamAppsSettingsRequest|1 team_id 5|2 settings #0|3 accepted_terms #1",GJ,R]}}class vM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vM).fromBinary(t,r)}static fromJson(t,r){return(new vM).fromJson(t,r)}static fromJsonString(t,r){return(new vM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vM,t,r)}static $(){return["UpdateTeamAppsSettingsResponse"]}}class xM extends T{constructor(t){super(),this.id="",this.charCount=0,this.sha256Prefix="",this.createdByUserId=0,this.createdByName="",this.createdAtMs=n.protoInt64.zero,this.active=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xM).fromBinary(t,r)}static fromJson(t,r){return(new xM).fromJson(t,r)}static fromJsonString(t,r){return(new xM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xM,t,r)}static $(){return["TeamAppsReviewRulesVersion|1 id 9|2 char_count 5|3 sha256_prefix 9|4 created_by_user_id 5|5 created_by_name 9|6 created_at_ms 3|7 active 8"]}}class kM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kM).fromBinary(t,r)}static fromJson(t,r){return(new kM).fromJson(t,r)}static fromJsonString(t,r){return(new kM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kM,t,r)}static $(){return["GetTeamAppsReviewRulesRequest|1 team_id 5"]}}class EM extends T{constructor(t){super(),this.rules="",this.maxChars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EM).fromBinary(t,r)}static fromJson(t,r){return(new EM).fromJson(t,r)}static fromJsonString(t,r){return(new EM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EM,t,r)}static $(){return["GetTeamAppsReviewRulesResponse|1 active #0?|2 rules 9|3 max_chars 5",xM]}}class CM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CM).fromBinary(t,r)}static fromJson(t,r){return(new CM).fromJson(t,r)}static fromJsonString(t,r){return(new CM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CM,t,r)}static $(){return["ListTeamAppsReviewRulesVersionsRequest|1 team_id 5"]}}class TM extends T{constructor(t){super(),this.versions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TM).fromBinary(t,r)}static fromJson(t,r){return(new TM).fromJson(t,r)}static fromJsonString(t,r){return(new TM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TM,t,r)}static $(){return["ListTeamAppsReviewRulesVersionsResponse|1 versions #0*",xM]}}class UM extends T{constructor(t){super(),this.teamId=0,this.versionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UM).fromBinary(t,r)}static fromJson(t,r){return(new UM).fromJson(t,r)}static fromJsonString(t,r){return(new UM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UM,t,r)}static $(){return["GetTeamAppsReviewRulesVersionRequest|1 team_id 5|2 version_id 9"]}}class AM extends T{constructor(t){super(),this.rules="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AM).fromBinary(t,r)}static fromJson(t,r){return(new AM).fromJson(t,r)}static fromJsonString(t,r){return(new AM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AM,t,r)}static $(){return["GetTeamAppsReviewRulesVersionResponse|1 version #0|2 rules 9",xM]}}class $M extends T{constructor(t){super(),this.teamId=0,this.rules="",this.expectedActiveVersionId="",this.acknowledgedWarnings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $M).fromBinary(t,r)}static fromJson(t,r){return(new $M).fromJson(t,r)}static fromJsonString(t,r){return(new $M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($M,t,r)}static $(){return["SaveTeamAppsReviewRulesRequest|1 team_id 5|2 rules 9|3 expected_active_version_id 9|4 acknowledged_warnings 8"]}}class MM extends T{constructor(t){super(),this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MM).fromBinary(t,r)}static fromJson(t,r){return(new MM).fromJson(t,r)}static fromJsonString(t,r){return(new MM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MM,t,r)}static $(){return["SaveTeamAppsReviewRulesResponse|1 version #0?|2 warnings 9*",xM]}}class OM extends T{constructor(t){super(),this.teamId=0,this.versionId="",this.expectedActiveVersionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OM).fromBinary(t,r)}static fromJson(t,r){return(new OM).fromJson(t,r)}static fromJsonString(t,r){return(new OM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OM,t,r)}static $(){return["ActivateTeamAppsReviewRulesVersionRequest|1 team_id 5|2 version_id 9|3 expected_active_version_id 9"]}}class DM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DM).fromBinary(t,r)}static fromJson(t,r){return(new DM).fromJson(t,r)}static fromJsonString(t,r){return(new DM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DM,t,r)}static $(){return["ActivateTeamAppsReviewRulesVersionResponse|1 active #0?",xM]}}class NM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NM).fromBinary(t,r)}static fromJson(t,r){return(new NM).fromJson(t,r)}static fromJsonString(t,r){return(new NM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NM,t,r)}static $(){return["GetTeamPublicProfileSettingsRequest|1 team_id 5"]}}class GM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GM).fromBinary(t,r)}static fromJson(t,r){return(new GM).fromJson(t,r)}static fromJsonString(t,r){return(new GM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GM,t,r)}static $(){return["GetTeamPublicProfileSettingsResponse|1 settings #0",OJ]}}class LM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LM).fromBinary(t,r)}static fromJson(t,r){return(new LM).fromJson(t,r)}static fromJsonString(t,r){return(new LM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LM,t,r)}static $(){return["UpdateTeamPublicProfileSettingsRequest|1 team_id 5|2 settings #0",OJ]}}class FM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FM).fromBinary(t,r)}static fromJson(t,r){return(new FM).fromJson(t,r)}static fromJsonString(t,r){return(new FM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FM,t,r)}static $(){return["UpdateTeamPublicProfileSettingsResponse"]}}class KM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KM).fromBinary(t,r)}static fromJson(t,r){return(new KM).fromJson(t,r)}static fromJsonString(t,r){return(new KM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KM,t,r)}static $(){return["GetTeamBackgroundAgentSettingsRequest|1 team_id 5"]}}class zM extends T{constructor(t){super(),this.grokBotCustomerHostedAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zM).fromBinary(t,r)}static fromJson(t,r){return(new zM).fromJson(t,r)}static fromJsonString(t,r){return(new zM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zM,t,r)}static $(){return["GetTeamBackgroundAgentSettingsResponse|1 settings #0|2 grok_bot_customer_hosted_available 8|3 cloud_agent_inference_hooks_available 8?|4 personal_machines_allowed 8?",cJ]}}class jM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jM).fromBinary(t,r)}static fromJson(t,r){return(new jM).fromJson(t,r)}static fromJsonString(t,r){return(new jM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jM,t,r)}static $(){return["UpdateTeamBackgroundAgentSettingsRequest|1 team_id 5|2 settings #0",cJ]}}class HM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HM).fromBinary(t,r)}static fromJson(t,r){return(new HM).fromJson(t,r)}static fromJsonString(t,r){return(new HM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HM,t,r)}static $(){return["UpdateTeamBackgroundAgentSettingsResponse"]}}class WM extends T{constructor(t){super(),this.id="",this.teamId=0,this.targetType="",this.targetScope="",this.thresholdCents=0,this.notificationMode="",this.enabled=!1,this.createdAt=n.protoInt64.zero,this.notifyAdminUserIds=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WM).fromBinary(t,r)}static fromJson(t,r){return(new WM).fromJson(t,r)}static fromJsonString(t,r){return(new WM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WM,t,r)}static $(){return["UsageAlert|1 id 9|2 team_id 5|3 target_type 9|4 target_scope 9|5 threshold_cents 5|6 notification_mode 9|7 enabled 8|8 created_at 3|9 notify_all_admins 8?|10 notify_admin_user_ids 5*|11 notify_member 8?|12 group_id 5?|13 group_name 9?|14 threshold_type 9?|15 threshold_bps 5?|16 resource_threshold_id 9?|17 resource_threshold_cents 5?|18 resource_threshold_level 9?|19 notification_channels 9*|20 spend_bucket 9?"]}}class QM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QM).fromBinary(t,r)}static fromJson(t,r){return(new QM).fromJson(t,r)}static fromJsonString(t,r){return(new QM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QM,t,r)}static $(){return["ListUsageAlertsRequest|1 team_id 5"]}}class VM extends T{constructor(t){super(),this.alerts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VM).fromBinary(t,r)}static fromJson(t,r){return(new VM).fromJson(t,r)}static fromJsonString(t,r){return(new VM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VM,t,r)}static $(){return["ListUsageAlertsResponse|1 alerts #0*",WM]}}class XM extends T{constructor(t){super(),this.teamId=0,this.targetType="",this.targetScope="",this.thresholdCents=[],this.notificationMode="",this.notifyAdminUserIds=[],this.thresholdBps=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XM).fromBinary(t,r)}static fromJson(t,r){return(new XM).fromJson(t,r)}static fromJsonString(t,r){return(new XM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XM,t,r)}static $(){return["CreateUsageAlertsRequest|1 team_id 5|2 target_type 9|3 target_scope 9|4 threshold_cents 5*|5 notification_mode 9|6 notify_all_admins 8?|7 notify_admin_user_ids 5*|8 notify_member 8?|9 group_id 5?|10 threshold_type 9?|11 threshold_bps 5*|12 resource_threshold_cents 5?|13 resource_threshold_id 9?|14 resource_threshold_level 9?|15 notification_channels 9*|16 spend_bucket 9?"]}}class YM extends T{constructor(t){super(),this.createdAlerts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YM).fromBinary(t,r)}static fromJson(t,r){return(new YM).fromJson(t,r)}static fromJsonString(t,r){return(new YM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YM,t,r)}static $(){return["CreateUsageAlertsResponse|1 created_alerts #0*",WM]}}class ZM extends T{constructor(t){super(),this.teamId=0,this.alertIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZM).fromBinary(t,r)}static fromJson(t,r){return(new ZM).fromJson(t,r)}static fromJsonString(t,r){return(new ZM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZM,t,r)}static $(){return["DeleteUsageAlertsRequest|1 team_id 5|2 alert_ids 9*"]}}class tO extends T{constructor(t){super(),this.deletedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tO).fromBinary(t,r)}static fromJson(t,r){return(new tO).fromJson(t,r)}static fromJsonString(t,r){return(new tO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tO,t,r)}static $(){return["DeleteUsageAlertsResponse|1 deleted_count 5"]}}class rO extends T{constructor(t){super(),this.teamId=0,this.alertIds=[],this.notificationMode="",this.notifyAdminUserIds=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rO).fromBinary(t,r)}static fromJson(t,r){return(new rO).fromJson(t,r)}static fromJsonString(t,r){return(new rO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rO,t,r)}static $(){return["UpdateUsageAlertsRequest|1 team_id 5|2 alert_ids 9*|3 notification_mode 9|4 notify_all_admins 8?|5 notify_admin_user_ids 5*|6 notify_member 8?|7 notification_channels 9*"]}}class eO extends T{constructor(t){super(),this.updatedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eO).fromBinary(t,r)}static fromJson(t,r){return(new eO).fromJson(t,r)}static fromJsonString(t,r){return(new eO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eO,t,r)}static $(){return["UpdateUsageAlertsResponse|1 updated_count 5"]}}class nO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nO).fromBinary(t,r)}static fromJson(t,r){return(new nO).fromJson(t,r)}static fromJsonString(t,r){return(new nO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nO,t,r)}static $(){return["RequestIndividualLimitsOptOutRequest"]}}class sO extends T{constructor(t){super(),this.teamResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sO).fromBinary(t,r)}static fromJson(t,r){return(new sO).fromJson(t,r)}static fromJsonString(t,r){return(new sO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sO,t,r)}static $(){return["RequestIndividualLimitsOptOutResponse|1 team_results #0*",iO]}}class iO extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.outcome=Ae.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iO).fromBinary(t,r)}static fromJson(t,r){return(new iO).fromJson(t,r)}static fromJsonString(t,r){return(new iO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iO,t,r)}static $(){return["IndividualLimitsOptOutTeamResult|1 team_id 5|2 team_name 9|3 outcome #0",Ae]}}class oO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oO).fromBinary(t,r)}static fromJson(t,r){return(new oO).fromJson(t,r)}static fromJsonString(t,r){return(new oO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oO,t,r)}static $(){return["ListSlackConversationsRequest|1 search 9?|2 include_private 8?|3 skip_cache 8?|4 allow_partial 8?"]}}class aO extends T{constructor(t){super(),this.conversations=[],this.hasSlackAuth=!1,this.isPartial=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aO).fromBinary(t,r)}static fromJson(t,r){return(new aO).fromJson(t,r)}static fromJsonString(t,r){return(new aO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aO,t,r)}static $(){return["ListSlackConversationsResponse|1 conversations #0*|2 has_slack_auth 8|3 is_partial 8",dO]}}class uO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uO).fromBinary(t,r)}static fromJson(t,r){return(new uO).fromJson(t,r)}static fromJsonString(t,r){return(new uO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uO,t,r)}static $(){return["ListMicrosoftTeamsChannelsRequest|1 search 9?"]}}class cO extends T{constructor(t){super(),this.channels=[],this.hasMicrosoftTeamsAuth=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cO).fromBinary(t,r)}static fromJson(t,r){return(new cO).fromJson(t,r)}static fromJsonString(t,r){return(new cO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cO,t,r)}static $(){return["ListMicrosoftTeamsChannelsResponse|1 channels #0*|2 has_microsoft_teams_auth 8",lO]}}class lO extends T{constructor(t){super(),this.tenantId="",this.teamId="",this.teamDisplayName="",this.channelId="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lO).fromBinary(t,r)}static fromJson(t,r){return(new lO).fromJson(t,r)}static fromJsonString(t,r){return(new lO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lO,t,r)}static $(){return["MicrosoftTeamsChannel|1 tenant_id 9|2 team_id 9|3 team_display_name 9|4 channel_id 9|5 display_name 9|6 description 9?"]}}class mO extends T{constructor(t){super(),this.conversationIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mO).fromBinary(t,r)}static fromJson(t,r){return(new mO).fromJson(t,r)}static fromJsonString(t,r){return(new mO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mO,t,r)}static $(){return["GetSlackConversationsByIdsRequest|1 conversation_ids 9*"]}}class fO extends T{constructor(t){super(),this.conversations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fO).fromBinary(t,r)}static fromJson(t,r){return(new fO).fromJson(t,r)}static fromJsonString(t,r){return(new fO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fO,t,r)}static $(){return["GetSlackConversationsByIdsResponse|1 conversations #0*",dO]}}class dO extends T{constructor(t){super(),this.id="",this.name="",this.type=$e.UNSPECIFIED,this.isPrivate=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dO).fromBinary(t,r)}static fromJson(t,r){return(new dO).fromJson(t,r)}static fromJsonString(t,r){return(new dO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dO,t,r)}static $(){return["SlackConversation|1 id 9|2 name 9|3 type #0|4 is_private 8|5 is_bot_in_channel 8?",$e]}}class pO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pO).fromBinary(t,r)}static fromJson(t,r){return(new pO).fromJson(t,r)}static fromJsonString(t,r){return(new pO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pO,t,r)}static $(){return["SendDownloadEmailRequest"]}}class hO extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hO).fromBinary(t,r)}static fromJson(t,r){return(new hO).fromJson(t,r)}static fromJsonString(t,r){return(new hO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hO,t,r)}static $(){return["SendDownloadEmailResponse|1 success 8"]}}class gO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.isUserOwned=!1,this.isVerified=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gO).fromBinary(t,r)}static fromJson(t,r){return(new gO).fromJson(t,r)}static fromJsonString(t,r){return(new gO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gO,t,r)}static $(){return["Publisher|1 id 3|2 name 9|3 display_name 9|4 description 9?|5 owner_user_id 5?|6 owner_team_id 5?|15 is_user_owned 8|7 is_verified 8|8 verified_at 3?|9 verified_domain 9?|10 logo_url 9?|11 website_url 9?|12 support_url 9?|13 created_at 3|14 updated_at 3"]}}class _O extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.directoryGroupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _O).fromBinary(t,r)}static fromJson(t,r){return(new _O).fromJson(t,r)}static fromJsonString(t,r){return(new _O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_O,t,r)}static $(){return["MarketplaceRequiredPluginInstall|1 plugin_id 3|2 directory_group_ids 3*"]}}class JO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.gitUrl="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.requiredPluginInstalls=[],this.autoReindex=!1,this.isDefault=!1,this.allowUserPublish=!1,this.grokBotLinked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JO).fromBinary(t,r)}static fromJson(t,r){return(new JO).fromJson(t,r)}static fromJsonString(t,r){return(new JO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JO,t,r)}static $(){return["Marketplace|1 id 3|2 name 9|3 display_name 9?|4 description 9?|5 git_url 9|6 git_ref 9?|7 user_id 5?|8 team_id 5?|9 logo_url 9?|10 created_at 3|11 updated_at 3|12 last_indexed_at 3?|13 last_indexed_commit_sha 9?|14 team_config #0?|15 required_plugin_installs #1*|16 auto_reindex 8|17 distribution_git_url 9?|18 is_default 8|19 allow_user_publish 8|20 grok_bot_linked 8",IG,_O]}}class wO extends T{constructor(t){super(),this.name="",this.environments=[],this.disabledEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wO).fromBinary(t,r)}static fromJson(t,r){return(new wO).fromJson(t,r)}static fromJsonString(t,r){return(new wO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wO,t,r)}static $(){return["SkillDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?|5 environments 9*|6 disabled_environments 9*|7 custom_mode #0?|8 display_name 9?|9 icon 9?|10 color 9?|11 content 9?|12 source_repo_url 9?",E.o7L]}}class yO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yO).fromBinary(t,r)}static fromJson(t,r){return(new yO).fromJson(t,r)}static fromJsonString(t,r){return(new yO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yO,t,r)}static $(){return["SubagentDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class SO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SO).fromBinary(t,r)}static fromJson(t,r){return(new SO).fromJson(t,r)}static fromJsonString(t,r){return(new SO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SO,t,r)}static $(){return["HookDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class qO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qO).fromBinary(t,r)}static fromJson(t,r){return(new qO).fromJson(t,r)}static fromJsonString(t,r){return(new qO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qO,t,r)}static $(){return["RuleDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class BO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BO).fromBinary(t,r)}static fromJson(t,r){return(new BO).fromJson(t,r)}static fromJsonString(t,r){return(new BO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BO,t,r)}static $(){return["McpDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class IO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IO).fromBinary(t,r)}static fromJson(t,r){return(new IO).fromJson(t,r)}static fromJsonString(t,r){return(new IO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IO,t,r)}static $(){return["CommandDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?|5 source_repo_url 9?"]}}class PO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.status=Me.UNSPECIFIED,this.tags=[],this.isPublished=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.isDeprecated=!1,this.gitUrl="",this.fullRef="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],this.curatedCategoryKeys=[],this.lifecycleState=Oe.UNSPECIFIED,this.publishedByUser=!1,this.teamMarketplaceConfiguredSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PO).fromBinary(t,r)}static fromJson(t,r){return(new PO).fromJson(t,r)}static fromJsonString(t,r){return(new PO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PO,t,r)}static $(){return["Plugin|1 id 3|2 name 9|3 display_name 9|4 description 9|6 status #0|8 repository_url 9?|9 tags 9*|10 logo_url 9?|11 primary_color 9?|12 is_published 8|13 created_at 3|14 updated_at 3|16 publisher_id 3?|17 publisher #1?|18 is_deprecated 8|19 deprecation_message 9?|20 deprecated_at 3?|21 replaced_by_plugin_id 3?|22 marketplace_id 3?|23 marketplace #2?|24 git_url 9|25 git_ref 9?|26 git_path 9?|27 full_ref 9|28 skills #3*|29 subagents #4*|30 hooks #5*|31 rules #6*|32 mcp_servers #7*|33 commands #8*|34 release_repo 9?|35 release_asset 9?|36 release_tag 9?|37 curated_category_keys 9*|38 variables #9|39 team_marketplace_install_mode #10?|40 team_marketplace_configured_variables #9|41 lifecycle_state #11|42 min_client_versions #12?|43 published_by_user 8|44 popularity_rank 5?|45 team_admin_install_block_reason #13?|46 account_unavailable_reason #14?|47 sharepoint_install_block_detail #15?|48 team_marketplace_configured_secret_names 9*|49 backend_content #16?",Me,gO,JO,wO,yO,SO,qO,BO,IO,n.Struct,rn,Oe,bO,Ge,Ne,De,CN]}}class bO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bO).fromBinary(t,r)}static fromJson(t,r){return(new bO).fromJson(t,r)}static fromJsonString(t,r){return(new bO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bO,t,r)}static $(){return["PluginMinClientVersions|1 cursor 9?|2 sand 9?|3 sand_mobile 9?"]}}class RO extends T{constructor(t){super(),this.userId=0,this.pluginId=n.protoInt64.zero,this.isEnabled=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RO).fromBinary(t,r)}static fromJson(t,r){return(new RO).fromJson(t,r)}static fromJsonString(t,r){return(new RO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RO,t,r)}static $(){return["UserPluginInstall|1 user_id 5|2 plugin_id 3|4 is_enabled 8|6 created_at 3|7 updated_at 3|8 plugin #0|10 pinned_git_ref 9?",PO]}}class vO extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,this.isRequired=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vO).fromBinary(t,r)}static fromJson(t,r){return(new vO).fromJson(t,r)}static fromJsonString(t,r){return(new vO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vO,t,r)}static $(){return["TeamPluginInstall|1 team_id 5|2 plugin_id 3|3 added_by_user_id 5?|4 is_required 8|6 created_at 3|7 updated_at 3|8 plugin #0|10 pinned_git_ref 9?",PO]}}class xO extends T{constructor(t){super(),this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xO).fromBinary(t,r)}static fromJson(t,r){return(new xO).fromJson(t,r)}static fromJsonString(t,r){return(new xO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xO,t,r)}static $(){return["ListMarketplacePluginsRequest|1 search 9?|2 tags 9*|3 page_size 5?|4 page_token 9?|5 marketplace_id 3?|6 publisher_id 3?|7 skip_team_admin_filter 8?|8 exclude_cloud_agent_plugins 8?|9 include_team_admin_blocked 8?|10 supports_backend_content 8?"]}}class kO extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,this.supersededPluginPopularityRanks={},this.teamAdminBlockedShown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kO).fromBinary(t,r)}static fromJson(t,r){return(new kO).fromJson(t,r)}static fromJsonString(t,r){return(new kO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kO,t,r)}static $(){return["ListMarketplacePluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8|4 superseded_plugin_popularity_ranks 9,5|5 team_admin_blocked_shown 8",PO]}}class EO extends T{constructor(t){super(),this.stage=Le.UNSPECIFIED,this.client=Fe.UNSPECIFIED,this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EO).fromBinary(t,r)}static fromJson(t,r){return(new EO).fromJson(t,r)}static fromJsonString(t,r){return(new EO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EO,t,r)}static $(){return["RecordConnectorPolicyBlockedRequest|1 stage #0|2 client #1|3 plugin_ids 3*",Le,Fe]}}class CO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CO).fromBinary(t,r)}static fromJson(t,r){return(new CO).fromJson(t,r)}static fromJsonString(t,r){return(new CO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CO,t,r)}static $(){return["RecordConnectorPolicyBlockedResponse"]}}class TO extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TO).fromBinary(t,r)}static fromJson(t,r){return(new TO).fromJson(t,r)}static fromJsonString(t,r){return(new TO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TO,t,r)}static $(){return["ListPublisherPublicPluginsRequest|1 publisher_id 3|2 page_size 5?|3 page_token 9?"]}}class UO extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UO).fromBinary(t,r)}static fromJson(t,r){return(new UO).fromJson(t,r)}static fromJsonString(t,r){return(new UO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UO,t,r)}static $(){return["ListPublisherPublicPluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8",PO]}}class AO extends T{constructor(t){super(),this.visibility="",this.links={},this.createdAt="",this.updatedAt="",this.badges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AO).fromBinary(t,r)}static fromJson(t,r){return(new AO).fromJson(t,r)}static fromJsonString(t,r){return(new AO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AO,t,r)}static $(){return["UserProfile|1 handle 9?|2 visibility 9|3 links 9,9|4 created_at 9|5 updated_at 9|6 display_name 9?|7 avatar_url 9?|8 badges 9*|9 show_private_origin_contributions 8?"]}}class $O extends T{constructor(t){super(),this.date="",this.agentCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $O).fromBinary(t,r)}static fromJson(t,r){return(new $O).fromJson(t,r)}static fromJsonString(t,r){return(new $O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($O,t,r)}static $(){return["PublicProfileDailyAgentCount|1 date 9|2 agent_count 5"]}}class MO extends T{constructor(t){super(),this.date="",this.count=0,this.value=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MO).fromBinary(t,r)}static fromJson(t,r){return(new MO).fromJson(t,r)}static fromJsonString(t,r){return(new MO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MO,t,r)}static $(){return["PublicProfileActivityCount|1 date 9|2 count 5|3 value 3"]}}class OO extends T{constructor(t){super(),this.date="",this.tokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OO).fromBinary(t,r)}static fromJson(t,r){return(new OO).fromJson(t,r)}static fromJsonString(t,r){return(new OO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OO,t,r)}static $(){return["PublicProfileTokensPerDay|1 date 9|2 tokens 3"]}}class DO extends T{constructor(t){super(),this.date="",this.localCount=0,this.cloudCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DO).fromBinary(t,r)}static fromJson(t,r){return(new DO).fromJson(t,r)}static fromJsonString(t,r){return(new DO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DO,t,r)}static $(){return["PublicProfileAgentsPerDay|1 date 9|2 local_count 5|3 cloud_count 5"]}}class NO extends T{constructor(t){super(),this.date="",this.pullRequests=0,this.reviews=0,this.commits=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NO).fromBinary(t,r)}static fromJson(t,r){return(new NO).fromJson(t,r)}static fromJsonString(t,r){return(new NO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NO,t,r)}static $(){return["PublicProfileOriginContributionsPerDay|1 date 9|2 pull_requests 5|3 reviews 5|4 commits 5"]}}class GO extends T{constructor(t){super(),this.days=[],this.activityYears=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GO).fromBinary(t,r)}static fromJson(t,r){return(new GO).fromJson(t,r)}static fromJsonString(t,r){return(new GO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GO,t,r)}static $(){return["PublicProfileOriginActivity|1 days #0*|2 activity_years 5*",NO]}}class LO extends T{constructor(t){super(),this.mostActiveMonth="",this.mostActiveDay="",this.longestStreak=0,this.currentStreak=0,this.activeDates=[],this.dailyAgentCounts=[],this.activityCounts=[],this.agentsLocal=0,this.agentsCloud=0,this.longestAgentSeconds=n.protoInt64.zero,this.tokensOverTime=[],this.agentsOverTime=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LO).fromBinary(t,r)}static fromJson(t,r){return(new LO).fromJson(t,r)}static fromJsonString(t,r){return(new LO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LO,t,r)}static $(){return["PublicProfileActivitySummary|1 most_active_month 9|2 most_active_day 9|3 longest_streak 5|4 current_streak 5|5 active_dates 9*|6 daily_agent_counts #0*|7 activity_counts #1*|10 agents_local 5|11 agents_cloud 5|12 longest_agent_seconds 3|13 tokens_over_time #2*|14 agents_over_time #3*|16 origin_activity #4",$O,MO,OO,DO,GO]}}class FO extends T{constructor(t){super(),this.includeActivitySummary=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FO).fromBinary(t,r)}static fromJson(t,r){return(new FO).fromJson(t,r)}static fromJsonString(t,r){return(new FO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FO,t,r)}static $(){return["GetUserProfileRequest|1 include_activity_summary 8"]}}class KO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KO).fromBinary(t,r)}static fromJson(t,r){return(new KO).fromJson(t,r)}static fromJsonString(t,r){return(new KO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KO,t,r)}static $(){return["GetUserProfileResponse|1 profile #0?|3 activity_summary #1|4 public_visibility_allowed 8?|5 max_visibility 9?",AO,LO]}}class zO extends T{constructor(t){super(),this.links={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zO).fromBinary(t,r)}static fromJson(t,r){return(new zO).fromJson(t,r)}static fromJsonString(t,r){return(new zO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zO,t,r)}static $(){return["UpdateUserProfileRequest|1 visibility 9?|2 links 9,9|3 metadata #0?|4 show_private_origin_contributions 8?",n.Struct]}}class jO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jO).fromBinary(t,r)}static fromJson(t,r){return(new jO).fromJson(t,r)}static fromJsonString(t,r){return(new jO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jO,t,r)}static $(){return["UpdateUserProfileResponse|1 profile #0",AO]}}class HO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HO).fromBinary(t,r)}static fromJson(t,r){return(new HO).fromJson(t,r)}static fromJsonString(t,r){return(new HO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HO,t,r)}static $(){return["ClaimUserProfileHandleRequest|1 handle 9"]}}class WO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WO).fromBinary(t,r)}static fromJson(t,r){return(new WO).fromJson(t,r)}static fromJsonString(t,r){return(new WO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WO,t,r)}static $(){return["ClaimUserProfileHandleResponse|1 profile #0",AO]}}class QO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QO).fromBinary(t,r)}static fromJson(t,r){return(new QO).fromJson(t,r)}static fromJsonString(t,r){return(new QO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QO,t,r)}static $(){return["GetPublicProfileByHandleRequest|1 handle 9"]}}class VO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VO).fromBinary(t,r)}static fromJson(t,r){return(new VO).fromJson(t,r)}static fromJsonString(t,r){return(new VO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VO,t,r)}static $(){return["GetPublicProfileByHandleResponse|1 profile #0|2 activity_summary #1",AO,LO]}}class XO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XO).fromBinary(t,r)}static fromJson(t,r){return(new XO).fromJson(t,r)}static fromJsonString(t,r){return(new XO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XO,t,r)}static $(){return["GetViewableProfileByHandleRequest|1 handle 9"]}}class YO extends T{constructor(t){super(),this.viewedAs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YO).fromBinary(t,r)}static fromJson(t,r){return(new YO).fromJson(t,r)}static fromJsonString(t,r){return(new YO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YO,t,r)}static $(){return["GetViewableProfileByHandleResponse|1 profile #0|2 activity_summary #1|3 viewed_as 9",AO,LO]}}class ZO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZO).fromBinary(t,r)}static fromJson(t,r){return(new ZO).fromJson(t,r)}static fromJsonString(t,r){return(new ZO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZO,t,r)}static $(){return["GetTeamMemberProfileByHandleRequest|1 handle 9"]}}class tD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tD).fromBinary(t,r)}static fromJson(t,r){return(new tD).fromJson(t,r)}static fromJsonString(t,r){return(new tD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tD,t,r)}static $(){return["GetTeamMemberProfileByHandleResponse|1 profile #0|2 activity_summary #1",AO,LO]}}class rD extends T{constructor(t){super(),this.year=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rD).fromBinary(t,r)}static fromJson(t,r){return(new rD).fromJson(t,r)}static fromJsonString(t,r){return(new rD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rD,t,r)}static $(){return["GetProfileOriginContributionsRequest|1 handle 9?|2 year 5"]}}class eD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eD).fromBinary(t,r)}static fromJson(t,r){return(new eD).fromJson(t,r)}static fromJsonString(t,r){return(new eD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eD,t,r)}static $(){return["GetProfileOriginContributionsResponse|1 origin_activity #0",GO]}}class nD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nD).fromBinary(t,r)}static fromJson(t,r){return(new nD).fromJson(t,r)}static fromJsonString(t,r){return(new nD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nD,t,r)}static $(){return["GetPluginRequest|1 plugin_id 3|2 supports_backend_content 8?"]}}class sD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sD).fromBinary(t,r)}static fromJson(t,r){return(new sD).fromJson(t,r)}static fromJsonString(t,r){return(new sD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sD,t,r)}static $(){return["GetPluginResponse|1 plugin #0|2 mcp_server_links #1?",PO,iD]}}class iD extends T{constructor(t){super(),this.servers=[],this.viewerIsTeamAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iD).fromBinary(t,r)}static fromJson(t,r){return(new iD).fromJson(t,r)}static fromJsonString(t,r){return(new iD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iD,t,r)}static $(){return["PluginMcpServerLinks|1 servers #0*|2 viewer_is_team_admin 8|3 manage_team_connectors_url 9?",oD]}}class oD extends T{constructor(t){super(),this.name="",this.description="",this.serverUrl="",this.state={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oD).fromBinary(t,r)}static fromJson(t,r){return(new oD).fromJson(t,r)}static fromJsonString(t,r){return(new oD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oD,t,r)}static $(){return["PluginMcpServerLink|1 name 9|2 description 9|3 server_url 9|4 ready #0 state|5 needs_connect #0 state|6 needs_reauth #0 state|7 disabled #0 state|8 ambiguous #1 state|9 not_approved #2 state|10 unknown #3 state|11 local #2 state|12 unusable #2 state|13 blocked_by_team_policy #0 state",aD,uD,lD,cD]}}class aD extends T{constructor(t){super(),this.connectorId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aD).fromBinary(t,r)}static fromJson(t,r){return(new aD).fromJson(t,r)}static fromJsonString(t,r){return(new aD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aD,t,r)}static $(){return["PluginMcpServerLink.Connector|1 connector_id 9|2 name 9|3 server_identifier 9?"]}}class uD extends T{constructor(t){super(),this.connectors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uD).fromBinary(t,r)}static fromJson(t,r){return(new uD).fromJson(t,r)}static fromJsonString(t,r){return(new uD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uD,t,r)}static $(){return["PluginMcpServerLink.Connectors|1 connectors #0*",aD]}}class cD extends T{constructor(t){super(),this.cause=Ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cD).fromBinary(t,r)}static fromJson(t,r){return(new cD).fromJson(t,r)}static fromJsonString(t,r){return(new cD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cD,t,r)}static $(){return["PluginMcpServerLink.Unknown|1 cause #0",Ke]}}class lD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lD).fromBinary(t,r)}static fromJson(t,r){return(new lD).fromJson(t,r)}static fromJsonString(t,r){return(new lD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lD,t,r)}static $(){return["PluginMcpServerLink.Empty"]}}class mD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.connectorId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mD).fromBinary(t,r)}static fromJson(t,r){return(new mD).fromJson(t,r)}static fromJsonString(t,r){return(new mD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mD,t,r)}static $(){return["StartPluginMcpConnectorSignInRequest|1 plugin_id 3|2 connector_id 9"]}}class fD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fD).fromBinary(t,r)}static fromJson(t,r){return(new fD).fromJson(t,r)}static fromJsonString(t,r){return(new fD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fD,t,r)}static $(){return["StartPluginMcpConnectorSignInResponse|1 auth_url 9?"]}}class dD extends T{constructor(t){super(),this.name="",this.content="",this.environments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dD).fromBinary(t,r)}static fromJson(t,r){return(new dD).fromJson(t,r)}static fromJsonString(t,r){return(new dD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dD,t,r)}static $(){return["TeamSkill|1 name 9|2 description 9?|3 content 9|4 source_path 9?|5 environments 9*"]}}class pD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pD).fromBinary(t,r)}static fromJson(t,r){return(new pD).fromJson(t,r)}static fromJsonString(t,r){return(new pD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pD,t,r)}static $(){return["TeamSubagent"]}}class hD extends T{constructor(t){super(),this.name="",this.displayName="",this.description="",this.tags=[],this.inlineRules=[],this.inlineHooks=[],this.inlineCommands=[],this.mcpConfigJson="",this.inlineSkills=[],this.inlineSubagents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hD).fromBinary(t,r)}static fromJson(t,r){return(new hD).fromJson(t,r)}static fromJsonString(t,r){return(new hD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hD,t,r)}static $(){return["CreatePluginRequest|2 name 9|3 display_name 9|4 description 9|5 tags 9*|6 git_url 9?|7 git_ref 9?|8 repository_url 9?|9 logo_url 9?|16 inline_rules #0*|17 inline_hooks #1*|18 inline_commands #2*|19 mcp_config_json 9|20 variables #3|21 inline_skills #4*|22 inline_subagents #5*|23 marketplace_id 3?|24 team_id 5?",fU,xU,OU,n.Struct,dD,pD]}}class gD extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gD).fromBinary(t,r)}static fromJson(t,r){return(new gD).fromJson(t,r)}static fromJsonString(t,r){return(new gD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gD,t,r)}static $(){return["CreatePluginResponse|1 plugin #0|2 mcp_servers #1*",PO,qN]}}class _D extends T{constructor(t){super(),this.teamId=0,this.name="",this.displayName="",this.description="",this.pluginTarGz=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _D).fromBinary(t,r)}static fromJson(t,r){return(new _D).fromJson(t,r)}static fromJsonString(t,r){return(new _D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_D,t,r)}static $(){return["PublishPluginRequest|1 team_id 5|2 name 9|3 display_name 9|4 description 9|5 plugin_tar_gz 12|6 commit_message 9?|7 expected_plugin_id 3?"]}}class JD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.marketplaceId=n.protoInt64.zero,this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JD).fromBinary(t,r)}static fromJson(t,r){return(new JD).fromJson(t,r)}static fromJsonString(t,r){return(new JD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JD,t,r)}static $(){return["PublishPluginResponse|1 plugin_id 3|2 marketplace_id 3|3 commit_sha 9"]}}class wD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wD).fromBinary(t,r)}static fromJson(t,r){return(new wD).fromJson(t,r)}static fromJsonString(t,r){return(new wD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wD,t,r)}static $(){return["UnpublishPluginRequest|1 plugin_id 3|2 team_id 5?|3 commit_message 9?|4 publisher_only 8?"]}}class yD extends T{constructor(t){super(),this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yD).fromBinary(t,r)}static fromJson(t,r){return(new yD).fromJson(t,r)}static fromJsonString(t,r){return(new yD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yD,t,r)}static $(){return["UnpublishPluginResponse|1 commit_sha 9"]}}class SD extends T{constructor(t){super(),this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SD).fromBinary(t,r)}static fromJson(t,r){return(new SD).fromJson(t,r)}static fromJsonString(t,r){return(new SD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SD,t,r)}static $(){return["ParseGitHubRepoForPluginRequest|1 git_url 9|2 git_ref 9?|3 enforce_auth 8?"]}}class qD extends T{constructor(t){super(),this.name="",this.displayName="",this.description="",this.gitPath="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qD).fromBinary(t,r)}static fromJson(t,r){return(new qD).fromJson(t,r)}static fromJsonString(t,r){return(new qD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qD,t,r)}static $(){return["ParsedPluginEntry|1 name 9|2 display_name 9|3 description 9|4 git_path 9|5 skills #0*|6 subagents #1*|7 hooks #2*|8 rules #3*|9 mcp_servers #4*|10 commands #5*|11 logo_url 9?|12 variables #6|13 source_git_url 9?|14 source_git_ref 9?|15 parse_error 9?|16 min_client_versions #7?",wO,yO,SO,qO,BO,IO,n.Struct,bO]}}class BD extends T{constructor(t){super(),this.marketplaceName="",this.marketplaceDescription="",this.defaultBranch="",this.repositoryUrl="",this.plugins=[],this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BD).fromBinary(t,r)}static fromJson(t,r){return(new BD).fromJson(t,r)}static fromJsonString(t,r){return(new BD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BD,t,r)}static $(){return["ParseGitHubRepoForPluginsResponse|1 marketplace_name 9|2 marketplace_description 9|3 default_branch 9|4 repository_url 9|5 plugins #0*|6 commit_sha 9",qD]}}class ID extends T{constructor(t){super(),this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ID).fromBinary(t,r)}static fromJson(t,r){return(new ID).fromJson(t,r)}static fromJsonString(t,r){return(new ID).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ID,t,r)}static $(){return["ParsePluginPublisherRepoInternalRequest|1 git_url 9|2 git_ref 9?|3 release_tag 9?|4 release_asset 9?"]}}class PD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PD).fromBinary(t,r)}static fromJson(t,r){return(new PD).fromJson(t,r)}static fromJsonString(t,r){return(new PD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PD,t,r)}static $(){return["ParsePluginPublisherRepoInternalResponse|1 parsed_repo #0|2 release_repo 9?|3 release_asset 9?|4 release_tag 9?",BD]}}class bD extends T{constructor(t){super(),this.type="",this.added=[],this.removed=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bD).fromBinary(t,r)}static fromJson(t,r){return(new bD).fromJson(t,r)}static fromJsonString(t,r){return(new bD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bD,t,r)}static $(){return["ReindexComponentDiff|1 type 9|2 added 9*|3 removed 9*"]}}class RD extends T{constructor(t){super(),this.name="",this.displayName="",this.status="",this.componentChanges=[],this.metadataChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RD).fromBinary(t,r)}static fromJson(t,r){return(new RD).fromJson(t,r)}static fromJsonString(t,r){return(new RD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RD,t,r)}static $(){return["ReindexPluginDiff|1 name 9|2 display_name 9|3 status 9|4 component_changes #0*|5 metadata_changes 9*",bD]}}class vD extends T{constructor(t){super(),this.newPlugins=0,this.removedPlugins=0,this.updatedPlugins=0,this.unchangedPlugins=0,this.totalNewComponents=0,this.totalRemovedComponents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vD).fromBinary(t,r)}static fromJson(t,r){return(new vD).fromJson(t,r)}static fromJsonString(t,r){return(new vD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vD,t,r)}static $(){return["ReindexSummary|1 new_plugins 5|2 removed_plugins 5|3 updated_plugins 5|4 unchanged_plugins 5|5 total_new_components 5|6 total_removed_components 5"]}}class xD extends T{constructor(t){super(),this.publisherName="",this.gitUrl="",this.gitRef="",this.commitSha="",this.pluginDiffs=[],this.newCommitCount=0,this.conflictingNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xD).fromBinary(t,r)}static fromJson(t,r){return(new xD).fromJson(t,r)}static fromJsonString(t,r){return(new xD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xD,t,r)}static $(){return["PreviewReindexPluginRepoResponse|1 publisher_name 9|2 git_url 9|3 git_ref 9|4 commit_sha 9|5 plugin_diffs #0*|6 summary #1|7 new_commit_count 5|8 conflicting_names 9*",RD,vD]}}class kD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kD).fromBinary(t,r)}static fromJson(t,r){return(new kD).fromJson(t,r)}static fromJsonString(t,r){return(new kD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kD,t,r)}static $(){return["PreviewReindexPluginRepoInternalRequest|1 publisher_id 3|2 git_url 9|3 git_ref 9?|4 pinned_git_ref 9?|5 release_tag 9?"]}}class ED extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.gitUrl="",this.deprecateRemoved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ED).fromBinary(t,r)}static fromJson(t,r){return(new ED).fromJson(t,r)}static fromJsonString(t,r){return(new ED).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ED,t,r)}static $(){return["ApplyReindexPluginRepoInternalRequest|1 publisher_id 3|2 git_url 9|3 git_ref 9?|4 deprecate_removed 8|5 release_tag 9?"]}}class CD extends T{constructor(t){super(),this.createdCount=0,this.updatedCount=0,this.deprecatedCount=0,this.createdPluginNames=[],this.updatedPluginNames=[],this.deprecatedPluginNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CD).fromBinary(t,r)}static fromJson(t,r){return(new CD).fromJson(t,r)}static fromJsonString(t,r){return(new CD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CD,t,r)}static $(){return["ApplyReindexPluginRepoResponse|1 created_count 5|2 updated_count 5|3 deprecated_count 5|4 created_plugin_names 9*|5 updated_plugin_names 9*|6 deprecated_plugin_names 9*"]}}class TD extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.distributionGitUrl="",this.originRepoUuid="",this.acknowledgeDistributionRisk=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TD).fromBinary(t,r)}static fromJson(t,r){return(new TD).fromJson(t,r)}static fromJsonString(t,r){return(new TD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TD,t,r)}static $(){return["UpdateTeamMarketplaceOriginDistributionInternalRequest|1 marketplace_id 3|2 distribution_git_url 9|3 origin_repo_uuid 9|4 acknowledge_distribution_risk 8"]}}class UD extends T{constructor(t){super(),this.changed=!1,this.distributionGitUrl="",this.originRepoUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UD).fromBinary(t,r)}static fromJson(t,r){return(new UD).fromJson(t,r)}static fromJsonString(t,r){return(new UD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UD,t,r)}static $(){return["UpdateTeamMarketplaceOriginDistributionInternalResponse|1 changed 8|2 distribution_git_url 9|3 origin_repo_uuid 9"]}}class AD extends T{constructor(t){super(),this.cursorUserId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AD).fromBinary(t,r)}static fromJson(t,r){return(new AD).fromJson(t,r)}static fromJsonString(t,r){return(new AD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AD,t,r)}static $(){return["GetUserServedPlanInternalRequest|1 cursor_user_id 3"]}}class $D extends T{constructor(t){super(),this.kind=ze.UNSPECIFIED,this.membershipType="",this.target="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $D).fromBinary(t,r)}static fromJson(t,r){return(new $D).fromJson(t,r)}static fromJsonString(t,r){return(new $D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($D,t,r)}static $(){return["GetUserServedPlanInternalResponse|1 kind #0|2 membership_type 9|3 target 9|4 team_id 3?|5 merged_team_seat_tier 9?",ze]}}class MD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.fromGitUrl="",this.toGitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MD).fromBinary(t,r)}static fromJson(t,r){return(new MD).fromJson(t,r)}static fromJsonString(t,r){return(new MD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MD,t,r)}static $(){return["PreviewMigrateReindexPluginRepoInternalRequest|1 publisher_id 3|2 from_git_url 9|3 to_git_url 9|4 git_ref 9?|5 release_tag 9?"]}}class OD extends T{constructor(t){super(),this.publisherName="",this.fromGitUrl="",this.toGitUrl="",this.gitUrl="",this.gitRef="",this.commitSha="",this.pluginDiffs=[],this.conflictingNames=[],this.targetRepoNameConflicts=[],this.deprecatedSourceNameConflicts=[],this.canApply=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OD).fromBinary(t,r)}static fromJson(t,r){return(new OD).fromJson(t,r)}static fromJsonString(t,r){return(new OD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OD,t,r)}static $(){return["PreviewMigrateReindexPluginRepoResponse|1 publisher_name 9|2 from_git_url 9|3 to_git_url 9|4 git_url 9|5 git_ref 9|6 commit_sha 9|7 plugin_diffs #0*|8 summary #1|9 conflicting_names 9*|10 target_repo_name_conflicts 9*|11 deprecated_source_name_conflicts 9*|12 can_apply 8",RD,vD]}}class DD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.fromGitUrl="",this.toGitUrl="",this.deprecateRemoved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DD).fromBinary(t,r)}static fromJson(t,r){return(new DD).fromJson(t,r)}static fromJsonString(t,r){return(new DD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DD,t,r)}static $(){return["ApplyMigrateReindexPluginRepoInternalRequest|1 publisher_id 3|2 from_git_url 9|3 to_git_url 9|4 git_ref 9?|5 release_tag 9?|6 deprecate_removed 8"]}}class ND extends T{constructor(t){super(),this.migratedCount=0,this.createdCount=0,this.updatedCount=0,this.deprecatedCount=0,this.createdPluginNames=[],this.updatedPluginNames=[],this.deprecatedPluginNames=[],this.toGitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ND).fromBinary(t,r)}static fromJson(t,r){return(new ND).fromJson(t,r)}static fromJsonString(t,r){return(new ND).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ND,t,r)}static $(){return["ApplyMigrateReindexPluginRepoResponse|1 migrated_count 5|2 created_count 5|3 updated_count 5|4 deprecated_count 5|5 created_plugin_names 9*|6 updated_plugin_names 9*|7 deprecated_plugin_names 9*|8 to_git_url 9"]}}class GD extends T{constructor(t){super(),this.targetUserId=n.protoInt64.zero,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GD).fromBinary(t,r)}static fromJson(t,r){return(new GD).fromJson(t,r)}static fromJsonString(t,r){return(new GD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GD,t,r)}static $(){return["CreateSupportImpersonationSessionInternalRequest|1 target_user_id 3|2 reason 9"]}}class LD extends T{constructor(t){super(),this.redemptionCode="",this.targetEmail="",this.targetAuthId="",this.redemptionExpiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LD).fromBinary(t,r)}static fromJson(t,r){return(new LD).fromJson(t,r)}static fromJsonString(t,r){return(new LD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LD,t,r)}static $(){return["CreateSupportImpersonationSessionInternalResponse|1 redemption_code 9|2 target_email 9|3 target_auth_id 9|4 redemption_expires_at_ms 3"]}}class FD extends T{constructor(t){super(),this.targetUserId=n.protoInt64.zero,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FD).fromBinary(t,r)}static fromJson(t,r){return(new FD).fromJson(t,r)}static fromJsonString(t,r){return(new FD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FD,t,r)}static $(){return["RevokeSupportImpersonationSessionsInternalRequest|1 target_user_id 3|2 reason 9"]}}class KD extends T{constructor(t){super(),this.revokedCount=0,this.targetAuthId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KD).fromBinary(t,r)}static fromJson(t,r){return(new KD).fromJson(t,r)}static fromJsonString(t,r){return(new KD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KD,t,r)}static $(){return["RevokeSupportImpersonationSessionsInternalResponse|1 revoked_count 5|2 target_auth_id 9"]}}class zD extends T{constructor(t){super(),this.organizationPublicId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zD).fromBinary(t,r)}static fromJson(t,r){return(new zD).fromJson(t,r)}static fromJsonString(t,r){return(new zD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zD,t,r)}static $(){return["RemoveOrganizationMemberInternalRequest|1 organization_public_id 9|2 user_id 5"]}}class jD extends T{constructor(t){super(),this.removed=!1,this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jD).fromBinary(t,r)}static fromJson(t,r){return(new jD).fromJson(t,r)}static fromJsonString(t,r){return(new jD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jD,t,r)}static $(){return["RemoveOrganizationMemberInternalResponse|1 removed 8|2 removed_team_ids 5*"]}}class HD extends T{constructor(t){super(),this.organizationPublicId="",this.teamId=0,this.ownerUserId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HD).fromBinary(t,r)}static fromJson(t,r){return(new HD).fromJson(t,r)}static fromJsonString(t,r){return(new HD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HD,t,r)}static $(){return["LinkOrganizationTeamToXaiInternalRequest|1 organization_public_id 9|2 team_id 5|3 owner_user_id 5"]}}class WD extends T{constructor(t){super(),this.outcome=je.UNSPECIFIED,this.xaiTeamId="",this.enterprise="",this.step="",this.xaiStatus=0,this.wellKnownCode="",this.code="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WD).fromBinary(t,r)}static fromJson(t,r){return(new WD).fromJson(t,r)}static fromJsonString(t,r){return(new WD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WD,t,r)}static $(){return["LinkOrganizationTeamToXaiInternalResponse|1 outcome #0|2 xai_team_id 9|3 enterprise 9|4 step 9|5 xai_status 5|6 well_known_code 9|7 code 9|8 message 9",je]}}class QD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QD).fromBinary(t,r)}static fromJson(t,r){return(new QD).fromJson(t,r)}static fromJsonString(t,r){return(new QD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QD,t,r)}static $(){return["SubmitPluginForApprovalRequest|1 plugin_id 3"]}}class VD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VD).fromBinary(t,r)}static fromJson(t,r){return(new VD).fromJson(t,r)}static fromJsonString(t,r){return(new VD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VD,t,r)}static $(){return["SubmitPluginForApprovalResponse|1 plugin #0",PO]}}class XD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XD).fromBinary(t,r)}static fromJson(t,r){return(new XD).fromJson(t,r)}static fromJsonString(t,r){return(new XD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XD,t,r)}static $(){return["ApprovePluginRequest|1 plugin_id 3"]}}class YD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YD).fromBinary(t,r)}static fromJson(t,r){return(new YD).fromJson(t,r)}static fromJsonString(t,r){return(new YD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YD,t,r)}static $(){return["ApprovePluginResponse|1 plugin #0",PO]}}class ZD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZD).fromBinary(t,r)}static fromJson(t,r){return(new ZD).fromJson(t,r)}static fromJsonString(t,r){return(new ZD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZD,t,r)}static $(){return["RejectPluginRequest|1 plugin_id 3|2 reason 9?"]}}class tN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tN).fromBinary(t,r)}static fromJson(t,r){return(new tN).fromJson(t,r)}static fromJsonString(t,r){return(new tN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tN,t,r)}static $(){return["RejectPluginResponse|1 plugin #0",PO]}}class rN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rN).fromBinary(t,r)}static fromJson(t,r){return(new rN).fromJson(t,r)}static fromJsonString(t,r){return(new rN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rN,t,r)}static $(){return["ListUserPluginInstallsRequest|1 use_replica 8?"]}}class eN extends T{constructor(t){super(),this.installs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eN).fromBinary(t,r)}static fromJson(t,r){return(new eN).fromJson(t,r)}static fromJsonString(t,r){return(new eN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eN,t,r)}static $(){return["ListUserPluginInstallsResponse|1 installs #0*",RO]}}class nN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.allowMissingSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nN).fromBinary(t,r)}static fromJson(t,r){return(new nN).fromJson(t,r)}static fromJsonString(t,r){return(new nN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nN,t,r)}static $(){return["InstallUserPluginRequest|1 plugin_id 3|4 pinned_git_ref 9?|5 variables #0|6 allow_missing_secrets 8|7 supports_backend_content 8?",n.Struct]}}class sN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sN).fromBinary(t,r)}static fromJson(t,r){return(new sN).fromJson(t,r)}static fromJsonString(t,r){return(new sN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sN,t,r)}static $(){return["InstallUserPluginResponse|1 install #0",RO]}}class iN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.mergeWithStored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iN).fromBinary(t,r)}static fromJson(t,r){return(new iN).fromJson(t,r)}static fromJsonString(t,r){return(new iN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iN,t,r)}static $(){return["UpdateUserPluginInstallRequest|1 plugin_id 3|3 is_enabled 8?|5 pinned_git_ref 9?|6 variables #0|7 merge_with_stored 8",n.Struct]}}class oN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oN).fromBinary(t,r)}static fromJson(t,r){return(new oN).fromJson(t,r)}static fromJsonString(t,r){return(new oN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oN,t,r)}static $(){return["UpdateUserPluginInstallResponse|1 install #0",RO]}}class aN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aN).fromBinary(t,r)}static fromJson(t,r){return(new aN).fromJson(t,r)}static fromJsonString(t,r){return(new aN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aN,t,r)}static $(){return["UninstallUserPluginRequest|1 plugin_id 3"]}}class uN extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uN).fromBinary(t,r)}static fromJson(t,r){return(new uN).fromJson(t,r)}static fromJsonString(t,r){return(new uN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uN,t,r)}static $(){return["UninstallUserPluginResponse|1 success 8"]}}class cN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.memberInstallCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cN).fromBinary(t,r)}static fromJson(t,r){return(new cN).fromJson(t,r)}static fromJsonString(t,r){return(new cN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cN,t,r)}static $(){return["TeamPluginPopularityCount|1 plugin_id 3|2 member_install_count 5"]}}class lN extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lN).fromBinary(t,r)}static fromJson(t,r){return(new lN).fromJson(t,r)}static fromJsonString(t,r){return(new lN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lN,t,r)}static $(){return["GetTeamPluginPopularityRequest|1 team_id 5|2 use_replica 8?"]}}class mN extends T{constructor(t){super(),this.counts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mN).fromBinary(t,r)}static fromJson(t,r){return(new mN).fromJson(t,r)}static fromJsonString(t,r){return(new mN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mN,t,r)}static $(){return["GetTeamPluginPopularityResponse|1 counts #0*",cN]}}class fN extends T{constructor(t){super(),this.teamId=0,this.primitiveType=He.UNSPECIFIED,this.interval=We.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fN).fromBinary(t,r)}static fromJson(t,r){return(new fN).fromJson(t,r)}static fromJsonString(t,r){return(new fN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fN,t,r)}static $(){return["GetTeamPluginPrimitiveUsageRequest|1 team_id 5|2 primitive_type #0|3 interval #1|4 limit 5?|5 page_number 5?",He,We]}}class dN extends T{constructor(t){super(),this.primitiveName="",this.pluginId=n.protoInt64.zero,this.primitiveType=He.UNSPECIFIED,this.usageCount=n.protoInt64.zero,this.humanUsageCount=n.protoInt64.zero,this.agentUsageCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dN).fromBinary(t,r)}static fromJson(t,r){return(new dN).fromJson(t,r)}static fromJsonString(t,r){return(new dN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dN,t,r)}static $(){return["TeamPluginPrimitiveUsageRow|1 primitive_name 9|2 plugin_id 3|3 primitive_type #0|4 usage_count 4|5 human_usage_count 4|6 agent_usage_count 4",He]}}class pN extends T{constructor(t){super(),this.rows=[],this.hasMore=!1,this.pageSize=0,this.pageNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pN).fromBinary(t,r)}static fromJson(t,r){return(new pN).fromJson(t,r)}static fromJsonString(t,r){return(new pN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pN,t,r)}static $(){return["GetTeamPluginPrimitiveUsageResponse|1 rows #0*|2 has_more 8|3 page_size 5|4 page_number 5",dN]}}class hN extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hN).fromBinary(t,r)}static fromJson(t,r){return(new hN).fromJson(t,r)}static fromJsonString(t,r){return(new hN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hN,t,r)}static $(){return["ListTeamAvailableMarketplacePluginsRequest|1 team_id 5|2 search 9?|3 page_size 5?|4 page_token 9?|5 sort_by_team_popularity 8?|6 offset 5?"]}}class gN extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gN).fromBinary(t,r)}static fromJson(t,r){return(new gN).fromJson(t,r)}static fromJsonString(t,r){return(new gN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gN,t,r)}static $(){return["ListTeamAvailableMarketplacePluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8|4 total_count 5?",PO]}}class _N extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _N).fromBinary(t,r)}static fromJson(t,r){return(new _N).fromJson(t,r)}static fromJsonString(t,r){return(new _N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_N,t,r)}static $(){return["GetTeamPinnedMarketplacePluginsRequest|1 team_id 5"]}}class JN extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JN).fromBinary(t,r)}static fromJson(t,r){return(new JN).fromJson(t,r)}static fromJsonString(t,r){return(new JN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JN,t,r)}static $(){return["GetTeamPinnedMarketplacePluginsResponse|1 plugins #0*",PO]}}class wN extends T{constructor(t){super(),this.teamId=0,this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wN).fromBinary(t,r)}static fromJson(t,r){return(new wN).fromJson(t,r)}static fromJsonString(t,r){return(new wN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wN,t,r)}static $(){return["UpdateTeamPinnedMarketplacePluginsRequest|1 team_id 5|2 plugin_ids 3*"]}}class yN extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yN).fromBinary(t,r)}static fromJson(t,r){return(new yN).fromJson(t,r)}static fromJsonString(t,r){return(new yN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yN,t,r)}static $(){return["UpdateTeamPinnedMarketplacePluginsResponse|1 plugins #0*",PO]}}class SN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SN).fromBinary(t,r)}static fromJson(t,r){return(new SN).fromJson(t,r)}static fromJsonString(t,r){return(new SN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SN,t,r)}static $(){return["InstallTeamPluginRequest|1 team_id 5|2 plugin_id 3|4 is_required 8?|5 pinned_git_ref 9?"]}}class qN extends T{constructor(t){super(),this.serverId=n.protoInt64.zero,this.name="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qN).fromBinary(t,r)}static fromJson(t,r){return(new qN).fromJson(t,r)}static fromJsonString(t,r){return(new qN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qN,t,r)}static $(){return["TeamPluginMcpServer|1 server_id 3|2 name 9|3 type 9|4 local #0|5 cloud #0",BN]}}class BN extends T{constructor(t){super(),this.blocked=!1,this.blockedBy=Qe.UNSPECIFIED,this.byOffRule=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BN).fromBinary(t,r)}static fromJson(t,r){return(new BN).fromJson(t,r)}static fromJsonString(t,r){return(new BN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BN,t,r)}static $(){return["McpServerAddSurfaceCheck|1 blocked 8|2 blocked_by #0|3 by_off_rule 8",Qe]}}class IN extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IN).fromBinary(t,r)}static fromJson(t,r){return(new IN).fromJson(t,r)}static fromJsonString(t,r){return(new IN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IN,t,r)}static $(){return["InstallTeamPluginResponse|1 install #0|2 mcp_servers #1*",vO,qN]}}class PN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PN).fromBinary(t,r)}static fromJson(t,r){return(new PN).fromJson(t,r)}static fromJsonString(t,r){return(new PN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PN,t,r)}static $(){return["UpdateTeamPluginInstallRequest|1 team_id 5|2 plugin_id 3|4 is_required 8?|5 pinned_git_ref 9?"]}}class bN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bN).fromBinary(t,r)}static fromJson(t,r){return(new bN).fromJson(t,r)}static fromJsonString(t,r){return(new bN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bN,t,r)}static $(){return["UpdateTeamPluginInstallResponse|1 install #0",vO]}}class RN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RN).fromBinary(t,r)}static fromJson(t,r){return(new RN).fromJson(t,r)}static fromJsonString(t,r){return(new RN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RN,t,r)}static $(){return["UninstallTeamPluginRequest|1 team_id 5|2 plugin_id 3"]}}class vN extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vN).fromBinary(t,r)}static fromJson(t,r){return(new vN).fromJson(t,r)}static fromJsonString(t,r){return(new vN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vN,t,r)}static $(){return["UninstallTeamPluginResponse|1 success 8"]}}class xN extends T{constructor(t){super(),this.excludeConfiguredVariables=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xN).fromBinary(t,r)}static fromJson(t,r){return(new xN).fromJson(t,r)}static fromJsonString(t,r){return(new xN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xN,t,r)}static $(){return["GetEffectiveUserPluginsRequest|1 use_replica 8?|2 team_id 5?|4 exclude_configured_variables 8|5 supports_backend_content 8?"]}}class kN extends T{constructor(t){super(),this.isTeamRequired=!1,this.isEnabled=!1,this.hasTeamConfiguredVariables=!1,this.installMode=Ve.UNSPECIFIED,this.configuredVariableKeys=[],this.servedBy=tt.UNSPECIFIED,this.viewerCanUnpublish=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kN).fromBinary(t,r)}static fromJson(t,r){return(new kN).fromJson(t,r)}static fromJsonString(t,r){return(new kN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kN,t,r)}static $(){return["EffectivePlugin|1 plugin #0|3 is_team_required 8|4 is_enabled 8|6 pinned_git_ref 9?|7 configured_variables #1|8 has_team_configured_variables 8|9 inline_content_json 9?|10 install_mode #2|11 configured_variable_keys 9*|12 served_by #3|13 viewer_can_unpublish 8",PO,n.Struct,Ve,tt]}}class EN extends T{constructor(t){super(),this.plugins=[],this.marketplaces=[],this.bitbucketServerHostsNeedingLink=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EN).fromBinary(t,r)}static fromJson(t,r){return(new EN).fromJson(t,r)}static fromJsonString(t,r){return(new EN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EN,t,r)}static $(){return["GetEffectiveUserPluginsResponse|1 plugins #0*|2 marketplaces #1*|3 bitbucket_server_hosts_needing_link 9*",kN,JO]}}class CN extends T{constructor(t){super(),this.revision="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CN).fromBinary(t,r)}static fromJson(t,r){return(new CN).fromJson(t,r)}static fromJsonString(t,r){return(new CN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CN,t,r)}static $(){return["PluginBackendContent|1 revision 9"]}}class TN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.revision="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TN).fromBinary(t,r)}static fromJson(t,r){return(new TN).fromJson(t,r)}static fromJsonString(t,r){return(new TN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TN,t,r)}static $(){return["DownloadPluginContentRequest|1 plugin_id 3|2 revision 9"]}}class UN extends T{constructor(t){super(),this.sha256="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UN).fromBinary(t,r)}static fromJson(t,r){return(new UN).fromJson(t,r)}static fromJsonString(t,r){return(new UN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UN,t,r)}static $(){return["DownloadPluginContentHeader|1 sha256 9|2 size_bytes 3"]}}class AN extends T{constructor(t){super(),this.part={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AN).fromBinary(t,r)}static fromJson(t,r){return(new AN).fromJson(t,r)}static fromJsonString(t,r){return(new AN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AN,t,r)}static $(){return["DownloadPluginContentResponse|2 header #0 part|1 data 12 part",UN]}}class $N extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $N).fromBinary(t,r)}static fromJson(t,r){return(new $N).fromJson(t,r)}static fromJsonString(t,r){return(new $N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($N,t,r)}static $(){return["ListInstalledPluginsRequest|1 use_replica 8?|2 team_id 5?"]}}class MN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.installMode=Ve.UNSPECIFIED,this.ownedByCaller=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MN).fromBinary(t,r)}static fromJson(t,r){return(new MN).fromJson(t,r)}static fromJsonString(t,r){return(new MN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MN,t,r)}static $(){return["InstalledPluginSummary|1 id 3|2 name 9|3 display_name 9|4 description 9|5 publisher_display_name 9?|6 publisher_logo_url 9?|7 logo_url 9?|8 mcp_server_name 9?|9 install_mode #0|10 owned_by_caller 8",Ve]}}class ON extends T{constructor(t){super(),this.plugins=[],this.ownedByCallerKnown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ON).fromBinary(t,r)}static fromJson(t,r){return(new ON).fromJson(t,r)}static fromJsonString(t,r){return(new ON).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ON,t,r)}static $(){return["ListInstalledPluginsResponse|1 plugins #0*|2 owned_by_caller_known 8",MN]}}class DN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DN).fromBinary(t,r)}static fromJson(t,r){return(new DN).fromJson(t,r)}static fromJsonString(t,r){return(new DN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DN,t,r)}static $(){return["GetInstalledPluginDetailRequest|1 plugin_id 3|2 use_replica 8?|3 team_id 5?"]}}class NN extends T{constructor(t){super(),this.ownedByCallerKnown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NN).fromBinary(t,r)}static fromJson(t,r){return(new NN).fromJson(t,r)}static fromJsonString(t,r){return(new NN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NN,t,r)}static $(){return["GetInstalledPluginDetailResponse|1 plugin #0|2 owned_by_caller_known 8",VN]}}class GN extends T{constructor(t){super(),this.teamId=0,this.page=0,this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GN).fromBinary(t,r)}static fromJson(t,r){return(new GN).fromJson(t,r)}static fromJsonString(t,r){return(new GN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GN,t,r)}static $(){return["ListTeamPluginsTableRequest|1 team_id 5|2 team_marketplace_id 3?|3 page 5|4 page_size 5"]}}class LN extends T{constructor(t){super(),this.rows=[],this.totalCount=0,this.allowlistEnabled=!1,this.cloudAgentAllowlistEnabled=!1,this.viewerCanManage=!1,this.teamMarketplaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LN).fromBinary(t,r)}static fromJson(t,r){return(new LN).fromJson(t,r)}static fromJsonString(t,r){return(new LN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LN,t,r)}static $(){return["ListTeamPluginsTableResponse|1 rows #0*|2 total_count 5|3 allowlist_enabled 8|4 cloud_agent_allowlist_enabled 8|5 viewer_can_manage 8|6 team_marketplaces #1*",QN,FN]}}class FN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FN).fromBinary(t,r)}static fromJson(t,r){return(new FN).fromJson(t,r)}static fromJsonString(t,r){return(new FN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FN,t,r)}static $(){return["TeamPluginsTableMarketplace|1 id 3|2 name 9"]}}class KN extends T{constructor(t){super(),this.state=Ye.UNSPECIFIED,this.toolCountIncomplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KN).fromBinary(t,r)}static fromJson(t,r){return(new KN).fromJson(t,r)}static fromJsonString(t,r){return(new KN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KN,t,r)}static $(){return["TeamPluginsTableToolAccess|1 state #0|2 allowed_tool_count 5?|3 tool_count_incomplete 8",Ye]}}class zN extends T{constructor(t){super(),this.mcpServers=0,this.skills=0,this.rules=0,this.commands=0,this.subagents=0,this.hooks=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zN).fromBinary(t,r)}static fromJson(t,r){return(new zN).fromJson(t,r)}static fromJsonString(t,r){return(new zN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zN,t,r)}static $(){return["TeamPluginsTableIncludes|1 mcp_servers 5|2 skills 5|3 rules 5|4 commands 5|5 subagents 5|6 hooks 5"]}}class jN extends T{constructor(t){super(),this.kind=Ze.UNSPECIFIED,this.toolAccess="",this.tools=[],this.coversOtherServers=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jN).fromBinary(t,r)}static fromJson(t,r){return(new jN).fromJson(t,r)}static fromJsonString(t,r){return(new jN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jN,t,r)}static $(){return["TeamPluginsTableRule|1 kind #0|2 name 9?|3 server_url_pattern 9?|4 command_pattern 9?|5 tool_access 9|6 tools 9*|7 covers_other_servers 8",Ze]}}class HN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HN).fromBinary(t,r)}static fromJson(t,r){return(new HN).fromJson(t,r)}static fromJsonString(t,r){return(new HN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HN,t,r)}static $(){return["TeamPluginsTableServerAccess|1 access #0|2 rule #1",KN,jN]}}class WN extends T{constructor(t){super(),this.serverId=n.protoInt64.zero,this.name="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WN).fromBinary(t,r)}static fromJson(t,r){return(new WN).fromJson(t,r)}static fromJsonString(t,r){return(new WN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WN,t,r)}static $(){return["TeamPluginsTableServer|1 server_id 3|2 name 9|3 type 9|4 url 9?|5 total_tool_count 5?|6 local #0|7 cloud #0",HN]}}class QN extends T{constructor(t){super(),this.key="",this.kind=Xe.UNSPECIFIED,this.title="",this.servers=[],this.totalToolCountIncomplete=!1,this.teamMarketplaceIds=[],this.installMode=Ve.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QN).fromBinary(t,r)}static fromJson(t,r){return(new QN).fromJson(t,r)}static fromJsonString(t,r){return(new QN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QN,t,r)}static $(){return["TeamPluginsTableRow|1 key 9|2 kind #0|3 plugin_id 3?|4 server_id 3?|5 title 9|6 logo_url 9?|7 includes #1|8 servers #2*|9 local #3|10 cloud #3|11 total_tool_count 5?|12 total_tool_count_incomplete 8|13 team_marketplace_ids 3*|14 install_mode #4",Xe,zN,WN,KN,Ve]}}class VN extends T{constructor(t){super(),this.description="",this.mcpServers=[],this.skills=[],this.subagents=[],this.rules=[],this.commands=[],this.hooks=[],this.variableNames=[],this.hasConfiguredVariables=!1,this.hasTeamConfiguredVariables=!1,this.teamScopeInstalled=!1,this.canManageTeamPlugins=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VN).fromBinary(t,r)}static fromJson(t,r){return(new VN).fromJson(t,r)}static fromJsonString(t,r){return(new VN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VN,t,r)}static $(){return["InstalledPluginDetail|1 summary #0|2 description 9|3 publisher #1|4 mcp_servers #2*|5 skills #3*|6 subagents #4*|7 rules #5*|8 commands #6*|9 hooks #7*|10 repository_url 9?|11 variable_names 9*|12 has_configured_variables 8|13 has_team_configured_variables 8|14 team_scope_installed 8|15 can_manage_team_plugins 8",MN,XN,BO,wO,yO,qO,IO,SO]}}class XN extends T{constructor(t){super(),this.isVerified=!1,this.isUserOwned=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XN).fromBinary(t,r)}static fromJson(t,r){return(new XN).fromJson(t,r)}static fromJsonString(t,r){return(new XN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XN,t,r)}static $(){return["InstalledPluginPublisher|1 is_verified 8|2 is_user_owned 8"]}}class YN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YN).fromBinary(t,r)}static fromJson(t,r){return(new YN).fromJson(t,r)}static fromJsonString(t,r){return(new YN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YN,t,r)}static $(){return["ListStorefrontPluginsRequest"]}}class ZN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZN).fromBinary(t,r)}static fromJson(t,r){return(new ZN).fromJson(t,r)}static fromJsonString(t,r){return(new ZN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZN,t,r)}static $(){return["StorefrontMarketplace|1 id 3|2 name 9|3 display_name 9?|4 user_id 5?|5 team_id 5?|6 plugin_ids 3*"]}}class tG extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.publisherIsUserOwned=!1,this.marketplaceId=n.protoInt64.zero,this.curatedCategoryKeys=[],this.tags=[],this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tG).fromBinary(t,r)}static fromJson(t,r){return(new tG).fromJson(t,r)}static fromJsonString(t,r){return(new tG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tG,t,r)}static $(){return["StorefrontPlugin|1 id 3|2 name 9|3 display_name 9|4 description 9|5 logo_url 9?|6 publisher_name 9?|7 publisher_display_name 9?|8 publisher_logo_url 9?|9 publisher_is_user_owned 8|10 marketplace_id 3|11 curated_category_keys 9*|12 tags 9*|13 updated_at 3"]}}class rG extends T{constructor(t){super(),this.marketplaces=[],this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rG).fromBinary(t,r)}static fromJson(t,r){return(new rG).fromJson(t,r)}static fromJsonString(t,r){return(new rG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rG,t,r)}static $(){return["ListStorefrontPluginsResponse|1 marketplaces #0*|2 plugins #1*",ZN,tG]}}class eG extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eG).fromBinary(t,r)}static fromJson(t,r){return(new eG).fromJson(t,r)}static fromJsonString(t,r){return(new eG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eG,t,r)}static $(){return["PluginRef|1 name 9|2 marketplace_name 9?"]}}class nG extends T{constructor(t){super(),this.refs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nG).fromBinary(t,r)}static fromJson(t,r){return(new nG).fromJson(t,r)}static fromJsonString(t,r){return(new nG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nG,t,r)}static $(){return["ResolvePluginsByRefRequest|1 refs #0*|2 supports_backend_content 8?",eG]}}class sG extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sG).fromBinary(t,r)}static fromJson(t,r){return(new sG).fromJson(t,r)}static fromJsonString(t,r){return(new sG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sG,t,r)}static $(){return["ResolvePluginsByRefResponse|1 plugins #0*",PO]}}class iG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iG).fromBinary(t,r)}static fromJson(t,r){return(new iG).fromJson(t,r)}static fromJsonString(t,r){return(new iG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iG,t,r)}static $(){return["ListMarketplacesRequest"]}}class oG extends T{constructor(t){super(),this.marketplaces=[],this.bitbucketDataCenterImportAvailable=!1,this.bitbucketServerHostsNeedingLink=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oG).fromBinary(t,r)}static fromJson(t,r){return(new oG).fromJson(t,r)}static fromJsonString(t,r){return(new oG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oG,t,r)}static $(){return["ListMarketplacesResponse|1 marketplaces #0*|2 bitbucket_data_center_import_available 8|3 bitbucket_server_hosts_needing_link 9*",JO]}}class aG extends T{constructor(t){super(),this.name="",this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aG).fromBinary(t,r)}static fromJson(t,r){return(new aG).fromJson(t,r)}static fromJsonString(t,r){return(new aG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aG,t,r)}static $(){return["AddMarketplaceRequest|1 name 9|2 git_url 9|3 git_ref 9?|4 display_name 9?|5 description 9?|6 team_id 5?|7 auto_reindex 8?"]}}class uG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uG).fromBinary(t,r)}static fromJson(t,r){return(new uG).fromJson(t,r)}static fromJsonString(t,r){return(new uG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uG,t,r)}static $(){return["AddMarketplaceResponse|1 marketplace #0",JO]}}class cG extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cG).fromBinary(t,r)}static fromJson(t,r){return(new cG).fromJson(t,r)}static fromJsonString(t,r){return(new cG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cG,t,r)}static $(){return["GetOrCreateDefaultTeamMarketplaceRequest|1 team_id 5"]}}class lG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lG).fromBinary(t,r)}static fromJson(t,r){return(new lG).fromJson(t,r)}static fromJsonString(t,r){return(new lG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lG,t,r)}static $(){return["GetOrCreateDefaultTeamMarketplaceResponse|1 marketplace_id 3"]}}class mG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mG).fromBinary(t,r)}static fromJson(t,r){return(new mG).fromJson(t,r)}static fromJsonString(t,r){return(new mG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mG,t,r)}static $(){return["UpdateMarketplaceRequest|1 marketplace_id 3|2 name 9?|3 description 9?|4 auto_reindex 8?|5 team_id 5?|6 display_name 9?|7 allow_user_publish 8?"]}}class fG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fG).fromBinary(t,r)}static fromJson(t,r){return(new fG).fromJson(t,r)}static fromJsonString(t,r){return(new fG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fG,t,r)}static $(){return["UpdateMarketplaceResponse|1 marketplace #0",JO]}}class dG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dG).fromBinary(t,r)}static fromJson(t,r){return(new dG).fromJson(t,r)}static fromJsonString(t,r){return(new dG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dG,t,r)}static $(){return["RemoveMarketplaceRequest|1 marketplace_id 3|2 team_id 5?"]}}class pG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pG).fromBinary(t,r)}static fromJson(t,r){return(new pG).fromJson(t,r)}static fromJsonString(t,r){return(new pG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pG,t,r)}static $(){return["RemoveMarketplaceResponse|1 success 8"]}}class hG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hG).fromBinary(t,r)}static fromJson(t,r){return(new hG).fromJson(t,r)}static fromJsonString(t,r){return(new hG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hG,t,r)}static $(){return["RefreshMarketplaceRequest|1 marketplace_id 3|2 team_id 5?"]}}class gG extends T{constructor(t){super(),this.pluginsIndexed=0,this.pluginsUpdated=0,this.pluginsDeprecated=0,this.deprecatedPluginNames=[],this.errors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gG).fromBinary(t,r)}static fromJson(t,r){return(new gG).fromJson(t,r)}static fromJsonString(t,r){return(new gG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gG,t,r)}static $(){return["RefreshMarketplaceResponse|1 marketplace #0|2 plugins_indexed 5|3 plugins_updated 5|4 plugins_deprecated 5|5 deprecated_plugin_names 9*|6 errors 9*",JO]}}class _G extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _G).fromBinary(t,r)}static fromJson(t,r){return(new _G).fromJson(t,r)}static fromJsonString(t,r){return(new _G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_G,t,r)}static $(){return["ReindexAndApplyTeamMarketplaceChangesRequest|1 marketplace_id 3|2 git_ref 9?|3 commit_sha 9?|4 team_id 5?"]}}class JG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.plugins=[],this.removedPluginNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JG).fromBinary(t,r)}static fromJson(t,r){return(new JG).fromJson(t,r)}static fromJsonString(t,r){return(new JG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JG,t,r)}static $(){return["ReindexAndApplyTeamMarketplaceChangesResponse|1 marketplace_id 3|2 plugins #0*|3 removed_plugin_names 9*",qG]}}class wG extends T{constructor(t){super(),this.gitUrl="",this.gitRef="",this.marketplaceName="",this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wG).fromBinary(t,r)}static fromJson(t,r){return(new wG).fromJson(t,r)}static fromJsonString(t,r){return(new wG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wG,t,r)}static $(){return["RegisterMarketplaceAndPluginsRequest|1 git_url 9|2 git_ref 9|3 marketplace_name 9|4 plugins #0*|5 team_id 5?|6 commit_sha 9?",yG]}}class yG extends T{constructor(t){super(),this.name="",this.description="",this.version="",this.gitPath="",this.gitUrl="",this.gitRef="",this.displayName="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yG).fromBinary(t,r)}static fromJson(t,r){return(new yG).fromJson(t,r)}static fromJsonString(t,r){return(new yG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yG,t,r)}static $(){return["RegisterPluginEntry|1 name 9|2 description 9|3 version 9|4 git_path 9|5 git_url 9|6 git_ref 9|7 display_name 9|8 skills #0*|9 subagents #1*|10 hooks #2*|11 rules #3*|12 mcp_servers #4*|13 commands #5*|14 logo_url 9?|15 variables #6|16 min_client_versions #7?",wO,yO,SO,qO,BO,IO,n.Struct,bO]}}class SG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SG).fromBinary(t,r)}static fromJson(t,r){return(new SG).fromJson(t,r)}static fromJsonString(t,r){return(new SG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SG,t,r)}static $(){return["RegisterMarketplaceAndPluginsResponse|1 marketplace_id 3|2 plugins #0*",qG]}}class qG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qG).fromBinary(t,r)}static fromJson(t,r){return(new qG).fromJson(t,r)}static fromJsonString(t,r){return(new qG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qG,t,r)}static $(){return["RegisteredPlugin|1 plugin_id 3|2 name 9"]}}class BG extends T{constructor(t){super(),this.principalKind=tn.UNSPECIFIED,this.principalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BG).fromBinary(t,r)}static fromJson(t,r){return(new BG).fromJson(t,r)}static fromJsonString(t,r){return(new BG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BG,t,r)}static $(){return["MarketplaceAccessGrant|1 principal_kind #0|2 principal_id 9",tn]}}class IG extends T{constructor(t){super(),this.directoryGroupIds=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.accessGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IG).fromBinary(t,r)}static fromJson(t,r){return(new IG).fromJson(t,r)}static fromJsonString(t,r){return(new IG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IG,t,r)}static $(){return["TeamMarketplaceConfig|1 directory_group_ids 3*|2 configured_by 5?|3 created_at 3|4 updated_at 3|5 access_grants #0*",BG]}}class PG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.directoryGroupIds=[],this.accessGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PG).fromBinary(t,r)}static fromJson(t,r){return(new PG).fromJson(t,r)}static fromJsonString(t,r){return(new PG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PG,t,r)}static $(){return["UpdateTeamMarketplaceConfigRequest|1 marketplace_id 3|2 directory_group_ids 3*|3 team_id 5?|4 access_grants #0*|5 sync_access_grants 8?",BG]}}class bG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bG).fromBinary(t,r)}static fromJson(t,r){return(new bG).fromJson(t,r)}static fromJsonString(t,r){return(new bG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bG,t,r)}static $(){return["UpdateTeamMarketplaceConfigResponse|1 marketplace #0",JO]}}class RG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RG).fromBinary(t,r)}static fromJson(t,r){return(new RG).fromJson(t,r)}static fromJsonString(t,r){return(new RG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RG,t,r)}static $(){return["SetTeamMarketplaceRepositoryRequest|1 marketplace_id 3|2 git_url 9|3 git_ref 9?"]}}class vG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vG).fromBinary(t,r)}static fromJson(t,r){return(new vG).fromJson(t,r)}static fromJsonString(t,r){return(new vG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vG,t,r)}static $(){return["SetTeamMarketplaceRepositoryResponse|1 marketplace #0",JO]}}class xG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xG).fromBinary(t,r)}static fromJson(t,r){return(new xG).fromJson(t,r)}static fromJsonString(t,r){return(new xG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xG,t,r)}static $(){return["SetMarketplaceOriginDistributionRequest|1 marketplace_id 3|2 team_id 5?|3 enabled 8"]}}class kG extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kG).fromBinary(t,r)}static fromJson(t,r){return(new kG).fromJson(t,r)}static fromJsonString(t,r){return(new kG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kG,t,r)}static $(){return["SetMarketplaceOriginDistributionResponse|1 enabled 8"]}}class EG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EG).fromBinary(t,r)}static fromJson(t,r){return(new EG).fromJson(t,r)}static fromJsonString(t,r){return(new EG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EG,t,r)}static $(){return["GetMarketplaceOriginDistributionStatusRequest|1 marketplace_id 3|2 team_id 5?"]}}class CG extends T{constructor(t){super(),this.enabled=!1,this.initialSyncComplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CG).fromBinary(t,r)}static fromJson(t,r){return(new CG).fromJson(t,r)}static fromJsonString(t,r){return(new CG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CG,t,r)}static $(){return["GetMarketplaceOriginDistributionStatusResponse|1 enabled 8|2 initial_sync_complete 8"]}}class TG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.installMode=rn.OPTIONAL,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TG).fromBinary(t,r)}static fromJson(t,r){return(new TG).fromJson(t,r)}static fromJsonString(t,r){return(new TG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TG,t,r)}static $(){return["TeamMarketplacePluginPolicy|1 plugin_id 3|2 install_mode #0|3 configured_by 5?|4 created_at 3|5 updated_at 3",rn]}}class UG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.policies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UG).fromBinary(t,r)}static fromJson(t,r){return(new UG).fromJson(t,r)}static fromJsonString(t,r){return(new UG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UG,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesRequest|1 marketplace_id 3|2 policies #0*|3 team_id 5?|4 mcp_server_plugin_id 3?",AG]}}class AG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.installMode=rn.OPTIONAL,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AG).fromBinary(t,r)}static fromJson(t,r){return(new AG).fromJson(t,r)}static fromJsonString(t,r){return(new AG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AG,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesRequest.Policy|1 plugin_id 3|2 install_mode #0",rn]}}class $G extends T{constructor(t){super(),this.policies=[],this.mcpServers=[],this.addedTeamServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $G).fromBinary(t,r)}static fromJson(t,r){return(new $G).fromJson(t,r)}static fromJsonString(t,r){return(new $G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($G,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesResponse|1 policies #0*|2 mcp_servers #1*|3 added_team_servers #1*",TG,qN]}}class MG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.pluginId=n.protoInt64.zero,this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MG).fromBinary(t,r)}static fromJson(t,r){return(new MG).fromJson(t,r)}static fromJsonString(t,r){return(new MG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MG,t,r)}static $(){return["SetTeamMarketplacePluginPolicyVariablesRequest|1 marketplace_id 3|2 plugin_id 3|3 variables #0|4 team_id 5?|5 cleared_secret_names 9*",n.Struct]}}class OG extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OG).fromBinary(t,r)}static fromJson(t,r){return(new OG).fromJson(t,r)}static fromJsonString(t,r){return(new OG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OG,t,r)}static $(){return["CompleteSharepointOauthRequest|1 code 9|2 state 9"]}}class DG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DG).fromBinary(t,r)}static fromJson(t,r){return(new DG).fromJson(t,r)}static fromJsonString(t,r){return(new DG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DG,t,r)}static $(){return["CompleteSharepointOauthResponse"]}}class NG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NG).fromBinary(t,r)}static fromJson(t,r){return(new NG).fromJson(t,r)}static fromJsonString(t,r){return(new NG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NG,t,r)}static $(){return["GetTeamSharepointConnectorRequest|1 team_id 5?"]}}class GG extends T{constructor(t){super(),this.connected=!1,this.signedIn=!1,this.applicationPermissions=!1,this.connectorId="",this.writeExists=!1,this.writeConnectorId="",this.writeNeedsSignIn=!1,this.writeConnected=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GG).fromBinary(t,r)}static fromJson(t,r){return(new GG).fromJson(t,r)}static fromJsonString(t,r){return(new GG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GG,t,r)}static $(){return["GetTeamSharepointConnectorResponse|1 connected 8|2 signed_in 8|3 application_permissions 8|4 connector_id 9|5 write_exists 8|6 write_connector_id 9|7 write_needs_sign_in 8|8 write_connected 8"]}}class LG extends T{constructor(t){super(),this.connectorId="",this.allowedSiteIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LG).fromBinary(t,r)}static fromJson(t,r){return(new LG).fromJson(t,r)}static fromJsonString(t,r){return(new LG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LG,t,r)}static $(){return["SetTeamSharepointAllowedSitesRequest|1 team_id 5?|2 connector_id 9|3 allowed_site_ids 9*"]}}class FG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FG).fromBinary(t,r)}static fromJson(t,r){return(new FG).fromJson(t,r)}static fromJsonString(t,r){return(new FG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FG,t,r)}static $(){return["SetTeamSharepointAllowedSitesResponse"]}}class KG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KG).fromBinary(t,r)}static fromJson(t,r){return(new KG).fromJson(t,r)}static fromJsonString(t,r){return(new KG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KG,t,r)}static $(){return["DisconnectTeamSharepointRequest|1 team_id 5?"]}}class zG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zG).fromBinary(t,r)}static fromJson(t,r){return(new zG).fromJson(t,r)}static fromJsonString(t,r){return(new zG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zG,t,r)}static $(){return["DisconnectTeamSharepointResponse"]}}class jG extends T{constructor(t){super(),this.teamId=0,this.marketplaceId=n.protoInt64.zero,this.pluginId=n.protoInt64.zero,this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jG).fromBinary(t,r)}static fromJson(t,r){return(new jG).fromJson(t,r)}static fromJsonString(t,r){return(new jG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jG,t,r)}static $(){return["SaveTeamPluginServerSettingsRequest|1 team_id 5|2 marketplace_id 3|3 plugin_id 3|4 variables #0?|5 access #1?|6 cleared_secret_names 9*",n.Struct,HG]}}class HG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HG).fromBinary(t,r)}static fromJson(t,r){return(new HG).fromJson(t,r)}static fromJsonString(t,r){return(new HG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HG,t,r)}static $(){return["TeamPluginServerAccess|1 server_url 9?|2 command 9?|3 local #0?|4 cloud #0?",Q_]}}class WG extends T{constructor(t){super(),this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WG).fromBinary(t,r)}static fromJson(t,r){return(new WG).fromJson(t,r)}static fromJsonString(t,r){return(new WG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WG,t,r)}static $(){return["SaveTeamPluginServerSettingsResponse|1 variables #0?|2 cleared_secret_names 9*",QG]}}class QG extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QG).fromBinary(t,r)}static fromJson(t,r){return(new QG).fromJson(t,r)}static fromJsonString(t,r){return(new QG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QG,t,r)}static $(){return["SetTeamMarketplacePluginPolicyVariablesResponse|1 auth_url 9?|2 admin_consent_url 9?|3 connector_id 9?|4 mcp_servers #0*",qN]}}class VG extends T{constructor(t){super(),this.pluginIds=[],this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VG).fromBinary(t,r)}static fromJson(t,r){return(new VG).fromJson(t,r)}static fromJsonString(t,r){return(new VG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VG,t,r)}static $(){return["LinkPluginsToTeamMarketplaceRequest|1 plugin_ids 9*|2 marketplace_id 3"]}}class XG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XG).fromBinary(t,r)}static fromJson(t,r){return(new XG).fromJson(t,r)}static fromJsonString(t,r){return(new XG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XG,t,r)}static $(){return["LinkPluginsToTeamMarketplaceResponse|1 success 8"]}}class YG extends T{constructor(t){super(),this.pluginIds=[],this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YG).fromBinary(t,r)}static fromJson(t,r){return(new YG).fromJson(t,r)}static fromJsonString(t,r){return(new YG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YG,t,r)}static $(){return["UnlinkPluginsFromTeamMarketplaceRequest|1 plugin_ids 9*|2 marketplace_id 3"]}}class ZG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZG).fromBinary(t,r)}static fromJson(t,r){return(new ZG).fromJson(t,r)}static fromJsonString(t,r){return(new ZG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZG,t,r)}static $(){return["UnlinkPluginsFromTeamMarketplaceResponse|1 success 8"]}}class tL extends T{constructor(t){super(),this.repoUrl="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tL).fromBinary(t,r)}static fromJson(t,r){return(new tL).fromJson(t,r)}static fromJsonString(t,r){return(new tL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tL,t,r)}static $(){return["GetPullRequestForBranchRequest|1 repo_url 9|2 branch_name 9|3 skip_cache 8?"]}}class rL extends T{constructor(t){super(),this.prUrl="",this.prUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rL).fromBinary(t,r)}static fromJson(t,r){return(new rL).fromJson(t,r)}static fromJsonString(t,r){return(new rL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rL,t,r)}static $(){return["GetPullRequestForBranchResponse|1 pr_url 9|2 pr_urls 9*"]}}class eL extends T{constructor(t){super(),this.supportedCanvasKits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eL).fromBinary(t,r)}static fromJson(t,r){return(new eL).fromJson(t,r)}static fromJsonString(t,r){return(new eL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eL,t,r)}static $(){return["GetManagedSkillsRequest|1 supported_canvas_kits 9*|2 bc_id 9?"]}}class nL extends T{constructor(t){super(),this.id="",this.description="",this.content="",this.disableModelInvocation=!1,this.environments=[],this.disabledEnvironments=[],this.resources={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nL).fromBinary(t,r)}static fromJson(t,r){return(new nL).fromJson(t,r)}static fromJsonString(t,r){return(new nL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nL,t,r)}static $(){return["ManagedSkill|1 id 9|2 description 9|3 content 9|4 disable_model_invocation 8|5 environments 9*|6 disabled_environments 9*|7 enabled 8?|8 custom_mode #0?|9 resources 9,9",E.o7L]}}class sL extends T{constructor(t){super(),this.skills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sL).fromBinary(t,r)}static fromJson(t,r){return(new sL).fromJson(t,r)}static fromJsonString(t,r){return(new sL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sL,t,r)}static $(){return["GetManagedSkillsResponse|1 skills #0*",nL]}}class iL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iL).fromBinary(t,r)}static fromJson(t,r){return(new iL).fromJson(t,r)}static fromJsonString(t,r){return(new iL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iL,t,r)}static $(){return["GetCursorUserStateRequest"]}}class oL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oL).fromBinary(t,r)}static fromJson(t,r){return(new oL).fromJson(t,r)}static fromJsonString(t,r){return(new oL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oL,t,r)}static $(){return["GetCursorUserStateResponse|1 state #0",n.Struct]}}class aL extends T{constructor(t){super(),this.jobRole="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aL).fromBinary(t,r)}static fromJson(t,r){return(new aL).fromJson(t,r)}static fromJsonString(t,r){return(new aL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aL,t,r)}static $(){return["SetJobDataRequest|1 job_role 9|2 use_case 9?"]}}class uL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uL).fromBinary(t,r)}static fromJson(t,r){return(new uL).fromJson(t,r)}static fromJsonString(t,r){return(new uL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uL,t,r)}static $(){return["SetJobDataResponse"]}}class cL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cL).fromBinary(t,r)}static fromJson(t,r){return(new cL).fromJson(t,r)}static fromJsonString(t,r){return(new cL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cL,t,r)}static $(){return["GetJiraInstallUrlRequest"]}}class lL extends T{constructor(t){super(),this.installUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lL).fromBinary(t,r)}static fromJson(t,r){return(new lL).fromJson(t,r)}static fromJsonString(t,r){return(new lL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lL,t,r)}static $(){return["GetJiraInstallUrlResponse|1 install_url 9"]}}class mL extends T{constructor(t){super(),this.installationId="",this.teamId=0,this.installToken="",this.setupCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mL).fromBinary(t,r)}static fromJson(t,r){return(new mL).fromJson(t,r)}static fromJsonString(t,r){return(new mL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mL,t,r)}static $(){return["LinkJiraInstallationRequest|1 installation_id 9|2 team_id 5|3 install_token 9|4 setup_code 9"]}}class fL extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fL).fromBinary(t,r)}static fromJson(t,r){return(new fL).fromJson(t,r)}static fromJsonString(t,r){return(new fL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fL,t,r)}static $(){return["LinkJiraInstallationResponse|1 success 8"]}}class dL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dL).fromBinary(t,r)}static fromJson(t,r){return(new dL).fromJson(t,r)}static fromJsonString(t,r){return(new dL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dL,t,r)}static $(){return["GetJiraStatusRequest|1 team_id 5"]}}class pL extends T{constructor(t){super(),this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pL).fromBinary(t,r)}static fromJson(t,r){return(new pL).fromJson(t,r)}static fromJsonString(t,r){return(new pL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pL,t,r)}static $(){return["GetJiraStatusResponse|1 status 9|2 site_name 9?|3 base_url 9?"]}}class hL extends T{constructor(t){super(),this.installationId="",this.cloudId="",this.siteName="",this.baseUrl="",this.linkedUserCount=0,this.activeTaskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hL).fromBinary(t,r)}static fromJson(t,r){return(new hL).fromJson(t,r)}static fromJsonString(t,r){return(new hL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hL,t,r)}static $(){return["JiraInstallation|1 installation_id 9|2 cloud_id 9|3 site_name 9|4 base_url 9|5 linked_user_count 13|6 active_task_count 13"]}}class gL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gL).fromBinary(t,r)}static fromJson(t,r){return(new gL).fromJson(t,r)}static fromJsonString(t,r){return(new gL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gL,t,r)}static $(){return["ListJiraInstallationsRequest|1 team_id 5"]}}class _L extends T{constructor(t){super(),this.installations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _L).fromBinary(t,r)}static fromJson(t,r){return(new _L).fromJson(t,r)}static fromJsonString(t,r){return(new _L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_L,t,r)}static $(){return["ListJiraInstallationsResponse|1 installations #0*",hL]}}class JL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JL).fromBinary(t,r)}static fromJson(t,r){return(new JL).fromJson(t,r)}static fromJsonString(t,r){return(new JL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JL,t,r)}static $(){return["GetBitbucketForgeStatusRequest|1 team_id 5"]}}class wL extends T{constructor(t){super(),this.status="",this.workspaces=[],this.multiWorkspaceEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wL).fromBinary(t,r)}static fromJson(t,r){return(new wL).fromJson(t,r)}static fromJsonString(t,r){return(new wL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wL,t,r)}static $(){return["GetBitbucketForgeStatusResponse|1 status 9|2 workspace_name 9?|3 base_url 9?|4 workspace_settings_url 9?|5 pending_workspace_name 9?|6 pending_workspace_settings_url 9?|7 workspaces #0*|8 multi_workspace_enabled 8|9 access_role 9?|10 can_disconnect 8?|11 can_share 8?|12 cloud_id 9?",yL]}}class yL extends T{constructor(t){super(),this.cloudId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yL).fromBinary(t,r)}static fromJson(t,r){return(new yL).fromJson(t,r)}static fromJsonString(t,r){return(new yL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yL,t,r)}static $(){return["BitbucketForgeWorkspace|1 workspace_name 9?|2 base_url 9?|3 cloud_id 9|4 access_role 9?|5 can_disconnect 8?|6 can_share 8?"]}}class SL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SL).fromBinary(t,r)}static fromJson(t,r){return(new SL).fromJson(t,r)}static fromJsonString(t,r){return(new SL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SL,t,r)}static $(){return["DisconnectJiraRequest|1 team_id 5|2 cloud_id 9?"]}}class qL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qL).fromBinary(t,r)}static fromJson(t,r){return(new qL).fromJson(t,r)}static fromJsonString(t,r){return(new qL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qL,t,r)}static $(){return["DisconnectJiraResponse"]}}class BL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BL).fromBinary(t,r)}static fromJson(t,r){return(new BL).fromJson(t,r)}static fromJsonString(t,r){return(new BL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BL,t,r)}static $(){return["DisconnectBitbucketForgeRequest|1 team_id 5|2 cloud_id 9?"]}}class IL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IL).fromBinary(t,r)}static fromJson(t,r){return(new IL).fromJson(t,r)}static fromJsonString(t,r){return(new IL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IL,t,r)}static $(){return["DisconnectBitbucketForgeResponse"]}}class PL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PL).fromBinary(t,r)}static fromJson(t,r){return(new PL).fromJson(t,r)}static fromJsonString(t,r){return(new PL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsRequest|1 team_id 5|2 cloud_id 9"]}}class bL extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bL).fromBinary(t,r)}static fromJson(t,r){return(new bL).fromJson(t,r)}static fromJsonString(t,r){return(new bL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsResponse|1 teams #0*",RL]}}class RL extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.granted=!1,this.stale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RL).fromBinary(t,r)}static fromJson(t,r){return(new RL).fromJson(t,r)}static fromJsonString(t,r){return(new RL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsResponse.Team|1 team_id 5|2 team_name 9|3 granted 8|4 stale 8"]}}class vL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vL).fromBinary(t,r)}static fromJson(t,r){return(new vL).fromJson(t,r)}static fromJsonString(t,r){return(new vL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vL,t,r)}static $(){return["GrantBitbucketForgeInstallationRequest|1 team_id 5|2 cloud_id 9|3 target_team_id 5"]}}class xL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xL).fromBinary(t,r)}static fromJson(t,r){return(new xL).fromJson(t,r)}static fromJsonString(t,r){return(new xL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xL,t,r)}static $(){return["GrantBitbucketForgeInstallationResponse"]}}class kL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kL).fromBinary(t,r)}static fromJson(t,r){return(new kL).fromJson(t,r)}static fromJsonString(t,r){return(new kL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kL,t,r)}static $(){return["RevokeBitbucketForgeInstallationRequest|1 team_id 5|2 cloud_id 9|3 target_team_id 5"]}}class EL extends T{constructor(t){super(),this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EL).fromBinary(t,r)}static fromJson(t,r){return(new EL).fromJson(t,r)}static fromJsonString(t,r){return(new EL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EL,t,r)}static $(){return["RevokeBitbucketForgeInstallationResponse|1 revoked 8"]}}class CL extends T{constructor(t){super(),this.id="",this.key="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CL).fromBinary(t,r)}static fromJson(t,r){return(new CL).fromJson(t,r)}static fromJsonString(t,r){return(new CL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CL,t,r)}static $(){return["JiraProject|1 id 9|2 key 9|3 name 9"]}}class TL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TL).fromBinary(t,r)}static fromJson(t,r){return(new TL).fromJson(t,r)}static fromJsonString(t,r){return(new TL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TL,t,r)}static $(){return["GetJiraProjectsRequest|1 team_id 5|2 cloud_id 9?"]}}class UL extends T{constructor(t){super(),this.projects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UL).fromBinary(t,r)}static fromJson(t,r){return(new UL).fromJson(t,r)}static fromJsonString(t,r){return(new UL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UL,t,r)}static $(){return["GetJiraProjectsResponse|1 projects #0*|2 error 9?",CL]}}class AL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AL).fromBinary(t,r)}static fromJson(t,r){return(new AL).fromJson(t,r)}static fromJsonString(t,r){return(new AL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AL,t,r)}static $(){return["GetJiraTeamSettingsRequest|1 team_id 5|2 cloud_id 9?"]}}class $L extends T{constructor(t){super(),this.requireUserAuth=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $L).fromBinary(t,r)}static fromJson(t,r){return(new $L).fromJson(t,r)}static fromJsonString(t,r){return(new $L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($L,t,r)}static $(){return["GetJiraTeamSettingsResponse|1 require_user_auth 8"]}}class ML extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ML).fromBinary(t,r)}static fromJson(t,r){return(new ML).fromJson(t,r)}static fromJsonString(t,r){return(new ML).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ML,t,r)}static $(){return["UpdateJiraTeamSettingsRequest|1 team_id 5|2 require_user_auth 8?|7 cloud_id 9?"]}}class OL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OL).fromBinary(t,r)}static fromJson(t,r){return(new OL).fromJson(t,r)}static fromJsonString(t,r){return(new OL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OL,t,r)}static $(){return["UpdateJiraTeamSettingsResponse"]}}class DL extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DL).fromBinary(t,r)}static fromJson(t,r){return(new DL).fromJson(t,r)}static fromJsonString(t,r){return(new DL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DL,t,r)}static $(){return["JiraRoutingRule|1 id 3|2 repo 9|3 rule_text 9"]}}class NL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NL).fromBinary(t,r)}static fromJson(t,r){return(new NL).fromJson(t,r)}static fromJsonString(t,r){return(new NL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NL,t,r)}static $(){return["GetJiraRoutingRulesRequest|1 team_id 5"]}}class GL extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GL).fromBinary(t,r)}static fromJson(t,r){return(new GL).fromJson(t,r)}static fromJsonString(t,r){return(new GL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GL,t,r)}static $(){return["GetJiraRoutingRulesResponse|1 rules #0*",DL]}}class LL extends T{constructor(t){super(),this.teamId=0,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LL).fromBinary(t,r)}static fromJson(t,r){return(new LL).fromJson(t,r)}static fromJsonString(t,r){return(new LL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LL,t,r)}static $(){return["CreateJiraRoutingRuleRequest|1 team_id 5|2 repo 9|3 rule_text 9"]}}class FL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FL).fromBinary(t,r)}static fromJson(t,r){return(new FL).fromJson(t,r)}static fromJsonString(t,r){return(new FL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FL,t,r)}static $(){return["CreateJiraRoutingRuleResponse|1 rule #0",DL]}}class KL extends T{constructor(t){super(),this.teamId=0,this.ruleId=n.protoInt64.zero,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KL).fromBinary(t,r)}static fromJson(t,r){return(new KL).fromJson(t,r)}static fromJsonString(t,r){return(new KL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KL,t,r)}static $(){return["UpdateJiraRoutingRuleRequest|1 team_id 5|2 rule_id 3|3 repo 9|4 rule_text 9"]}}class zL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zL).fromBinary(t,r)}static fromJson(t,r){return(new zL).fromJson(t,r)}static fromJsonString(t,r){return(new zL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zL,t,r)}static $(){return["UpdateJiraRoutingRuleResponse|1 rule #0",DL]}}class jL extends T{constructor(t){super(),this.teamId=0,this.ruleId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jL).fromBinary(t,r)}static fromJson(t,r){return(new jL).fromJson(t,r)}static fromJsonString(t,r){return(new jL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jL,t,r)}static $(){return["DeleteJiraRoutingRuleRequest|1 team_id 5|2 rule_id 3"]}}class HL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HL).fromBinary(t,r)}static fromJson(t,r){return(new HL).fromJson(t,r)}static fromJsonString(t,r){return(new HL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HL,t,r)}static $(){return["DeleteJiraRoutingRuleResponse"]}}class WL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",this.linkToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WL).fromBinary(t,r)}static fromJson(t,r){return(new WL).fromJson(t,r)}static fromJsonString(t,r){return(new WL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WL,t,r)}static $(){return["LinkJiraUserRequest|1 cloud_id 9|2 jira_account_id 9|3 link_token 9"]}}class QL extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QL).fromBinary(t,r)}static fromJson(t,r){return(new QL).fromJson(t,r)}static fromJsonString(t,r){return(new QL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QL,t,r)}static $(){return["LinkJiraUserResponse|1 success 8"]}}class VL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VL).fromBinary(t,r)}static fromJson(t,r){return(new VL).fromJson(t,r)}static fromJsonString(t,r){return(new VL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VL,t,r)}static $(){return["ListJiraUserLinksRequest"]}}class XL extends T{constructor(t){super(),this.links=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XL).fromBinary(t,r)}static fromJson(t,r){return(new XL).fromJson(t,r)}static fromJsonString(t,r){return(new XL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XL,t,r)}static $(){return["ListJiraUserLinksResponse|1 links #0*",YL]}}class YL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",this.siteName="",this.baseUrl="",this.linkedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YL).fromBinary(t,r)}static fromJson(t,r){return(new YL).fromJson(t,r)}static fromJsonString(t,r){return(new YL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YL,t,r)}static $(){return["JiraUserLink|1 cloud_id 9|2 jira_account_id 9|3 site_name 9|4 base_url 9|5 linked_at_ms 3"]}}class ZL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZL).fromBinary(t,r)}static fromJson(t,r){return(new ZL).fromJson(t,r)}static fromJsonString(t,r){return(new ZL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZL,t,r)}static $(){return["UnlinkJiraUserRequest|1 cloud_id 9|2 jira_account_id 9"]}}class tF extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tF).fromBinary(t,r)}static fromJson(t,r){return(new tF).fromJson(t,r)}static fromJsonString(t,r){return(new tF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tF,t,r)}static $(){return["UnlinkJiraUserResponse|1 success 8"]}}class rF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rF).fromBinary(t,r)}static fromJson(t,r){return(new rF).fromJson(t,r)}static fromJsonString(t,r){return(new rF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rF,t,r)}static $(){return["ListFinancialConnectionsRequest"]}}class eF extends T{constructor(t){super(),this.connectionId="",this.provider="",this.providerConnectionId="",this.status="",this.hasSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eF).fromBinary(t,r)}static fromJson(t,r){return(new eF).fromJson(t,r)}static fromJsonString(t,r){return(new eF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eF,t,r)}static $(){return["FinancialConnection|1 connection_id 9|2 provider 9|3 provider_connection_id 9|4 status 9|5 created_at #0|6 updated_at #0|7 has_synced 8|8 institution_id 9?|9 institution_name 9?|10 institution_logo 9?|11 institution_primary_color 9?|12 institution_icon_url 9?",n.Timestamp]}}class nF extends T{constructor(t){super(),this.connections=[],this.pendingLinkSessions=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nF).fromBinary(t,r)}static fromJson(t,r){return(new nF).fromJson(t,r)}static fromJsonString(t,r){return(new nF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nF,t,r)}static $(){return["ListFinancialConnectionsResponse|1 connections #0*|2 pending_link_sessions 13|3 connect_url 9?",eF]}}class sF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sF).fromBinary(t,r)}static fromJson(t,r){return(new sF).fromJson(t,r)}static fromJsonString(t,r){return(new sF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sF,t,r)}static $(){return["ListFinancialAccountsRequest"]}}class iF extends T{constructor(t){super(),this.accountId="",this.connectionId="",this.accountClass="",this.connectionStatus="",this.hasSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iF).fromBinary(t,r)}static fromJson(t,r){return(new iF).fromJson(t,r)}static fromJsonString(t,r){return(new iF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iF,t,r)}static $(){return["FinancialAccount|1 account_id 9|2 connection_id 9|3 account_class 9|4 name 9?|5 official_name 9?|6 mask 9?|7 type 9?|8 subtype 9?|9 current_balance 9?|10 available_balance 9?|11 currency 9?|12 institution_id 9?|13 institution_name 9?|14 connection_status 9|15 has_synced 8"]}}class oF extends T{constructor(t){super(),this.accounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oF).fromBinary(t,r)}static fromJson(t,r){return(new oF).fromJson(t,r)}static fromJsonString(t,r){return(new oF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oF,t,r)}static $(){return["ListFinancialAccountsResponse|1 accounts #0*",iF]}}class aF extends T{constructor(t){super(),this.connectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aF).fromBinary(t,r)}static fromJson(t,r){return(new aF).fromJson(t,r)}static fromJsonString(t,r){return(new aF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aF,t,r)}static $(){return["DeleteFinancialConnectionRequest|1 connection_id 9"]}}class uF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uF).fromBinary(t,r)}static fromJson(t,r){return(new uF).fromJson(t,r)}static fromJsonString(t,r){return(new uF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uF,t,r)}static $(){return["DeleteFinancialConnectionResponse"]}}class cF extends T{constructor(t){super(),this.returnTo="",this.repairLinkedBank=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cF).fromBinary(t,r)}static fromJson(t,r){return(new cF).fromJson(t,r)}static fromJsonString(t,r){return(new cF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cF,t,r)}static $(){return["StartFinancialLinkRequest|1 return_to 9|2 repair_linked_bank 8"]}}class lF extends T{constructor(t){super(),this.hostedLinkUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lF).fromBinary(t,r)}static fromJson(t,r){return(new lF).fromJson(t,r)}static fromJsonString(t,r){return(new lF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lF,t,r)}static $(){return["StartFinancialLinkResponse|1 hosted_link_url 9|2 expires_at #0?",n.Timestamp]}}class mF extends T{constructor(t){super(),this.uuid="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mF).fromBinary(t,r)}static fromJson(t,r){return(new mF).fromJson(t,r)}static fromJsonString(t,r){return(new mF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest|1 uuid 9|2 set_oauth_app #0 action|3 clear_oauth_app #1 action",fF,dF]}}class fF extends T{constructor(t){super(),this.clientId="",this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fF).fromBinary(t,r)}static fromJson(t,r){return(new fF).fromJson(t,r)}static fromJsonString(t,r){return(new fF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest.SetOauthApp|1 client_id 9|2 client_secret 9"]}}class dF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dF).fromBinary(t,r)}static fromJson(t,r){return(new dF).fromJson(t,r)}static fromJsonString(t,r){return(new dF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest.ClearOauthApp"]}}class pF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pF).fromBinary(t,r)}static fromJson(t,r){return(new pF).fromJson(t,r)}static fromJsonString(t,r){return(new pF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppResponse"]}}class hF extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hF).fromBinary(t,r)}static fromJson(t,r){return(new hF).fromJson(t,r)}static fromJsonString(t,r){return(new hF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hF,t,r)}static $(){return["DisconnectBitbucketServerAccountRequest|1 uuid 9"]}}class gF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gF).fromBinary(t,r)}static fromJson(t,r){return(new gF).fromJson(t,r)}static fromJsonString(t,r){return(new gF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gF,t,r)}static $(){return["DisconnectBitbucketServerAccountResponse"]}}class _F extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _F).fromBinary(t,r)}static fromJson(t,r){return(new _F).fromJson(t,r)}static fromJsonString(t,r){return(new _F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_F,t,r)}static $(){return["ListUnpaidUsageInvoicesRequest|1 team_id 5?"]}}class JF extends T{constructor(t){super(),this.invoices=[],this.needsTeamAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JF).fromBinary(t,r)}static fromJson(t,r){return(new JF).fromJson(t,r)}static fromJsonString(t,r){return(new JF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JF,t,r)}static $(){return["ListUnpaidUsageInvoicesResponse|1 invoices #0*|2 needs_team_admin 8",aR]}}class wF extends T{constructor(t){super(),this.clientSecret="",this.publishableKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wF).fromBinary(t,r)}static fromJson(t,r){return(new wF).fromJson(t,r)}static fromJsonString(t,r){return(new wF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wF,t,r)}static $(){return["XaiPaymentChallenge|1 client_secret 9|2 publishable_key 9"]}}class yF extends T{constructor(t){super(),this.checkId="",this.joinerName="",this.cardholderUnknown=!1,this.expiresAt="",this.approved=!1,this.adminChange=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yF).fromBinary(t,r)}static fromJson(t,r){return(new yF).fromJson(t,r)}static fromJsonString(t,r){return(new yF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yF,t,r)}static $(){return["XaiSeatPaymentCheck|1 check_id 9|2 joiner_name 9|3 payment_challenge #0|4 cardholder_unknown 8|5 expires_at 9|6 approved 8|7 admin_change 8",wF]}}class SF extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SF).fromBinary(t,r)}static fromJson(t,r){return(new SF).fromJson(t,r)}static fromJsonString(t,r){return(new SF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SF,t,r)}static $(){return["ListGrokApiKeyAclOptionsRequest|1 team_id 5"]}}class qF extends T{constructor(t){super(),this.modelsStatus=BF.UNSPECIFIED,this.chatModels=[],this.imageModels=[],this.videoModels=[],this.embeddingModels=[],this.endpointsStatus=BF.UNSPECIFIED,this.endpoints=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qF).fromBinary(t,r)}static fromJson(t,r){return(new qF).fromJson(t,r)}static fromJsonString(t,r){return(new qF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qF,t,r)}static $(){return["ListGrokApiKeyAclOptionsResponse|1 models_status #0|2 chat_models 9*|3 image_models 9*|4 video_models 9*|5 embedding_models 9*|6 endpoints_status #0|7 endpoints 9*",BF]}}var BF=(0,a.QT)(n.proto3,C,"ListGrokApiKeyAclOptionsResponse.CatalogStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"NOT_OFFERED"],[3,"FAILED"]],1);class IF extends T{constructor(t){super(),this.batchId="",this.name="",this.createApiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IF).fromBinary(t,r)}static fromJson(t,r){return(new IF).fromJson(t,r)}static fromJsonString(t,r){return(new IF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IF,t,r)}static $(){return["GrokBatch|1 batch_id 9|2 name 9|3 create_time #0|4 expire_time #0|5 create_api_key_id 9|6 cancel_time #0|7 cancel_by_xai_message 9?|8 state #1|9 cost_breakdown #2|10 input_file_id 9?",n.Timestamp,PF,bF]}}class PF extends T{constructor(t){super(),this.numRequests=n.protoInt64.zero,this.numPending=n.protoInt64.zero,this.numSuccess=n.protoInt64.zero,this.numError=n.protoInt64.zero,this.numCancelled=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PF).fromBinary(t,r)}static fromJson(t,r){return(new PF).fromJson(t,r)}static fromJsonString(t,r){return(new PF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PF,t,r)}static $(){return["GrokBatchState|1 num_requests 3|2 num_pending 3|3 num_success 3|4 num_error 3|5 num_cancelled 3"]}}class bF extends T{constructor(t){super(),this.totalCostUsdTicks=n.protoInt64.zero,this.endpointCosts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bF).fromBinary(t,r)}static fromJson(t,r){return(new bF).fromJson(t,r)}static fromJsonString(t,r){return(new bF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bF,t,r)}static $(){return["GrokBatchCostBreakdown|1 total_cost_usd_ticks 3|2 endpoint_costs #0*|3 calculation_time #1",RF,n.Timestamp]}}class RF extends T{constructor(t){super(),this.endpoint="",this.costUsdTicks=n.protoInt64.zero,this.requestCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RF).fromBinary(t,r)}static fromJson(t,r){return(new RF).fromJson(t,r)}static fromJsonString(t,r){return(new RF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RF,t,r)}static $(){return["GrokBatchEndpointCost|1 endpoint 9|2 cost_usd_ticks 3|3 request_count 3"]}}class vF extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.filter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vF).fromBinary(t,r)}static fromJson(t,r){return(new vF).fromJson(t,r)}static fromJsonString(t,r){return(new vF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vF,t,r)}static $(){return["ListGrokBatchesRequest|1 team_id 5|2 limit 5|3 pagination_token 9?|4 filter 9"]}}class xF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.batches=[],this.canManage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xF).fromBinary(t,r)}static fromJson(t,r){return(new xF).fromJson(t,r)}static fromJsonString(t,r){return(new xF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xF,t,r)}static $(){return["ListGrokBatchesResponse|1 team_linked 8|2 user_linked 8|3 batches #0*|4 pagination_token 9?|5 can_manage 8",IF]}}class kF extends T{constructor(t){super(),this.teamId=0,this.batchId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kF).fromBinary(t,r)}static fromJson(t,r){return(new kF).fromJson(t,r)}static fromJsonString(t,r){return(new kF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kF,t,r)}static $(){return["GetGrokBatchRequest|1 team_id 5|2 batch_id 9"]}}class EF extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EF).fromBinary(t,r)}static fromJson(t,r){return(new EF).fromJson(t,r)}static fromJsonString(t,r){return(new EF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EF,t,r)}static $(){return["GetGrokBatchResponse|1 batch #0|2 can_manage 8|3 team_linked 8|4 user_linked 8",IF]}}class CF extends T{constructor(t){super(),this.batchRequestId="",this.endpoint="",this.model="",this.state=en.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CF).fromBinary(t,r)}static fromJson(t,r){return(new CF).fromJson(t,r)}static fromJsonString(t,r){return(new CF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CF,t,r)}static $(){return["GrokBatchRequestMetadata|1 batch_request_id 9|2 endpoint 9|3 model 9|4 state #0|5 create_time #1|6 finish_time #1|7 request_preview 9?|8 cost_usd_ticks 3?",en,n.Timestamp]}}class TF extends T{constructor(t){super(),this.teamId=0,this.batchId="",this.limit=0,this.status=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TF).fromBinary(t,r)}static fromJson(t,r){return(new TF).fromJson(t,r)}static fromJsonString(t,r){return(new TF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TF,t,r)}static $(){return["ListGrokBatchRequestsRequest|1 team_id 5|2 batch_id 9|3 limit 5|4 pagination_token 9?|5 status #0*",en]}}class UF extends T{constructor(t){super(),this.batchRequestMetadata=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UF).fromBinary(t,r)}static fromJson(t,r){return(new UF).fromJson(t,r)}static fromJsonString(t,r){return(new UF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UF,t,r)}static $(){return["ListGrokBatchRequestsResponse|1 batch_request_metadata #0*|2 pagination_token 9?",CF]}}class AF extends T{constructor(t){super(),this.teamId=0,this.batchId="",this.batchRequestId="",this.format=nn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AF).fromBinary(t,r)}static fromJson(t,r){return(new AF).fromJson(t,r)}static fromJsonString(t,r){return(new AF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AF,t,r)}static $(){return["GetGrokBatchRequestResultRequest|1 team_id 5|2 batch_id 9|3 batch_request_id 9|4 format #0",nn]}}class $F extends T{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $F).fromBinary(t,r)}static fromJson(t,r){return(new $F).fromJson(t,r)}static fromJsonString(t,r){return(new $F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($F,t,r)}static $(){return["GrokFormattedBatchRequest|1 json 9 data|2 request_b64 9 data"]}}class MF extends T{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MF).fromBinary(t,r)}static fromJson(t,r){return(new MF).fromJson(t,r)}static fromJsonString(t,r){return(new MF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MF,t,r)}static $(){return["GrokFormattedBatchResult|1 json 9 data|2 result_b64 9 data"]}}class OF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OF).fromBinary(t,r)}static fromJson(t,r){return(new OF).fromJson(t,r)}static fromJsonString(t,r){return(new OF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OF,t,r)}static $(){return["GetGrokBatchRequestResultResponse|1 request #0|2 result #1",$F,MF]}}class DF extends T{constructor(t){super(),this.name="",this.inputFileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DF).fromBinary(t,r)}static fromJson(t,r){return(new DF).fromJson(t,r)}static fromJsonString(t,r){return(new DF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DF,t,r)}static $(){return["GrokCreateBatchParams|1 name 9|2 input_file_id 9"]}}class NF extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NF).fromBinary(t,r)}static fromJson(t,r){return(new NF).fromJson(t,r)}static fromJsonString(t,r){return(new NF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NF,t,r)}static $(){return["CreateGrokBatchRequest|1 team_id 5|2 api_key_id 9|3 request #0",DF]}}class GF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GF).fromBinary(t,r)}static fromJson(t,r){return(new GF).fromJson(t,r)}static fromJsonString(t,r){return(new GF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GF,t,r)}static $(){return["CreateGrokBatchResponse|1 batch #0",IF]}}class LF extends T{constructor(t){super(),this.teamId=0,this.batchId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LF).fromBinary(t,r)}static fromJson(t,r){return(new LF).fromJson(t,r)}static fromJsonString(t,r){return(new LF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LF,t,r)}static $(){return["CancelGrokBatchRequest|1 team_id 5|2 batch_id 9"]}}class FF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FF).fromBinary(t,r)}static fromJson(t,r){return(new FF).fromJson(t,r)}static fromJsonString(t,r){return(new FF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FF,t,r)}static $(){return["CancelGrokBatchResponse|1 batch #0",IF]}}class KF extends T{constructor(t){super(),this.voiceId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KF).fromBinary(t,r)}static fromJson(t,r){return(new KF).fromJson(t,r)}static fromJsonString(t,r){return(new KF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KF,t,r)}static $(){return["GrokBuiltInVoice|1 voice_id 9|2 name 9|3 language 9?|4 gender 9?|5 age 9?"]}}class zF extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zF).fromBinary(t,r)}static fromJson(t,r){return(new zF).fromJson(t,r)}static fromJsonString(t,r){return(new zF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zF,t,r)}static $(){return["ListGrokBuiltInVoicesRequest|1 team_id 5"]}}class jF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.voices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jF).fromBinary(t,r)}static fromJson(t,r){return(new jF).fromJson(t,r)}static fromJsonString(t,r){return(new jF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jF,t,r)}static $(){return["ListGrokBuiltInVoicesResponse|1 team_linked 8|2 user_linked 8|3 voices #0*",KF]}}class HF extends T{constructor(t){super(),this.voiceId="",this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HF).fromBinary(t,r)}static fromJson(t,r){return(new HF).fromJson(t,r)}static fromJsonString(t,r){return(new HF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HF,t,r)}static $(){return["GrokCustomVoice|1 voice_id 9|2 name 9?|3 description 9?|4 gender 9?|5 accent 9?|6 age 9?|7 language 9?|8 use_case 9?|9 tone 9?|10 created_at 9"]}}class WF extends T{constructor(t){super(),this.teamId=0,this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WF).fromBinary(t,r)}static fromJson(t,r){return(new WF).fromJson(t,r)}static fromJsonString(t,r){return(new WF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WF,t,r)}static $(){return["ListGrokCustomVoicesRequest|1 team_id 5|2 limit 5|3 pagination_token 9?"]}}class QF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.voices=[],this.totalCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QF).fromBinary(t,r)}static fromJson(t,r){return(new QF).fromJson(t,r)}static fromJsonString(t,r){return(new QF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QF,t,r)}static $(){return["ListGrokCustomVoicesResponse|1 team_linked 8|2 user_linked 8|3 voices #0*|4 pagination_token 9?|5 total_count 3|6 cap 3?",HF]}}class VF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VF).fromBinary(t,r)}static fromJson(t,r){return(new VF).fromJson(t,r)}static fromJsonString(t,r){return(new VF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VF,t,r)}static $(){return["GrokCustomVoicePatch|1 name 9?|2 gender 9?|3 age 9?|4 tone 9?|5 language 9?"]}}class XF extends T{constructor(t){super(),this.teamId=0,this.voiceId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XF).fromBinary(t,r)}static fromJson(t,r){return(new XF).fromJson(t,r)}static fromJsonString(t,r){return(new XF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XF,t,r)}static $(){return["UpdateGrokCustomVoiceRequest|1 team_id 5|2 voice_id 9|3 patch #0",VF]}}class YF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YF).fromBinary(t,r)}static fromJson(t,r){return(new YF).fromJson(t,r)}static fromJsonString(t,r){return(new YF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YF,t,r)}static $(){return["UpdateGrokCustomVoiceResponse|1 voice #0",HF]}}class ZF extends T{constructor(t){super(),this.teamId=0,this.voiceId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZF).fromBinary(t,r)}static fromJson(t,r){return(new ZF).fromJson(t,r)}static fromJsonString(t,r){return(new ZF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZF,t,r)}static $(){return["DeleteGrokCustomVoiceRequest|1 team_id 5|2 voice_id 9"]}}class tK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tK).fromBinary(t,r)}static fromJson(t,r){return(new tK).fromJson(t,r)}static fromJsonString(t,r){return(new tK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tK,t,r)}static $(){return["DeleteGrokCustomVoiceResponse"]}}class rK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rK).fromBinary(t,r)}static fromJson(t,r){return(new rK).fromJson(t,r)}static fromJsonString(t,r){return(new rK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rK,t,r)}static $(){return["GetGrokVoiceCloningAccessRequest|1 team_id 5"]}}class eK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.allowed=!1,this.restriction=sn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eK).fromBinary(t,r)}static fromJson(t,r){return(new eK).fromJson(t,r)}static fromJsonString(t,r){return(new eK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eK,t,r)}static $(){return["GetGrokVoiceCloningAccessResponse|1 team_linked 8|2 user_linked 8|3 allowed 8|4 restriction #0",sn]}}class nK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nK).fromBinary(t,r)}static fromJson(t,r){return(new nK).fromJson(t,r)}static fromJsonString(t,r){return(new nK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nK,t,r)}static $(){return["GetGrokVoiceClonePassphraseRequest|1 team_id 5"]}}class sK extends T{constructor(t){super(),this.passphrase="",this.passphraseToken="",this.expiresInSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sK).fromBinary(t,r)}static fromJson(t,r){return(new sK).fromJson(t,r)}static fromJsonString(t,r){return(new sK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sK,t,r)}static $(){return["GetGrokVoiceClonePassphraseResponse|1 passphrase 9|2 passphrase_token 9|3 expires_in_seconds 5"]}}class iK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iK).fromBinary(t,r)}static fromJson(t,r){return(new iK).fromJson(t,r)}static fromJsonString(t,r){return(new iK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iK,t,r)}static $(){return["GrokVoiceCloneDetails|1 name 9?|2 description 9?|3 gender 9?|4 age 9?|5 tone 9?|6 accent 9?|7 language 9?|8 use_case 9?"]}}class oK extends T{constructor(t){super(),this.data=new Uint8Array(0),this.contentType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oK).fromBinary(t,r)}static fromJson(t,r){return(new oK).fromJson(t,r)}static fromJsonString(t,r){return(new oK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oK,t,r)}static $(){return["GrokVoiceCloneAudio|1 data 12|2 content_type 9"]}}class aK extends T{constructor(t){super(),this.teamId=0,this.passphraseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aK).fromBinary(t,r)}static fromJson(t,r){return(new aK).fromJson(t,r)}static fromJsonString(t,r){return(new aK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aK,t,r)}static $(){return["CloneGrokCustomVoiceRequest|1 team_id 5|2 passphrase_audio #0|3 voice_audio #0|4 passphrase_token 9|5 details #1",oK,iK]}}class uK extends T{constructor(t){super(),this.failure=on.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uK).fromBinary(t,r)}static fromJson(t,r){return(new uK).fromJson(t,r)}static fromJsonString(t,r){return(new uK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uK,t,r)}static $(){return["CloneGrokCustomVoiceResponse|1 voice #0|2 failure #1",HF,on]}}class cK extends T{constructor(t){super(),this.fileId="",this.name="",this.sizeBytes=n.protoInt64.zero,this.contentType="",this.hash="",this.collections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cK).fromBinary(t,r)}static fromJson(t,r){return(new cK).fromJson(t,r)}static fromJsonString(t,r){return(new cK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cK,t,r)}static $(){return["GrokFile|1 file_id 9|2 name 9|3 size_bytes 3|4 content_type 9|5 created_at #0|6 expires_at #0|7 hash 9|8 upload_status 9?|9 upload_error_message 9?|10 processing_status 9?|11 file_path 9?|12 public_url 9?|13 public_url_expires_at #0?|14 description 9?|15 collections #1*",n.Timestamp,lK]}}class lK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lK).fromBinary(t,r)}static fromJson(t,r){return(new lK).fromJson(t,r)}static fromJsonString(t,r){return(new lK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lK,t,r)}static $(){return["GrokFileCollectionInfo|1 collection_id 9|2 collection_name 9"]}}class mK extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=an.UNSPECIFIED,this.filter="",this.includeCollections=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mK).fromBinary(t,r)}static fromJson(t,r){return(new mK).fromJson(t,r)}static fromJsonString(t,r){return(new mK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mK,t,r)}static $(){return["ListGrokFilesRequest|1 team_id 5|2 limit 5|3 next_token 9?|4 order #0|5 sort_by #1|6 filter 9|7 include_collections 8",un,an]}}class fK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.files=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fK).fromBinary(t,r)}static fromJson(t,r){return(new fK).fromJson(t,r)}static fromJsonString(t,r){return(new fK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fK,t,r)}static $(){return["ListGrokFilesResponse|1 team_linked 8|2 user_linked 8|3 files #0*|4 next_token 9?|5 can_manage 8|6 zero_data_retention 8",cK]}}class dK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dK).fromBinary(t,r)}static fromJson(t,r){return(new dK).fromJson(t,r)}static fromJsonString(t,r){return(new dK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dK,t,r)}static $(){return["GetGrokFileRequest|1 team_id 5|2 file_id 9"]}}class pK extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pK).fromBinary(t,r)}static fromJson(t,r){return(new pK).fromJson(t,r)}static fromJsonString(t,r){return(new pK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pK,t,r)}static $(){return["GetGrokFileResponse|1 file #0|2 can_manage 8|3 team_linked 8|4 user_linked 8|5 zero_data_retention 8",cK]}}class hK extends T{constructor(t){super(),this.teamId=0,this.fileId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hK).fromBinary(t,r)}static fromJson(t,r){return(new hK).fromJson(t,r)}static fromJsonString(t,r){return(new hK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hK,t,r)}static $(){return["UpdateGrokFileRequest|1 team_id 5|2 file_id 9|3 name 9"]}}class gK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gK).fromBinary(t,r)}static fromJson(t,r){return(new gK).fromJson(t,r)}static fromJsonString(t,r){return(new gK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gK,t,r)}static $(){return["UpdateGrokFileResponse|1 file #0",cK]}}class _K extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _K).fromBinary(t,r)}static fromJson(t,r){return(new _K).fromJson(t,r)}static fromJsonString(t,r){return(new _K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_K,t,r)}static $(){return["DeleteGrokFileRequest|1 team_id 5|2 file_id 9"]}}class JK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JK).fromBinary(t,r)}static fromJson(t,r){return(new JK).fromJson(t,r)}static fromJsonString(t,r){return(new JK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JK,t,r)}static $(){return["DeleteGrokFileResponse"]}}class wK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wK).fromBinary(t,r)}static fromJson(t,r){return(new wK).fromJson(t,r)}static fromJsonString(t,r){return(new wK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wK,t,r)}static $(){return["CreateGrokFilePublicUrlRequest|1 team_id 5|2 file_id 9|3 expires_after_seconds 3?"]}}class yK extends T{constructor(t){super(),this.publicUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yK).fromBinary(t,r)}static fromJson(t,r){return(new yK).fromJson(t,r)}static fromJsonString(t,r){return(new yK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yK,t,r)}static $(){return["CreateGrokFilePublicUrlResponse|1 public_url 9|2 expires_at #0?",n.Timestamp]}}class SK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SK).fromBinary(t,r)}static fromJson(t,r){return(new SK).fromJson(t,r)}static fromJsonString(t,r){return(new SK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SK,t,r)}static $(){return["RevokeGrokFilePublicUrlRequest|1 team_id 5|2 file_id 9"]}}class qK extends T{constructor(t){super(),this.fileId="",this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qK).fromBinary(t,r)}static fromJson(t,r){return(new qK).fromJson(t,r)}static fromJsonString(t,r){return(new qK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qK,t,r)}static $(){return["RevokeGrokFilePublicUrlResponse|1 file_id 9|2 revoked 8|3 public_url 9?"]}}class BK extends T{constructor(t){super(),this.modelName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BK).fromBinary(t,r)}static fromJson(t,r){return(new BK).fromJson(t,r)}static fromJsonString(t,r){return(new BK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BK,t,r)}static $(){return["GrokCollectionIndexConfiguration|1 model_name 9"]}}class IK extends T{constructor(t){super(),this.maxChunkSizeTokens=0,this.chunkOverlapTokens=0,this.encodingName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IK).fromBinary(t,r)}static fromJson(t,r){return(new IK).fromJson(t,r)}static fromJsonString(t,r){return(new IK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IK,t,r)}static $(){return["GrokCollectionTokensConfiguration|1 max_chunk_size_tokens 5|2 chunk_overlap_tokens 5|3 encoding_name 9"]}}class PK extends T{constructor(t){super(),this.maxChunkSizeChars=0,this.chunkOverlapChars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PK).fromBinary(t,r)}static fromJson(t,r){return(new PK).fromJson(t,r)}static fromJsonString(t,r){return(new PK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PK,t,r)}static $(){return["GrokCollectionCharsConfiguration|1 max_chunk_size_chars 5|2 chunk_overlap_chars 5"]}}class bK extends T{constructor(t){super(),this.maxChunkSizeBytes=0,this.chunkOverlapBytes=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bK).fromBinary(t,r)}static fromJson(t,r){return(new bK).fromJson(t,r)}static fromJsonString(t,r){return(new bK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bK,t,r)}static $(){return["GrokCollectionBytesConfiguration|1 max_chunk_size_bytes 5|2 chunk_overlap_bytes 5"]}}class RK extends T{constructor(t){super(),this.stripWhitespace=!1,this.injectNameIntoChunks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RK).fromBinary(t,r)}static fromJson(t,r){return(new RK).fromJson(t,r)}static fromJsonString(t,r){return(new RK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RK,t,r)}static $(){return["GrokCollectionChunkConfiguration|1 tokens_configuration #0|2 strip_whitespace 8|3 inject_name_into_chunks 8|4 bytes_configuration #1|5 chars_configuration #2",IK,bK,PK]}}class vK extends T{constructor(t){super(),this.key="",this.required=!1,this.injectIntoChunk=!1,this.unique=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vK).fromBinary(t,r)}static fromJson(t,r){return(new vK).fromJson(t,r)}static fromJsonString(t,r){return(new vK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vK,t,r)}static $(){return["GrokCollectionFieldDefinition|1 key 9|2 required 8|3 inject_into_chunk 8|4 unique 8|5 description 9?"]}}class xK extends T{constructor(t){super(),this.operation=cn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xK).fromBinary(t,r)}static fromJson(t,r){return(new xK).fromJson(t,r)}static fromJsonString(t,r){return(new xK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xK,t,r)}static $(){return["GrokCollectionFieldDefinitionUpdate|1 field_definition #0|2 operation #1",vK,cn]}}class kK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",this.documentsCount=0,this.fieldDefinitions=[],this.totalFileSize=n.protoInt64.zero,this.disableRagLookup=!1,this.effectivePrivilege=0,this.isOwned=!1,this.ownerTeamId="",this.isEstimated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kK).fromBinary(t,r)}static fromJson(t,r){return(new kK).fromJson(t,r)}static fromJsonString(t,r){return(new kK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kK,t,r)}static $(){return["GrokCollection|1 collection_id 9|2 collection_name 9|3 created_at #0|4 index_configuration #1|5 chunk_configuration #2|6 documents_count 5|7 field_definitions #3*|8 collection_description 9?|9 total_file_size 3|10 cloned_from_id 9?|11 lineage_group_id 9?|12 clone_version 9?|13 disable_rag_lookup 8|14 effective_privilege 5|15 is_owned 8|16 owner_team_id 9|17 is_estimated 8",n.Timestamp,BK,RK,vK]}}class EK extends T{constructor(t){super(),this.fields={},this.status=mn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EK).fromBinary(t,r)}static fromJson(t,r){return(new EK).fromJson(t,r)}static fromJsonString(t,r){return(new EK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EK,t,r)}static $(){return["GrokCollectionDocument|1 file_metadata #0|2 fields 9,9|3 status #1|4 error_message 9?|5 last_indexed_at #2|6 chunk_count 5?|7 chunks_processed_count 3?",cK,mn,n.Timestamp]}}class CK extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=ln.UNSPECIFIED,this.filter="",this.includeShared=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CK).fromBinary(t,r)}static fromJson(t,r){return(new CK).fromJson(t,r)}static fromJsonString(t,r){return(new CK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CK,t,r)}static $(){return["ListGrokCollectionsRequest|1 team_id 5|2 limit 5|3 pagination_token 9?|4 order #0|5 sort_by #1|6 filter 9|7 include_shared 8",un,ln]}}class TK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.collections=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TK).fromBinary(t,r)}static fromJson(t,r){return(new TK).fromJson(t,r)}static fromJsonString(t,r){return(new TK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TK,t,r)}static $(){return["ListGrokCollectionsResponse|1 team_linked 8|2 user_linked 8|3 collections #0*|4 pagination_token 9?|5 can_manage 8|6 zero_data_retention 8",kK]}}class UK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UK).fromBinary(t,r)}static fromJson(t,r){return(new UK).fromJson(t,r)}static fromJsonString(t,r){return(new UK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UK,t,r)}static $(){return["GetGrokCollectionRequest|1 team_id 5|2 collection_id 9"]}}class AK extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AK).fromBinary(t,r)}static fromJson(t,r){return(new AK).fromJson(t,r)}static fromJsonString(t,r){return(new AK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AK,t,r)}static $(){return["GetGrokCollectionResponse|1 collection #0|2 can_manage 8|3 team_linked 8|4 user_linked 8|5 zero_data_retention 8",kK]}}class $K extends T{constructor(t){super(),this.teamId=0,this.collectionName="",this.fieldDefinitions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $K).fromBinary(t,r)}static fromJson(t,r){return(new $K).fromJson(t,r)}static fromJsonString(t,r){return(new $K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($K,t,r)}static $(){return["CreateGrokCollectionRequest|1 team_id 5|2 collection_name 9|3 collection_description 9?|4 index_configuration #0|5 chunk_configuration #1|6 field_definitions #2*",BK,RK,vK]}}class MK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MK).fromBinary(t,r)}static fromJson(t,r){return(new MK).fromJson(t,r)}static fromJsonString(t,r){return(new MK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MK,t,r)}static $(){return["CreateGrokCollectionResponse|1 collection #0",kK]}}class OK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.disableRagLookup=!1,this.fieldDefinitionUpdates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OK).fromBinary(t,r)}static fromJson(t,r){return(new OK).fromJson(t,r)}static fromJsonString(t,r){return(new OK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OK,t,r)}static $(){return["UpdateGrokCollectionRequest|1 team_id 5|2 collection_id 9|3 collection_name 9?|4 collection_description 9?|5 disable_rag_lookup 8|6 field_definition_updates #0*|7 chunk_configuration #1",xK,RK]}}class DK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DK).fromBinary(t,r)}static fromJson(t,r){return(new DK).fromJson(t,r)}static fromJsonString(t,r){return(new DK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DK,t,r)}static $(){return["UpdateGrokCollectionResponse|1 collection #0",kK]}}class NK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NK).fromBinary(t,r)}static fromJson(t,r){return(new NK).fromJson(t,r)}static fromJsonString(t,r){return(new NK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NK,t,r)}static $(){return["DeleteGrokCollectionRequest|1 team_id 5|2 collection_id 9"]}}class GK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GK).fromBinary(t,r)}static fromJson(t,r){return(new GK).fromJson(t,r)}static fromJsonString(t,r){return(new GK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GK,t,r)}static $(){return["DeleteGrokCollectionResponse"]}}class LK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LK).fromBinary(t,r)}static fromJson(t,r){return(new LK).fromJson(t,r)}static fromJsonString(t,r){return(new LK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LK,t,r)}static $(){return["CloneGrokCollectionRequest|1 team_id 5|2 collection_id 9|3 collection_name 9?"]}}class FK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FK).fromBinary(t,r)}static fromJson(t,r){return(new FK).fromJson(t,r)}static fromJsonString(t,r){return(new FK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FK,t,r)}static $(){return["CloneGrokCollectionResponse|1 collection #0",kK]}}class KK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KK).fromBinary(t,r)}static fromJson(t,r){return(new KK).fromJson(t,r)}static fromJsonString(t,r){return(new KK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KK,t,r)}static $(){return["GenerateGrokCollectionDescriptionRequest|1 team_id 5|2 collection_id 9"]}}class zK extends T{constructor(t){super(),this.collectionDescription="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zK).fromBinary(t,r)}static fromJson(t,r){return(new zK).fromJson(t,r)}static fromJsonString(t,r){return(new zK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zK,t,r)}static $(){return["GenerateGrokCollectionDescriptionResponse|1 collection_description 9"]}}class jK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",this.documentsCount=0,this.disableRagLookup=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jK).fromBinary(t,r)}static fromJson(t,r){return(new jK).fromJson(t,r)}static fromJsonString(t,r){return(new jK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jK,t,r)}static $(){return["GrokRelatedCollection|1 collection_id 9|2 collection_name 9|3 created_at #0|4 cloned_from_id 9?|5 documents_count 5|6 clone_version 9?|7 disable_rag_lookup 8",n.Timestamp]}}class HK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HK).fromBinary(t,r)}static fromJson(t,r){return(new HK).fromJson(t,r)}static fromJsonString(t,r){return(new HK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HK,t,r)}static $(){return["ListRelatedGrokCollectionsRequest|1 team_id 5|2 collection_id 9"]}}class WK extends T{constructor(t){super(),this.lineageGroupId="",this.collections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WK).fromBinary(t,r)}static fromJson(t,r){return(new WK).fromJson(t,r)}static fromJsonString(t,r){return(new WK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WK,t,r)}static $(){return["ListRelatedGrokCollectionsResponse|1 lineage_group_id 9|2 collections #0*",jK]}}class QK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QK).fromBinary(t,r)}static fromJson(t,r){return(new QK).fromJson(t,r)}static fromJsonString(t,r){return(new QK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QK,t,r)}static $(){return["ListGrokCollectionEmbeddingModelsRequest|1 team_id 5"]}}class VK extends T{constructor(t){super(),this.embeddingModels=[],this.chunkConfigEditable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VK).fromBinary(t,r)}static fromJson(t,r){return(new VK).fromJson(t,r)}static fromJsonString(t,r){return(new VK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VK,t,r)}static $(){return["ListGrokCollectionEmbeddingModelsResponse|1 embedding_models 9*|2 chunk_config_editable 8"]}}class XK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=an.UNSPECIFIED,this.filter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XK).fromBinary(t,r)}static fromJson(t,r){return(new XK).fromJson(t,r)}static fromJsonString(t,r){return(new XK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XK,t,r)}static $(){return["ListGrokCollectionDocumentsRequest|1 team_id 5|2 collection_id 9|3 limit 5|4 pagination_token 9?|5 order #0|6 sort_by #1|7 filter 9",un,an]}}class YK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.documents=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YK).fromBinary(t,r)}static fromJson(t,r){return(new YK).fromJson(t,r)}static fromJsonString(t,r){return(new YK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YK,t,r)}static $(){return["ListGrokCollectionDocumentsResponse|1 team_linked 8|2 user_linked 8|3 documents #0*|4 pagination_token 9?|5 can_manage 8|6 zero_data_retention 8",EK]}}class ZK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZK).fromBinary(t,r)}static fromJson(t,r){return(new ZK).fromJson(t,r)}static fromJsonString(t,r){return(new ZK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZK,t,r)}static $(){return["BatchGetGrokCollectionDocumentsRequest|1 team_id 5|2 collection_id 9|3 file_ids 9*"]}}class tz extends T{constructor(t){super(),this.documents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tz).fromBinary(t,r)}static fromJson(t,r){return(new tz).fromJson(t,r)}static fromJsonString(t,r){return(new tz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tz,t,r)}static $(){return["BatchGetGrokCollectionDocumentsResponse|1 documents #0*",EK]}}class rz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",this.fields={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rz).fromBinary(t,r)}static fromJson(t,r){return(new rz).fromJson(t,r)}static fromJsonString(t,r){return(new rz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rz,t,r)}static $(){return["AddGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9|4 fields 9,9"]}}class ez extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ez).fromBinary(t,r)}static fromJson(t,r){return(new ez).fromJson(t,r)}static fromJsonString(t,r){return(new ez).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ez,t,r)}static $(){return["AddGrokCollectionDocumentResponse"]}}class nz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",this.fields={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nz).fromBinary(t,r)}static fromJson(t,r){return(new nz).fromJson(t,r)}static fromJsonString(t,r){return(new nz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nz,t,r)}static $(){return["UpdateGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9|4 name 9?|5 fields 9,9"]}}class sz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sz).fromBinary(t,r)}static fromJson(t,r){return(new sz).fromJson(t,r)}static fromJsonString(t,r){return(new sz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sz,t,r)}static $(){return["UpdateGrokCollectionDocumentResponse|1 document #0",EK]}}class iz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iz).fromBinary(t,r)}static fromJson(t,r){return(new iz).fromJson(t,r)}static fromJsonString(t,r){return(new iz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iz,t,r)}static $(){return["RemoveGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9"]}}class oz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oz).fromBinary(t,r)}static fromJson(t,r){return(new oz).fromJson(t,r)}static fromJsonString(t,r){return(new oz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oz,t,r)}static $(){return["RemoveGrokCollectionDocumentResponse"]}}class az extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new az).fromBinary(t,r)}static fromJson(t,r){return(new az).fromJson(t,r)}static fromJsonString(t,r){return(new az).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(az,t,r)}static $(){return["ReindexGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9"]}}class uz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uz).fromBinary(t,r)}static fromJson(t,r){return(new uz).fromJson(t,r)}static fromJsonString(t,r){return(new uz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uz,t,r)}static $(){return["ReindexGrokCollectionDocumentResponse"]}}class cz extends T{constructor(t){super(),this.teamId=0,this.cluster="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cz).fromBinary(t,r)}static fromJson(t,r){return(new cz).fromJson(t,r)}static fromJsonString(t,r){return(new cz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cz,t,r)}static $(){return["ListGrokModelsRequest|1 team_id 5|2 cluster 9"]}}class lz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.clusters=[],this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lz).fromBinary(t,r)}static fromJson(t,r){return(new lz).fromJson(t,r)}static fromJsonString(t,r){return(new lz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lz,t,r)}static $(){return["ListGrokModelsResponse|1 team_linked 8|2 user_linked 8|3 clusters 9*|4 groups #0*|5 team_tier 5?",mz]}}class mz extends T{constructor(t){super(),this.type=fn.UNSPECIFIED,this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mz).fromBinary(t,r)}static fromJson(t,r){return(new mz).fromJson(t,r)}static fromJsonString(t,r){return(new mz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mz,t,r)}static $(){return["GrokModelGroup|1 type #0|2 models #1*",fn,pz]}}class fz extends T{constructor(t){super(),this.resolution="",this.usdCents=0,this.price=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fz).fromBinary(t,r)}static fromJson(t,r){return(new fz).fromJson(t,r)}static fromJsonString(t,r){return(new fz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fz,t,r)}static $(){return["GrokModelResolutionPrice|1 resolution 9|2 usd_cents 1|3 price 3"]}}class dz extends T{constructor(t){super(),this.outputByResolution=[],this.longContextPricing=!1,this.longContextThresholdTokens=n.protoInt64.zero,this.promptTextTokenPrice=n.protoInt64.zero,this.cachedPromptTokenPrice=n.protoInt64.zero,this.promptTextTokenPriceLongContext=n.protoInt64.zero,this.cachedPromptTokenPriceLongContext=n.protoInt64.zero,this.completionTextTokenPrice=n.protoInt64.zero,this.completionTokenPriceLongContext=n.protoInt64.zero,this.promptTokenPrice=n.protoInt64.zero,this.completionTokenPrice=n.protoInt64.zero,this.imagePrice=n.protoInt64.zero,this.pricePerInputImage=n.protoInt64.zero,this.pricePerInputVideoSecond=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dz).fromBinary(t,r)}static fromJson(t,r){return(new dz).fromJson(t,r)}static fromJsonString(t,r){return(new dz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dz,t,r)}static $(){return["GrokModelPricing|1 input_usd_cents 1?|2 cached_input_usd_cents 1?|3 output_usd_cents 1?|4 image_input_usd_cents 1?|5 video_input_usd_cents 1?|6 output_by_resolution #0*|7 long_context_pricing 8|8 long_context_threshold_tokens 3|9 prompt_text_token_price 3|10 cached_prompt_token_price 3|11 prompt_text_token_price_long_context 3|12 cached_prompt_token_price_long_context 3|13 completion_text_token_price 3|14 completion_token_price_long_context 3|15 prompt_token_price 3|16 completion_token_price 3|17 image_price 3|18 price_per_input_image 3|19 price_per_input_video_second 3",fz]}}class pz extends T{constructor(t){super(),this.name="",this.cluster="",this.showsCluster=!1,this.inputModalities=[],this.outputModalities=[],this.functionCalling=!1,this.structuredOutputs=!1,this.reasoning=!1,this.contextTokens=0,this.rps=n.protoInt64.zero,this.rpm=n.protoInt64.zero,this.tpm=n.protoInt64.zero,this.rph=n.protoInt64.zero,this.rpd=n.protoInt64.zero,this.tier=0,this.batchEnabled=!1,this.voiceEndpoints=[],this.aliases=[],this.supportedReasoningEfforts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pz).fromBinary(t,r)}static fromJson(t,r){return(new pz).fromJson(t,r)}static fromJsonString(t,r){return(new pz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pz,t,r)}static $(){return["GrokModel|1 name 9|2 cluster 9|3 shows_cluster 8|4 input_modalities #0*|5 output_modalities #0*|6 function_calling 8|7 structured_outputs 8|8 reasoning 8|9 context_tokens 5|10 pricing #1|11 rps 3|12 rpm 3|13 tpm 3|14 rph 3|15 rpd 3|16 tier 5|17 rate_limit_config #2|18 batch_enabled 8|19 batch_discount_percent 5?|20 voice_endpoints #3*|21 aliases 9*|22 supported_reasoning_efforts 9*|23 default_reasoning_effort 9?",dn,dz,gz,hz]}}class hz extends T{constructor(t){super(),this.kind=pn.UNSPECIFIED,this.rps=n.protoInt64.zero,this.rpm=n.protoInt64.zero,this.concurrentSessions=n.protoInt64.zero,this.perCharacter=n.protoInt64.zero,this.perAudioSecond=n.protoInt64.zero,this.perAudioSecondStreaming=n.protoInt64.zero,this.realtimeAudioSecondPrice=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hz).fromBinary(t,r)}static fromJson(t,r){return(new hz).fromJson(t,r)}static fromJsonString(t,r){return(new hz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hz,t,r)}static $(){return["GrokVoiceEndpoint|1 kind #0|2 rps 3|3 rpm 3|4 concurrent_sessions 3|5 per_character 3|6 per_audio_second 3|7 per_audio_second_streaming 3|8 realtime_audio_second_price 3",pn]}}class gz extends T{constructor(t){super(),this.queryOffset=n.protoInt64.zero,this.queryBaseRate=n.protoInt64.zero,this.queryMultiplier=n.protoInt64.zero,this.tokenOffset=n.protoInt64.zero,this.tokenBaseRate=n.protoInt64.zero,this.tokenMultiplier=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gz).fromBinary(t,r)}static fromJson(t,r){return(new gz).fromJson(t,r)}static fromJsonString(t,r){return(new gz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gz,t,r)}static $(){return["GrokModelRateLimitConfig|1 query_offset 3|2 query_base_rate 3|3 query_multiplier 3|4 token_offset 3|5 token_base_rate 3|6 token_multiplier 3"]}}class _z extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _z).fromBinary(t,r)}static fromJson(t,r){return(new _z).fromJson(t,r)}static fromJsonString(t,r){return(new _z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_z,t,r)}static $(){return["GetGrokApiKeyAccessRequest|1 team_id 5"]}}class Jz extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jz).fromBinary(t,r)}static fromJson(t,r){return(new Jz).fromJson(t,r)}static fromJsonString(t,r){return(new Jz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jz,t,r)}static $(){return["GetGrokApiKeyPropagationRequest|1 team_id 5|2 api_key_id 9"]}}class wz extends T{constructor(t){super(),this.status=yz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wz).fromBinary(t,r)}static fromJson(t,r){return(new wz).fromJson(t,r)}static fromJsonString(t,r){return(new wz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wz,t,r)}static $(){return["GetGrokApiKeyPropagationResponse|1 status #0",yz]}}var yz=(0,a.QT)(n.proto3,C,"GetGrokApiKeyPropagationResponse.Status",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"PROPAGATED"],[3,"UNKNOWN"]],1);class Sz extends T{constructor(t){super(),this.known=!1,this.canViewApiKeys=!1,this.canCreateApiKeys=!1,this.canViewManagementKeys=!1,this.canCreateManagementKeys=!1,this.canManageFiles=!1,this.allowAllModels=!1,this.allowAllEndpoints=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sz).fromBinary(t,r)}static fromJson(t,r){return(new Sz).fromJson(t,r)}static fromJsonString(t,r){return(new Sz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sz,t,r)}static $(){return["GetGrokApiKeyAccessResponse|1 known 8|2 can_view_api_keys 8|3 can_create_api_keys 8|4 can_view_management_keys 8|5 can_create_management_keys 8|6 can_manage_files 8|7 allow_all_models 8|8 allow_all_endpoints 8|9 personal_plan 8?"]}}class qz extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qz).fromBinary(t,r)}static fromJson(t,r){return(new qz).fromJson(t,r)}static fromJsonString(t,r){return(new qz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qz,t,r)}static $(){return["GetGrokTeamWatermarkingRequest|1 team_id 5"]}}class Bz extends T{constructor(t){super(),this.model="",this.state=Iz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bz).fromBinary(t,r)}static fromJson(t,r){return(new Bz).fromJson(t,r)}static fromJsonString(t,r){return(new Bz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bz,t,r)}static $(){return["GrokWatermarkModel|1 model 9|2 state #0",Iz]}}var Iz=(0,a.QT)(n.proto3,C,"GrokWatermarkModel.State",[[0,"UNSPECIFIED"],[1,"ON"],[2,"OFF"],[3,"STAFF_LOCKED"]],1);class Pz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.canAdminister=!1,this.textModels=[],this.audioModels=[],this.canChange=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pz).fromBinary(t,r)}static fromJson(t,r){return(new Pz).fromJson(t,r)}static fromJsonString(t,r){return(new Pz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pz,t,r)}static $(){return["GetGrokTeamWatermarkingResponse|1 team_linked 8|2 user_linked 8|3 can_administer 8|4 text_models #0*|5 audio_models #0*|6 can_change 8",Bz]}}class bz extends T{constructor(t){super(),this.model="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bz).fromBinary(t,r)}static fromJson(t,r){return(new bz).fromJson(t,r)}static fromJsonString(t,r){return(new bz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bz,t,r)}static $(){return["GrokWatermarkModelChoice|1 model 9|2 enabled 8"]}}class Rz extends T{constructor(t){super(),this.teamId=0,this.textModels=[],this.audioModels=[],this.attestationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rz).fromBinary(t,r)}static fromJson(t,r){return(new Rz).fromJson(t,r)}static fromJsonString(t,r){return(new Rz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rz,t,r)}static $(){return["SetGrokTeamWatermarkingRequest|1 team_id 5|2 text_models #0*|3 audio_models #0*|4 attestation_id 9",bz]}}class vz extends T{constructor(t){super(),this.textModels=[],this.audioModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vz).fromBinary(t,r)}static fromJson(t,r){return(new vz).fromJson(t,r)}static fromJsonString(t,r){return(new vz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vz,t,r)}static $(){return["SetGrokTeamWatermarkingResponse|1 text_models #0*|2 audio_models #0*",Bz]}}class xz extends T{constructor(t){super(),this.teamId=0,this.statusOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xz).fromBinary(t,r)}static fromJson(t,r){return(new xz).fromJson(t,r)}static fromJsonString(t,r){return(new xz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xz,t,r)}static $(){return["GetGrokTeamZdrRequest|1 team_id 5|2 status_only 8"]}}class kz extends T{constructor(t){super(),this.status=Ez.UNSPECIFIED,this.selfServeEligible=!1,this.legacyLocked=!1,this.storedData=Cz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kz).fromBinary(t,r)}static fromJson(t,r){return(new kz).fromJson(t,r)}static fromJsonString(t,r){return(new kz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kz,t,r)}static $(){return["GrokTeamZdr|1 status #0|2 self_serve_eligible 8|3 legacy_locked 8|4 stored_data #1",Ez,Cz]}}var Ez=(0,a.QT)(n.proto3,C,"GrokTeamZdr.Status",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"SELF_SERVE"],[3,"STAFF"]],1),Cz=(0,a.QT)(n.proto3,C,"GrokTeamZdr.StoredData",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"FILES"],[3,"COLLECTIONS"],[4,"FILES_AND_COLLECTIONS"],[5,"CHECK_FAILED"]],1);class Tz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.canAdminister=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tz).fromBinary(t,r)}static fromJson(t,r){return(new Tz).fromJson(t,r)}static fromJsonString(t,r){return(new Tz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tz,t,r)}static $(){return["GetGrokTeamZdrResponse|1 team_linked 8|2 user_linked 8|3 can_administer 8|4 zdr #0",kz]}}class Uz extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,this.termsId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uz).fromBinary(t,r)}static fromJson(t,r){return(new Uz).fromJson(t,r)}static fromJsonString(t,r){return(new Uz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uz,t,r)}static $(){return["SetGrokTeamZdrRequest|1 team_id 5|2 enabled 8|3 terms_id 9"]}}class Az extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Az).fromBinary(t,r)}static fromJson(t,r){return(new Az).fromJson(t,r)}static fromJsonString(t,r){return(new Az).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Az,t,r)}static $(){return["SetGrokTeamZdrResponse|1 zdr #0",kz]}}class $z extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.owningTeamId=0,this.joinedAt=n.protoInt64.zero,this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $z).fromBinary(t,r)}static fromJson(t,r){return(new $z).fromJson(t,r)}static fromJsonString(t,r){return(new $z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($z,t,r)}static $(){return["TeamGroupServiceAccountMember|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5|5 owning_team_name 9?|6 joined_at 3|7 archived 8"]}}class Mz extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mz).fromBinary(t,r)}static fromJson(t,r){return(new Mz).fromJson(t,r)}static fromJsonString(t,r){return(new Mz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mz,t,r)}static $(){return["GetTeamGroupServiceAccountMembersRequest|1 team_id 5|2 group_public_id 9"]}}class Oz extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oz).fromBinary(t,r)}static fromJson(t,r){return(new Oz).fromJson(t,r)}static fromJsonString(t,r){return(new Oz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oz,t,r)}static $(){return["GetTeamGroupServiceAccountMembersResponse|1 service_accounts #0*",$z]}}class Dz extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dz).fromBinary(t,r)}static fromJson(t,r){return(new Dz).fromJson(t,r)}static fromJsonString(t,r){return(new Dz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dz,t,r)}static $(){return["AddTeamGroupServiceAccountsRequest|1 team_id 5|2 group_id 3|3 service_account_ids 9*"]}}class Nz extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nz).fromBinary(t,r)}static fromJson(t,r){return(new Nz).fromJson(t,r)}static fromJsonString(t,r){return(new Nz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nz,t,r)}static $(){return["AddTeamGroupServiceAccountsResponse|1 added_count 5"]}}class Gz extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gz).fromBinary(t,r)}static fromJson(t,r){return(new Gz).fromJson(t,r)}static fromJsonString(t,r){return(new Gz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gz,t,r)}static $(){return["RemoveTeamGroupServiceAccountsRequest|1 team_id 5|2 group_id 3|3 service_account_ids 9*"]}}class Lz extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lz).fromBinary(t,r)}static fromJson(t,r){return(new Lz).fromJson(t,r)}static fromJsonString(t,r){return(new Lz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lz,t,r)}static $(){return["RemoveTeamGroupServiceAccountsResponse|1 removed_count 5"]}}class Fz extends T{constructor(t){super(),this.title="",this.body="",this.supportUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fz).fromBinary(t,r)}static fromJson(t,r){return(new Fz).fromJson(t,r)}static fromJsonString(t,r){return(new Fz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fz,t,r)}static $(){return["SuperGrokHeavyUltraEndedNotice|1 title 9|2 body 9|3 continue_unification_url 9?|4 support_url 9"]}}class Kz extends T{constructor(t){super(),this.allTeams=!1,this.teamIds=[],this.groupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kz).fromBinary(t,r)}static fromJson(t,r){return(new Kz).fromJson(t,r)}static fromJsonString(t,r){return(new Kz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kz,t,r)}static $(){return["PrivateInferenceAssignment|1 all_teams 8|2 team_ids 5*|3 group_ids 3*"]}}class zz extends T{constructor(t){super(),this.bugReportsAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zz).fromBinary(t,r)}static fromJson(t,r){return(new zz).fromJson(t,r)}static fromJsonString(t,r){return(new zz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zz,t,r)}static $(){return["PrivateInferencePolicy|1 enrolled #0|2 can_switch #0|3 bug_reports_allowed 8",Kz]}}class jz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jz).fromBinary(t,r)}static fromJson(t,r){return(new jz).fromJson(t,r)}static fromJsonString(t,r){return(new jz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jz,t,r)}static $(){return["GetOrganizationPrivateInferencePolicyRequest|1 organization_id 9"]}}class Hz extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hz).fromBinary(t,r)}static fromJson(t,r){return(new Hz).fromJson(t,r)}static fromJsonString(t,r){return(new Hz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hz,t,r)}static $(){return["GetOrganizationPrivateInferencePolicyResponse|4 enabled 8|3 policy #0",zz]}}class Wz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wz).fromBinary(t,r)}static fromJson(t,r){return(new Wz).fromJson(t,r)}static fromJsonString(t,r){return(new Wz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wz,t,r)}static $(){return["UpdateOrganizationPrivateInferencePolicyRequest|1 organization_id 9|2 policy #0",zz]}}class Qz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qz).fromBinary(t,r)}static fromJson(t,r){return(new Qz).fromJson(t,r)}static fromJsonString(t,r){return(new Qz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qz,t,r)}static $(){return["UpdateOrganizationPrivateInferencePolicyResponse|1 policy #0",zz]}}class Vz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vz).fromBinary(t,r)}static fromJson(t,r){return(new Vz).fromJson(t,r)}static fromJsonString(t,r){return(new Vz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vz,t,r)}static $(){return["GetOrganizationPrivateInferenceTeamGroupsRequest|1 organization_id 9"]}}class Xz extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xz).fromBinary(t,r)}static fromJson(t,r){return(new Xz).fromJson(t,r)}static fromJsonString(t,r){return(new Xz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xz,t,r)}static $(){return["PrivateInferenceTeamGroup|1 id 3|2 name 9|3 team_id 5"]}}class Yz extends T{constructor(t){super(),this.groups=[],this.unavailableTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yz).fromBinary(t,r)}static fromJson(t,r){return(new Yz).fromJson(t,r)}static fromJsonString(t,r){return(new Yz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yz,t,r)}static $(){return["GetOrganizationPrivateInferenceTeamGroupsResponse|1 groups #0*|2 unavailable_team_ids 5*",Xz]}}class Zz extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zz).fromBinary(t,r)}static fromJson(t,r){return(new Zz).fromJson(t,r)}static fromJsonString(t,r){return(new Zz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zz,t,r)}static $(){return["GetTeamPrivateInferencePolicyRequest|1 team_id 5"]}}class tj extends T{constructor(t){super(),this.enabled=!1,this.managedByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tj).fromBinary(t,r)}static fromJson(t,r){return(new tj).fromJson(t,r)}static fromJsonString(t,r){return(new tj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tj,t,r)}static $(){return["GetTeamPrivateInferencePolicyResponse|5 enabled 8|3 managed_by_organization 8|4 policy #0?",zz]}}class rj extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rj).fromBinary(t,r)}static fromJson(t,r){return(new rj).fromJson(t,r)}static fromJsonString(t,r){return(new rj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rj,t,r)}static $(){return["UpdateTeamPrivateInferencePolicyRequest|1 team_id 5|2 policy #0",zz]}}class ej extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ej).fromBinary(t,r)}static fromJson(t,r){return(new ej).fromJson(t,r)}static fromJsonString(t,r){return(new ej).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ej,t,r)}static $(){return["UpdateTeamPrivateInferencePolicyResponse|1 policy #0",zz]}}class nj extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nj).fromBinary(t,r)}static fromJson(t,r){return(new nj).fromJson(t,r)}static fromJsonString(t,r){return(new nj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nj,t,r)}static $(){return["SetPageAddressRequest|1 store_id 9|2 canvas_id 9|3 slug 9"]}}class sj extends T{constructor(t){super(),this.slug="",this.pageUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sj).fromBinary(t,r)}static fromJson(t,r){return(new sj).fromJson(t,r)}static fromJsonString(t,r){return(new sj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sj,t,r)}static $(){return["SetPageAddressResponse|1 slug 9|2 page_url 9"]}}class ij extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ij).fromBinary(t,r)}static fromJson(t,r){return(new ij).fromJson(t,r)}static fromJsonString(t,r){return(new ij).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ij,t,r)}static $(){return["SetSlackCursorTeamRequest|1 cursor_team_id 5?"]}}class oj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oj).fromBinary(t,r)}static fromJson(t,r){return(new oj).fromJson(t,r)}static fromJsonString(t,r){return(new oj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oj,t,r)}static $(){return["SetSlackCursorTeamResponse"]}}class aj extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aj).fromBinary(t,r)}static fromJson(t,r){return(new aj).fromJson(t,r)}static fromJsonString(t,r){return(new aj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aj,t,r)}static $(){return["DashboardAppOwner|1 user_id 3|2 name 9|3 email 9"]}}class uj extends T{constructor(t){super(),this.slug="",this.apex="",this.displayName="",this.url="",this.visibility=P.UNSPECIFIED,this.updatedAtMs=n.protoInt64.zero,this.status=I.UNSPECIFIED,this.lastDeployedAtMs=n.protoInt64.zero,this.teamId=n.protoInt64.zero,this.teamName="",this.projectDir="",this.id="",this.needsReview=!1,this.lastPublishBlockedByReview=!1,this.draft=!1,this.retentionUnpublishAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uj).fromBinary(t,r)}static fromJson(t,r){return(new uj).fromJson(t,r)}static fromJsonString(t,r){return(new uj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uj,t,r)}static $(){return["DashboardApp|1 slug 9|2 apex 9|3 display_name 9|4 url 9|5 visibility #0|6 owner #1|7 updated_at_ms 3|8 status #2|9 last_deployed_at_ms 3|10 team_id 3|11 team_name 9|12 project_dir 9|13 id 9|14 disabled_by_cursor #3|15 needs_review 8|16 last_publish_blocked_by_review 8|17 draft 8|18 retention_unpublish_at_ms 3",P,aj,I,x]}}class cj extends T{constructor(t){super(),this.scope=hn.UNSPECIFIED,this.search="",this.pageSize=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cj).fromBinary(t,r)}static fromJson(t,r){return(new cj).fromJson(t,r)}static fromJsonString(t,r){return(new cj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cj,t,r)}static $(){return["ListDashboardAppsRequest|1 scope #0|2 search 9|3 page_size 5|4 page_token 9",hn]}}class lj extends T{constructor(t){super(),this.apps=[],this.nextPageToken="",this.totalCount=0,this.teamScopeAvailable=!1,this.disabledByCursorCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lj).fromBinary(t,r)}static fromJson(t,r){return(new lj).fromJson(t,r)}static fromJsonString(t,r){return(new lj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lj,t,r)}static $(){return["ListDashboardAppsResponse|1 apps #0*|2 next_page_token 9|3 total_count 5|4 team_scope_available 8|5 disabled_by_cursor_count 5",uj]}}class mj extends T{constructor(t){super(),this.publishId="",this.url="",this.status=I.UNSPECIFIED,this.commitSha="",this.dirty=!1,this.bcId="",this.errorMessage="",this.createdAtMs=n.protoInt64.zero,this.publishedByUserId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mj).fromBinary(t,r)}static fromJson(t,r){return(new mj).fromJson(t,r)}static fromJsonString(t,r){return(new mj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mj,t,r)}static $(){return["DashboardAppDeployment|1 publish_id 9|2 url 9|3 status #0|4 commit_sha 9|5 dirty 8|6 bc_id 9|7 error_message 9|8 created_at_ms 3|9 published_by_user_id 3",I]}}class fj extends T{constructor(t){super(),this.name="",this.state=q.UNSPECIFIED,this.deployed=!1,this.updatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fj).fromBinary(t,r)}static fromJson(t,r){return(new fj).fromJson(t,r)}static fromJsonString(t,r){return(new fj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fj,t,r)}static $(){return["DashboardAppSecret|1 name 9|2 state #0|3 deployed 8|4 updated_at_ms 3",q]}}class dj extends T{constructor(t){super(),this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dj).fromBinary(t,r)}static fromJson(t,r){return(new dj).fromJson(t,r)}static fromJsonString(t,r){return(new dj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dj,t,r)}static $(){return["GetDashboardAppRequest|1 slug 9|2 apex 9"]}}class pj extends T{constructor(t){super(),this.previewUrl="",this.repoUrl="",this.deployments=[],this.secrets=[],this.viewerRole=gn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pj).fromBinary(t,r)}static fromJson(t,r){return(new pj).fromJson(t,r)}static fromJsonString(t,r){return(new pj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pj,t,r)}static $(){return["GetDashboardAppResponse|1 app #0|2 preview_url 9|3 repo_url 9|4 deployments #1*|5 secrets #2*|6 security_review #3|7 viewer_role #4",uj,mj,fj,hj,gn]}}class hj extends T{constructor(t){super(),this.overridesAllowed=!1,this.overrides=[],this.lastBlockedFindings=[],this.viewerCanDecide=!1,this.approvableOverrideId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hj).fromBinary(t,r)}static fromJson(t,r){return(new hj).fromJson(t,r)}static fromJsonString(t,r){return(new hj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hj,t,r)}static $(){return["DashboardAppSecurityReview|1 overrides_allowed 8|2 overrides #0*|3 last_blocked_findings #1*|4 viewer_can_decide 8|5 approvable_override_id 9",gj,v]}}class gj extends T{constructor(t){super(),this.id="",this.state=B.UNSPECIFIED,this.slug="",this.apex="",this.visibility=P.UNSPECIFIED,this.findings=[],this.requestReason="",this.decisionReason="",this.selfApproved=!1,this.createdAtMs=n.protoInt64.zero,this.decidedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.revokeReason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gj).fromBinary(t,r)}static fromJson(t,r){return(new gj).fromJson(t,r)}static fromJsonString(t,r){return(new gj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gj,t,r)}static $(){return["DashboardAppReviewOverride|1 id 9|2 state #0|3 slug 9|4 apex 9|5 owner #1|6 visibility #2|7 findings #3*|8 request_reason 9|9 decided_by #1|10 decision_reason 9|11 self_approved 8|12 created_at_ms 3|13 decided_at_ms 3|14 expires_at_ms 3|15 revoked_by #1|16 revoke_reason 9",B,aj,P,v]}}class _j extends T{constructor(t){super(),this.states=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _j).fromBinary(t,r)}static fromJson(t,r){return(new _j).fromJson(t,r)}static fromJsonString(t,r){return(new _j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_j,t,r)}static $(){return["ListAppReviewOverridesRequest|1 states #0*",B]}}class Jj extends T{constructor(t){super(),this.overrides=[],this.overridesAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jj).fromBinary(t,r)}static fromJson(t,r){return(new Jj).fromJson(t,r)}static fromJsonString(t,r){return(new Jj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jj,t,r)}static $(){return["ListAppReviewOverridesResponse|1 overrides #0*|2 overrides_allowed 8",gj]}}class wj extends T{constructor(t){super(),this.overrideId="",this.approve=!1,this.reason="",this.confirmSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wj).fromBinary(t,r)}static fromJson(t,r){return(new wj).fromJson(t,r)}static fromJsonString(t,r){return(new wj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wj,t,r)}static $(){return["DecideAppReviewOverrideRequest|1 override_id 9|2 approve 8|3 reason 9|4 confirm_slug 9"]}}class yj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yj).fromBinary(t,r)}static fromJson(t,r){return(new yj).fromJson(t,r)}static fromJsonString(t,r){return(new yj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yj,t,r)}static $(){return["DecideAppReviewOverrideResponse|1 override #0",gj]}}class Sj extends T{constructor(t){super(),this.overrideId="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sj).fromBinary(t,r)}static fromJson(t,r){return(new Sj).fromJson(t,r)}static fromJsonString(t,r){return(new Sj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sj,t,r)}static $(){return["RevokeAppReviewOverrideRequest|1 override_id 9|2 reason 9"]}}class qj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qj).fromBinary(t,r)}static fromJson(t,r){return(new qj).fromJson(t,r)}static fromJsonString(t,r){return(new qj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qj,t,r)}static $(){return["RevokeAppReviewOverrideResponse|1 override #0",gj]}}class Bj extends T{constructor(t){super(),this.overrideId="",this.reason="",this.confirmSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bj).fromBinary(t,r)}static fromJson(t,r){return(new Bj).fromJson(t,r)}static fromJsonString(t,r){return(new Bj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bj,t,r)}static $(){return["GrantAppReviewOverrideRequest|1 override_id 9|2 reason 9|3 confirm_slug 9"]}}class Ij extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ij).fromBinary(t,r)}static fromJson(t,r){return(new Ij).fromJson(t,r)}static fromJsonString(t,r){return(new Ij).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ij,t,r)}static $(){return["GrantAppReviewOverrideResponse|1 override #0",gj]}}class Pj extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pj).fromBinary(t,r)}static fromJson(t,r){return(new Pj).fromJson(t,r)}static fromJsonString(t,r){return(new Pj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pj,t,r)}static $(){return["ListServiceTokenAppsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9"]}}class bj extends T{constructor(t){super(),this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bj).fromBinary(t,r)}static fromJson(t,r){return(new bj).fromJson(t,r)}static fromJsonString(t,r){return(new bj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bj,t,r)}static $(){return["ListServiceTokenAppsResponse|1 apps #0*",uj]}}class Rj extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.appIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rj).fromBinary(t,r)}static fromJson(t,r){return(new Rj).fromJson(t,r)}static fromJsonString(t,r){return(new Rj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rj,t,r)}static $(){return["SetServiceTokenAppsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 app_ids 9*|6 castle_request_token 9?"]}}class vj extends T{constructor(t){super(),this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vj).fromBinary(t,r)}static fromJson(t,r){return(new vj).fromJson(t,r)}static fromJsonString(t,r){return(new vj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vj,t,r)}static $(){return["SetServiceTokenAppsResponse|1 apps #0*",uj]}}class xj extends T{constructor(t){super(),this.userId=0,this.name="",this.maskedKey="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xj).fromBinary(t,r)}static fromJson(t,r){return(new xj).fromJson(t,r)}static fromJsonString(t,r){return(new xj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xj,t,r)}static $(){return["MemberAppsApiKey|1 user_id 5|2 name 9|3 masked_key 9|4 created_at 3|5 expires_at 3?|6 revocable_service_token_public_id 9?"]}}class kj extends T{constructor(t){super(),this.teamId=0,this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kj).fromBinary(t,r)}static fromJson(t,r){return(new kj).fromJson(t,r)}static fromJsonString(t,r){return(new kj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kj,t,r)}static $(){return["ListAppMemberAppsApiKeysRequest|1 team_id 5|2 slug 9|3 apex 9"]}}class Ej extends T{constructor(t){super(),this.enabled=!1,this.keyAccess=_n.UNSPECIFIED,this.publicApp=!1,this.keys=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ej).fromBinary(t,r)}static fromJson(t,r){return(new Ej).fromJson(t,r)}static fromJsonString(t,r){return(new Ej).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ej,t,r)}static $(){return["ListAppMemberAppsApiKeysResponse|1 enabled 8|2 key_access #0|3 public_app 8|4 keys #1*|5 truncated 8",_n,xj]}}class Cj extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cj).fromBinary(t,r)}static fromJson(t,r){return(new Cj).fromJson(t,r)}static fromJsonString(t,r){return(new Cj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cj,t,r)}static $(){return["ListTeamAppsApiKeysRequest|1 team_id 5"]}}class Tj extends T{constructor(t){super(),this.enabled=!1,this.keyAccess=_n.UNSPECIFIED,this.keys=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tj).fromBinary(t,r)}static fromJson(t,r){return(new Tj).fromJson(t,r)}static fromJsonString(t,r){return(new Tj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tj,t,r)}static $(){return["ListTeamAppsApiKeysResponse|1 enabled 8|2 key_access #0|3 keys #1*|4 truncated 8",_n,xj]}}class Uj extends T{constructor(t){super(),this.list="",this.name="",this.reason="",this.allowedServerIdentifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uj).fromBinary(t,r)}static fromJson(t,r){return(new Uj).fromJson(t,r)}static fromJsonString(t,r){return(new Uj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uj,t,r)}static $(){return["McpAllowlistInUse|1 list 9|2 name 9|3 reason 9|4 allowed_server_identifiers 9*"]}}class Aj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aj).fromBinary(t,r)}static fromJson(t,r){return(new Aj).fromJson(t,r)}static fromJsonString(t,r){return(new Aj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aj,t,r)}static $(){return["ListXaiSessionsRequest"]}}class $j extends T{constructor(t){super(),this.sessions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $j).fromBinary(t,r)}static fromJson(t,r){return(new $j).fromJson(t,r)}static fromJsonString(t,r){return(new $j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($j,t,r)}static $(){return["ListXaiSessionsResponse|1 sessions #0*",Mj]}}class Mj extends T{constructor(t){super(),this.sessionId="",this.createdAt="",this.userAgent="",this.city="",this.country="",this.createdByCursor=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mj).fromBinary(t,r)}static fromJson(t,r){return(new Mj).fromJson(t,r)}static fromJsonString(t,r){return(new Mj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mj,t,r)}static $(){return["XaiSession|1 session_id 9|2 created_at 9|3 user_agent 9|4 city 9|5 country 9|6 created_by_cursor 8"]}}class Oj extends T{constructor(t){super(),this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oj).fromBinary(t,r)}static fromJson(t,r){return(new Oj).fromJson(t,r)}static fromJsonString(t,r){return(new Oj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oj,t,r)}static $(){return["RevokeXaiSessionRequest|1 session_id 9"]}}class Dj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dj).fromBinary(t,r)}static fromJson(t,r){return(new Dj).fromJson(t,r)}static fromJsonString(t,r){return(new Dj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dj,t,r)}static $(){return["RevokeXaiSessionResponse"]}}},"../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"(t,r,e){e.d(r,{I:()=>zp});var n=e("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),s=e("@bufbuild/protobuf"),i=e("../proto/dist/runtime/compact.js");const o="aiserver.v1.";class a extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return o}}var u=(0,i.QT)(s.proto3,o,"UnifyEligibilityReason",[[0,"UNSPECIFIED"],[1,"BLOCKLISTED"],[2,"ENTERPRISE"],[3,"REQUEST_BASED_PRICING"],[4,"OUTSTANDING_INVOICE"],[5,"STRIPE_CREDIT_BALANCE"],[7,"UNSAFE_SUBSCRIPTION_STATUS"],[8,"ALIPAY_PAYMENT_METHOD"],[9,"SSO"]],1),c=(0,i.QT)(s.proto3,o,"UnifyPendingMergeState",[[0,"UNSPECIFIED"],[1,"IN_PROGRESS"],[2,"DELAYED"]],1);class l extends a{constructor(t){super(),this.freeUpgradeCard=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(l,t,r)}static $(){return["IndividualUnifyEligibilitySubject|1 free_upgrade_card 8"]}}class m extends a{constructor(t){super(),this.subject={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(m,t,r)}static $(){return["GetUnifyEligibilityRequest|1 individual #0 subject|2 cursor_team_id 5 subject",l]}}class f extends a{constructor(t){super(),this.eligible=!1,this.reason=u.UNSPECIFIED,this.userFacingMessage="",this.reasons=[],this.canOptInToNewPricing=!1,this.outstandingInvoiceUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(f,t,r)}static $(){return["GetUnifyEligibilityResponse|1 eligible 8|2 reason #0|3 user_facing_message 9|4 reasons #0*|5 can_opt_in_to_new_pricing 8|7 outstanding_invoice_url 9|8 pending_merge #1?|9 free_upgrade_card #2?",u,p,d]}}class d extends a{constructor(t){super(),this.grokStepSkipEnabled=!1,this.foundGrokAccountModalEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(d,t,r)}static $(){return["UnifyFreeUpgradeCard|1 grok_step_skip_enabled 8|2 found_grok_account_modal_enabled 8"]}}class p extends a{constructor(t){super(),this.state=c.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(p,t,r)}static $(){return["UnifyPendingMerge|1 state #0",c]}}class h extends a{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(h,t,r)}static $(){return["GetUnifyPendingMergeRequest"]}}class g extends a{constructor(t){super(),this.pendingMergeUnread=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(g,t,r)}static $(){return["GetUnifyPendingMergeResponse|1 pending_merge #0?|2 pending_merge_unread 8",p]}}var _=(0,i.QT)(s.proto3,"aiserver.v1.","UnifyWaitlistStatus",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"ON_WAITLIST"],[3,"HAS_ACCESS"]],1);const J="aiserver.v1.";class w extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return J}}var y=(0,i.QT)(s.proto3,J,"CollapseCandidateMatchReason",[[0,"UNSPECIFIED"],[1,"SESSION"],[2,"PREVIOUSLY_LINKED"],[3,"MATCHING_EMAIL"],[4,"SAME_WORKOS_ID"],[5,"OWNERSHIP_PROVEN"]],1),S=(0,i.QT)(s.proto3,J,"CollapseCandidateMergeability",[[0,"UNSPECIFIED"],[1,"ELIGIBLE"],[2,"BLOCKED"]],1),q=(0,i.QT)(s.proto3,J,"CollapseCandidateBlockReason",[[0,"UNSPECIFIED"],[1,"ACTIVE_TEAM"],[2,"SSO_SCIM"],[3,"ENTERPRISE"],[4,"IDENTITY_JOIN_CONFLICT"],[5,"TOMBSTONED"],[6,"DOMAIN_CAPTURE"],[7,"ACTIVE_ORGANIZATION"],[8,"UNPROVEN_EMAIL_MATCH"],[9,"UNIFY_BLOCKLISTED"],[10,"REQUEST_BASED_PRICING"],[11,"ALIPAY_PAYMENT_METHOD"],[12,"OUTSTANDING_INVOICE"],[13,"STRIPE_CREDIT_BALANCE"],[14,"UNSAFE_SUBSCRIPTION_STATUS"]],1),B=(0,i.QT)(s.proto3,J,"CollapseCandidateSuggestionReason",[[0,"UNSPECIFIED"],[1,"CANONICAL_ACCOUNT_HEURISTIC"]],1),I=(0,i.QT)(s.proto3,J,"UnificationIntentStep",[[0,"UNSPECIFIED"],[1,"DRAFT"],[2,"AWAITING_PAYMENT"],[3,"COLLAPSING"],[4,"FINALIZING"],[5,"DONE"],[6,"MERGING_IDENTITY_JOINS"],[7,"MERGING_MAPPINGS"],[8,"SETTLING_LEGACY_BILLING"]],1),P=(0,i.QT)(s.proto3,J,"LegacyBillingSettlementStatus",[[0,"UNSPECIFIED"],[1,"NOT_STARTED"],[2,"PROCESSING"],[3,"PAYMENT_REQUIRED"],[4,"SETTLED"],[5,"BYPASSED"],[6,"EXEMPT"],[7,"MANUAL_REVIEW_REQUIRED"],[8,"PAYMENT_PROCESSING"]],1),b=(0,i.QT)(s.proto3,J,"IndividualUnificationMergeStatus",[[0,"UNSPECIFIED"],[1,"NOT_READY"],[2,"READY"],[3,"MERGED"],[4,"CONFLICT"]],1),R=(0,i.QT)(s.proto3,J,"IndividualUnificationEmailUpdateStatus",[[0,"UNSPECIFIED"],[1,"UPDATED"],[2,"ALREADY_CURRENT"],[3,"SKIPPED_CONFLICT"],[4,"SKIPPED_NO_GROK_EMAIL"],[5,"NOT_UPDATED"],[6,"SKIPPED_SCIM_MANAGED"]],1),v=(0,i.QT)(s.proto3,J,"UnificationIntentXaiSelectionKind",[[0,"UNSPECIFIED"],[1,"CREATED_BY_CURSOR"],[2,"DESELECTABLE"],[3,"LOCKED"]],1),x=(0,i.QT)(s.proto3,J,"UnificationIntentXLinkState",[[0,"UNSPECIFIED"],[1,"ALREADY_LINKED"],[2,"WILL_LINK"],[3,"NEEDS_GROK_CONFIRMATION"],[4,"LINK_PENDING"]],1),k=(0,i.QT)(s.proto3,J,"UpgradeGrokStep",[[0,"UNSPECIFIED"],[1,"SKIP"],[2,"FOUND_GROK_ACCOUNT"]],1),E=(0,i.QT)(s.proto3,J,"UnifyAppSheetHost",[[0,"UNSPECIFIED"],[1,"GROK_BOT"],[2,"CURSOR_IOS"]],1),C=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"CONFLICT"],[3,"ENTERPRISE_ACCOUNT"],[4,"SHADOW_REPLACEMENT_BLOCKED"]],1),T=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthShadowReplacementBlockReason",[[0,"UNSPECIFIED"],[1,"OPEN_USER_INTENT"],[2,"OPEN_TEAM_INTENT"],[3,"UNSETTLED_BILLING"],[4,"MANAGED_ACCOUNT"],[5,"COLLAPSE_CONFLICT"],[6,"SHADOW_CHANGED"],[7,"UNAVAILABLE"]],1),U=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthConflictReason",[[0,"UNSPECIFIED"],[1,"HELD_BY_ANOTHER_UNIFICATION"],[2,"LINKED_TO_ANOTHER_CURSOR_ACCOUNT"],[3,"GROK_ACCOUNT_ALREADY_UNIFIED"]],1),A=(0,i.QT)(s.proto3,J,"UnifyAlreadyUnifiedMergeRefusal",[[0,"UNSPECIFIED"],[1,"STORE_SUBSCRIPTION"],[2,"SOURCE_ON_TEAM"],[3,"SOURCE_MANAGED_BY_ORGANIZATION"],[4,"SOURCE_NEEDS_SIGN_IN"],[5,"GROK_BOT_TRANSFER_BLOCKED"],[6,"DESTINATION_ON_TEAM"],[7,"DESTINATION_MANAGED_BY_ORGANIZATION"]],1),$=(0,i.QT)(s.proto3,J,"CompleteUnifyXLoginOutcome",[[0,"UNSPECIFIED"],[1,"RECORDED"],[2,"SELECTED_BY_X"],[3,"NO_GROK_ACCOUNT"],[4,"NEEDS_GROK_CONFIRMATION"],[5,"WILL_LINK"],[6,"AUTHKIT_REQUIRED"],[7,"EMAIL_VERIFICATION_REQUIRED"]],1),M=(0,i.QT)(s.proto3,J,"CollapseSourceProofOutcome",[[0,"UNSPECIFIED"],[1,"OWNERSHIP_PROVEN"],[2,"SELF"],[3,"NO_ACCOUNT"]],1),O=(0,i.QT)(s.proto3,J,"ProvisionUnifyGrokAccountOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"GROK_ACCOUNT_EXISTS"],[3,"ENTERPRISE_GROK_ACCOUNT"],[4,"EXISTING_ACCOUNT_SELECTED"]],1),D=(0,i.QT)(s.proto3,J,"UnifyCtaAudience",[[0,"UNSPECIFIED"],[1,"INDIVIDUAL"],[2,"TEAM_ADMIN"]],1),N=(0,i.QT)(s.proto3,J,"SelectXaiUnificationCursorAccountOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"CONFLICT"],[3,"INVALID_STATE"],[4,"BLOCKED"]],1),G=(0,i.QT)(s.proto3,J,"UnlinkGrokAccountOutcome",[[0,"UNSPECIFIED"],[1,"UNLINKED"],[2,"NOT_LINKED"],[3,"REFUSED_MERGED"],[4,"RATE_LIMITED"],[5,"REFUSED_IN_PROGRESS"],[6,"REFUSED_ENTITLEMENT_GRANTED"]],1),L=(0,i.QT)(s.proto3,J,"DeselectXaiUnificationCursorAccountOutcome",[[0,"UNSPECIFIED"],[1,"DESELECTED"],[2,"UNCHANGED"],[3,"LOCKED"],[4,"INVALID_STATE"]],1),F=(0,i.QT)(s.proto3,J,"XaiUnificationCursorAccountProofOutcome",[[0,"UNSPECIFIED"],[1,"OWNERSHIP_PROVEN"],[2,"NO_ACCOUNT"],[3,"CANCELLED"],[4,"CALLBACK_READY"]],1),K=(0,i.QT)(s.proto3,J,"XaiCursorAccountLinkOutcome",[[0,"UNSPECIFIED"],[1,"CALLBACK_READY"],[2,"LINKED"],[3,"NO_ACCOUNT"],[4,"CANCELLED"],[5,"CONFLICT"],[6,"REFUSED"],[7,"CONSENT_REQUIRED"],[8,"INDIVIDUAL_ACCOUNT"]],1),z=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationStatus",[[0,"UNSPECIFIED"],[1,"QUEUED"],[2,"CHECKING"],[3,"INELIGIBLE"],[4,"RUNNING"],[5,"RETRYING"],[6,"SUCCEEDED"],[7,"FAILED"]],1),j=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationWorkflowState",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"PAUSED"],[3,"NOT_RUNNING"]],1),H=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationEligibilityStatus",[[0,"UNSPECIFIED"],[1,"CHECKING"],[2,"ELIGIBLE"],[3,"INELIGIBLE"],[4,"UNAVAILABLE"]],1),W=(0,i.QT)(s.proto3,J,"TeamUnifiedStatus",[[0,"UNSPECIFIED"],[1,"NOT_UNIFIED"],[2,"UNIFIED"]],1),Q=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"ACTIVE"],[3,"ENDING"],[4,"CONVERTING"],[5,"ENDED"],[6,"CONVERTED"]],1),V=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialSource",[[0,"UNSPECIFIED"],[1,"ACCOUNTINGSPHERE"],[2,"ANYTOOL"],[3,"SALESFORCE"]],1),X=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialOutcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"ALREADY_STARTED"],[3,"REFUSED"]],1),Y=(0,i.QT)(s.proto3,J,"GrokCreditPackReportOutcome",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"RETRYABLE"],[3,"REJECTED"]],1),Z=(0,i.QT)(s.proto3,J,"MergedTeamSeatChangeRefusalReason",[[0,"UNSPECIFIED"],[1,"NOT_MERGED_RAIL"],[2,"MEMBER_NOT_FOUND"],[3,"MEMBER_NOT_MERGED"],[4,"UNCHANGED"],[5,"NOT_CONFIGURED"],[6,"FREE_NOT_OFFERED"]],1),tt=(0,i.QT)(s.proto3,J,"MergedTeamSeatChangeOutcome",[[0,"UNSPECIFIED"],[1,"CHANGED"],[2,"SCHEDULED"],[3,"DOWNGRADE_WITHDRAWN"],[4,"MANAGE_ON_GROK"],[5,"TRY_AGAIN"],[6,"PAYMENT_FAILED"],[7,"PLAN_CANCELLING"],[8,"CHARGE_IN_FLIGHT"],[9,"REQUIRES_ACTION"],[10,"ADD_PAYMENT_METHOD"],[11,"GROK_SECURITY_BLOCKED"],[12,"GROK_SIGN_IN_REQUIRED"],[13,"GROK_OTHER_ACCOUNT"]],1),rt=(0,i.QT)(s.proto3,J,"UnifiedInvoiceKind",[[0,"UNSPECIFIED"],[1,"SUBSCRIPTION"],[2,"TOP_UP"]],1),et=(0,i.QT)(s.proto3,J,"UnifiedInvoiceStatus",[[0,"UNSPECIFIED"],[1,"PAID"],[2,"PENDING"],[3,"FAILED"]],1),nt=(0,i.QT)(s.proto3,J,"UnifiedInvoiceSource",[[0,"UNSPECIFIED"],[1,"COMMERCE_PLATFORM"],[2,"MC_BILLING"],[3,"STRIPE"]],1),st=(0,i.QT)(s.proto3,J,"XaiCursorTeamMergeCheckoutState",[[0,"UNSPECIFIED"],[1,"NOT_STARTED"],[2,"AWAITING_PAYMENT"],[3,"PAID"],[4,"MERGED"]],1),it=(0,i.QT)(s.proto3,J,"XaiCursorTeamMemberRole",[[0,"UNSPECIFIED"],[1,"MEMBER"],[2,"ADMIN"]],1),ot=(0,i.QT)(s.proto3,J,"XaiCursorTeamMergeGrokTeamsState",[[0,"UNSPECIFIED"],[1,"NOT_SIGNED_IN"],[2,"AVAILABLE"],[3,"MISSING_SCOPE"],[4,"UNAVAILABLE"]],1),at=(0,i.QT)(s.proto3,J,"EnsureXaiCursorTeamForMergeOutcome",[[0,"UNSPECIFIED"],[1,"ENSURED"],[2,"GROK_ACCOUNT_EXISTS"]],1),ut=(0,i.QT)(s.proto3,J,"XaiEmailEligibilityResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"MISSING_EMAIL"],[3,"NOT_CONFIGURED"],[4,"UNAVAILABLE"],[5,"REFUSED"]],1),ct=(0,i.QT)(s.proto3,J,"XaiEmailUnificationStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"ALREADY_UNIFIED_WITH_CALLER"],[3,"UNIFIED_WITH_OTHER_CURSOR_USER"]],1),lt=(0,i.QT)(s.proto3,J,"GrokAccountsByXUserResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"NOT_CONFIGURED"],[3,"UNAVAILABLE"],[4,"REFUSED"]],1),mt=(0,i.QT)(s.proto3,J,"UnifyAlreadyUnifiedMergeDestinationKind",[[0,"UNSPECIFIED"],[1,"EMAIL"],[2,"GENERIC"]],1);class ft extends w{constructor(t){super(),this.publicId="",this.targetUserId=0,this.status="",this.sources=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ft,t,r)}static $(){return["AccountCollapseRun|1 public_id 9|2 target_user_id 5|3 status 9|4 sources #0*|5 created_at #1|6 updated_at #1",dt,s.Timestamp]}}class dt extends w{constructor(t){super(),this.sourceUserId=0,this.status="",this.steps=[],this.totalSteps=0,this.doneSteps=0,this.progressPercent=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dt,t,r)}static $(){return["AccountCollapseRunSource|1 source_user_id 5|2 status 9|3 steps #0*|4 total_steps 5|5 done_steps 5|6 progress_percent 5",pt]}}class pt extends w{constructor(t){super(),this.stepKey="",this.status="",this.attemptCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pt,t,r)}static $(){return["AccountCollapseStep|1 step_key 9|2 status 9|3 attempt_count 5"]}}class ht extends w{constructor(t){super(),this.targetUserId=0,this.sourceUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ht,t,r)}static $(){return["StartAccountCollapseRunRequest|1 target_user_id 5|2 source_user_ids 5*"]}}class gt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gt,t,r)}static $(){return["StartAccountCollapseRunResponse|1 run #0",ft]}}class _t extends w{constructor(t){super(),this.publicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_t,t,r)}static $(){return["GetAccountCollapseRunRequest|1 public_id 9"]}}class Jt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jt,t,r)}static $(){return["GetAccountCollapseRunResponse|1 run #0",ft]}}class wt extends w{constructor(t){super(),this.targetCursorUserId=0,this.sourceCursorUserIds=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wt,t,r)}static $(){return["StartCursorAccountCollapseRequest|1 target_cursor_user_id 5|2 source_cursor_user_ids 5*|3 legacy_privacy_acknowledged 8"]}}class yt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yt,t,r)}static $(){return["StartCursorAccountCollapseResponse|1 run #0",ft]}}class St extends w{constructor(t){super(),this.targetCursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(St,t,r)}static $(){return["GetCursorAccountCollapseByTargetRequest|1 target_cursor_user_id 5"]}}class qt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qt,t,r)}static $(){return["GetCursorAccountCollapseByTargetResponse|1 run #0?",ft]}}class Bt extends w{constructor(t){super(),this.sourceCursorUserIds=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bt,t,r)}static $(){return["StartCursorSessionAccountCollapseRequest|1 source_cursor_user_ids 5*|2 legacy_privacy_acknowledged 8"]}}class It extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(It,t,r)}static $(){return["GetCursorSessionAccountCollapseRequest"]}}class Pt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pt,t,r)}static $(){return["ListCursorSessionAccountCollapseCandidatesRequest"]}}class bt extends w{constructor(t){super(),this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bt,t,r)}static $(){return["StartCursorSessionAccountCollapseProofRequest|1 redirect_uri 9|2 candidate_reference 9?"]}}class Rt extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rt,t,r)}static $(){return["CompleteCursorSessionAccountCollapseProofRequest|1 code 9|2 state 9"]}}class vt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vt,t,r)}static $(){return["GetUnificationLegacySuperGrokPlanRequest"]}}class xt extends w{constructor(t){super(),this.plan="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xt,t,r)}static $(){return["GetUnificationLegacySuperGrokPlanResponse|1 plan 9"]}}class kt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kt,t,r)}static $(){return["ListCollapseCandidatesRequest"]}}class Et extends w{constructor(t){super(),this.individualPlan="",this.activeTeamCount=0,this.hasEnterpriseMembership=!1,this.hasSsoOrScimMembership=!1,this.activeOrganizationCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Et,t,r)}static $(){return["CollapseCandidateMembershipSummary|1 individual_plan 9|2 active_team_count 5|3 has_enterprise_membership 8|4 has_sso_or_scim_membership 8|5 active_organization_count 5"]}}class Ct extends w{constructor(t){super(),this.name="",this.maskedKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ct,t,r)}static $(){return["CollapseCandidateApiKey|1 name 9|2 masked_key 9"]}}class Tt extends w{constructor(t){super(),this.matchReasons=[],this.mergeability=S.UNSPECIFIED,this.blockReasons=[],this.suggestedTarget=!1,this.requiresProof=!1,this.xaiJitShadow=!1,this.apiKeys=[],this.ownershipProofLapsed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tt,t,r)}static $(){return["CollapseCandidate|1 cursor_user_id 5?|2 auth_id 9?|3 email 9?|4 display_name 9?|5 workos_id 9?|6 membership #0|7 last_sign_in_at #1?|8 match_reasons #2*|9 mergeability #3|10 block_reasons #4*|11 suggested_target 8|12 suggestion_reason #5?|13 requires_proof 8|14 candidate_reference 9?|15 xai_jit_shadow 8|16 api_keys #6*|17 ownership_proof_lapsed 8",Et,s.Timestamp,y,S,q,B,Ct]}}class Ut extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ut,t,r)}static $(){return["CollapseLinkedGrokAccount|1 email 9?"]}}class At extends w{constructor(t){super(),this.candidates=[],this.legacyPrivacyAcknowledgementRequired=!1,this.grokBotDataTransferBlocked=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(At,t,r)}static $(){return["ListCollapseCandidatesResponse|1 candidates #0*|2 linked_grok_account #1?|3 session_account_created_by_unification 8?|4 legacy_privacy_acknowledgement_required 8|6 grok_bot_data_transfer_blocked 8",Tt,Ut]}}class $t extends w{constructor(t){super(),this.status=P.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($t,t,r)}static $(){return["LegacyBillingSettlement|1 status #0|2 hosted_invoice_url 9?|3 amount_cents 3?|4 currency 9?",P]}}class Mt extends w{constructor(t){super(),this.publicId="",this.initiatedFrom="",this.subjectType="",this.step=I.UNSPECIFIED,this.xLinkState=x.UNSPECIFIED,this.xaiSelectionKind=v.UNSPECIFIED,this.backgroundGrokAccountSelected=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mt,t,r)}static $(){return["UnificationIntent|1 public_id 9|2 initiated_from 9|4 subject_type 9|5 intended_xai_email 9?|6 created_at #0|7 updated_at #0|8 intended_cursor_resource_id 9?|9 intended_xai_resource_id 9?|10 joined_id 9?|11 step #1|12 collapse_run_id 9?|13 x_hosted_flow_returned_at #0?|14 x_link_state #2|15 pending_x_username 9?|16 xai_selection_kind #3|17 background_grok_account_selected 8|18 cursor_stripe_credit_balance_cents 3?|19 x_account_refusal #4?",s.Timestamp,I,x,v,Hn]}}class Ot extends w{constructor(t){super(),this.checkUpgradeGrokStep=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ot,t,r)}static $(){return["GetUnificationIntentRequest|1 check_upgrade_grok_step 8"]}}class Dt extends w{constructor(t){super(),this.forDuplicateSubscriptionReminder=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dt,t,r)}static $(){return["GetStoreSubscriptionsToCancelRequest|1 for_duplicate_subscription_reminder 8"]}}class Nt extends w{constructor(t){super(),this.store=Gt.UNSPECIFIED,this.app="",this.appName="",this.planLabel="",this.manageUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nt,t,r)}static $(){return["StoreSubscriptionToCancel|1 store #0|2 app 9|3 app_name 9|4 plan_label 9|5 manage_url 9",Gt]}}var Gt=(0,i.QT)(s.proto3,J,"StoreSubscriptionToCancel.Store",[[0,"UNSPECIFIED"],[1,"APPLE"],[2,"GOOGLE"]],1);class Lt extends w{constructor(t){super(),this.subscriptions=[],this.duplicateSubscriptionReminderEligible=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lt,t,r)}static $(){return["GetStoreSubscriptionsToCancelResponse|1 subscriptions #0*|2 duplicate_subscription_reminder_eligible 8",Nt]}}class Ft extends w{constructor(t){super(),this.enabled=!1,this.mergeStatus=b.UNSPECIFIED,this.emailUpdateStatus=R.UNSPECIFIED,this.grokReselectionAllowed=!1,this.cursorAccountLinkingEligible=!1,this.linkedGrokAccountHasGrokBotEntitlement=!1,this.hasPreviouslySelectedGrokAccount=!1,this.continueWithFreeEligible=!1,this.xFirstLinkingAvailable=!1,this.blockedByCursorTeam=!1,this.sameEmailGrokAccountLinked=!1,this.legacyPrivacyAcknowledgementRequired=!1,this.heldUnifiedPlanCarryOverEligible=!1,this.xWaitsForGrokSignIn=!1,this.grokBotDataTransferBlocked=!1,this.heldUnifiedPlanSignInRequired=!1,this.previousSubscriptionRefundRefusal="",this.paidMergeAwaitsLegacyPrivacyAcknowledgement=!1,this.paidMergeInProgress=!1,this.prePaymentCursorAccountsListAvailable=!1,this.upgradeGrokStep=k.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ft,t,r)}static $(){return["GetUnificationIntentResponse|1 enabled 8|2 intent #0?|3 merge_status #1|4 merged_at #2?|5 email_update_status #3|6 linked_grok_account #4?|7 grok_reselection_allowed 8|8 cursor_account_linking_eligible 8|9 linked_grok_account_has_grok_bot_entitlement 8|10 has_previously_selected_grok_account 8|11 continue_with_free_eligible 8|12 legacy_billing_settlement #5?|13 x_first_linking_available 8|14 blocked_by_cursor_team 8|15 same_email_grok_account_linked 8|16 grok_email_account_exists 8?|17 grok_email_can_proceed_without_suggestion 8?|18 legacy_privacy_acknowledgement_required 8|19 grok_email_linked_to_different_email 8?|20 held_unified_plan_carry_over_eligible 8|21 x_waits_for_grok_sign_in 8|23 grok_bot_data_transfer_blocked 8|24 held_unified_plan_sign_in_required 8|25 previous_subscription_refund_refusal 9|26 paid_merge_awaits_legacy_privacy_acknowledgement 8|27 paid_merge_in_progress 8|28 pre_payment_cursor_accounts_list_available 8|29 held_unified_grant #6?|30 upgrade_grok_step #7",Mt,b,s.Timestamp,R,Ut,$t,Kt,k]}}class Kt extends w{constructor(t){super(),this.subscriptionId="",this.skuId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kt,t,r)}static $(){return["HeldUnifiedGrant|1 subscription_id 9|2 sku_id 9"]}}class zt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zt,t,r)}static $(){return["GetIndividualUnificationPrepaidPreviewRequest"]}}class jt extends w{constructor(t){super(),this.available=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jt,t,r)}static $(){return["GetIndividualUnificationPrepaidPreviewResponse|1 available 8|2 prepaid_balance_cents 3?|3 grok_auto_top_up #0?|4 xai_team_id 9?|5 grok_monthly_cap_cents 3?",n.xYM]}}class Ht extends w{constructor(t){super(),this.deselectXaiAccount=!1,this.clearPendingXAccount=!1,this.acknowledgeXAccountRefusal=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ht,t,r)}static $(){return["UpsertUnificationIntentRequest|1 deselect_xai_account 8|2 clear_pending_x_account 8|3 acknowledge_x_account_refusal 8"]}}class Wt extends w{constructor(t){super(),this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wt,t,r)}static $(){return["UpsertUnificationIntentResponse|1 enabled 8|2 intent #0?",Mt]}}class Qt extends w{constructor(t){super(),this.redirectUri="",this.appSheetVerifierHash="",this.appSheetHost=E.UNSPECIFIED,this.unlinkExistingLink=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qt,t,r)}static $(){return["StartUnifyGrokOAuthRequest|1 redirect_uri 9|2 app_sheet_verifier_hash 9|3 app_sheet_host #0|4 unlink_existing_link 8",E]}}class Vt extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vt,t,r)}static $(){return["StartUnifyGrokOAuthResponse|1 authorize_url 9"]}}class Xt extends w{constructor(t){super(),this.code="",this.state="",this.unlinkConfirmation="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xt,t,r)}static $(){return["CompleteUnifyGrokOAuthRequest|1 code 9|2 state 9|3 unlink_confirmation 9"]}}class Yt extends w{constructor(t){super(),this.inviteCode="",this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yt,t,r)}static $(){return["StartTeamInviteGrokBindRequest|1 invite_code 9|2 redirect_uri 9"]}}class Zt extends w{constructor(t){super(),this.authorizeUrl="",this.alreadyLinked=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zt,t,r)}static $(){return["StartTeamInviteGrokBindResponse|1 authorize_url 9|2 already_linked 8"]}}class tr extends w{constructor(t){super(),this.inviteCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tr,t,r)}static $(){return["GetTeamInviteGrokBindStatusRequest|1 invite_code 9"]}}class rr extends w{constructor(t){super(),this.proven=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rr).fromBinary(t,r)}static fromJson(t,r){return(new rr).fromJson(t,r)}static fromJsonString(t,r){return(new rr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rr,t,r)}static $(){return["GetTeamInviteGrokBindStatusResponse|1 proven 8"]}}class er extends w{constructor(t){super(),this.outcome=C.UNSPECIFIED,this.returnPath="",this.continueUrl="",this.shadowReplacementBlockReason=T.UNSPECIFIED,this.conflictReason=U.UNSPECIFIED,this.alreadyUnifiedMergeOffered=!1,this.alreadyUnifiedMergeRefusal=A.UNSPECIFIED,this.linkedCursorEmailIsSynthetic=!1,this.unlinkConfirmation="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(er,t,r)}static $(){return["CompleteUnifyGrokOAuthResponse|1 outcome #0|2 intent #1?|3 return_path 9|4 continue_url 9|5 xai_email 9?|6 shadow_replacement_block_reason #2|7 conflict_reason #3|8 linked_cursor_email_masked 9?|9 already_unified_merge_offered 8|10 already_unified_merge_refusal #4|11 linked_cursor_email_is_synthetic 8|12 unlink #5|13 unlink_confirmation 9",C,Mt,T,U,A,nr]}}class nr extends w{constructor(t){super(),this.state={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nr,t,r)}static $(){return["UnifyGrokConflictUnlink|1 offered #0 state|2 refused #1 state",sr,ir]}}class sr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sr).fromBinary(t,r)}static fromJson(t,r){return(new sr).fromJson(t,r)}static fromJsonString(t,r){return(new sr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sr,t,r)}static $(){return["UnifyGrokConflictUnlink.Offered"]}}class ir extends w{constructor(t){super(),this.reason=or.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ir,t,r)}static $(){return["UnifyGrokConflictUnlink.Refused|1 reason #0|2 next_unlink_allowed_at #1?",or,s.Timestamp]}}var or=(0,i.QT)(s.proto3,J,"UnifyGrokConflictUnlink.Refused.Reason",[[0,"UNSPECIFIED"],[1,"MERGED"],[2,"IN_PROGRESS"],[3,"RATE_LIMITED"],[4,"ENTITLEMENT_GRANTED"]],1);class ar extends w{constructor(t){super(),this.redirectUri="",this.appSheetVerifierHash="",this.appSheetHost=E.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ar,t,r)}static $(){return["StartUnifyXLoginRequest|1 redirect_uri 9|2 app_sheet_verifier_hash 9|3 app_sheet_host #0",E]}}class ur extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ur,t,r)}static $(){return["StartUnifyXLoginResponse|1 authorize_url 9"]}}class cr extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cr,t,r)}static $(){return["CompleteUnifyXLoginRequest|1 code 9|2 state 9"]}}class lr extends w{constructor(t){super(),this.outcome=$.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lr,t,r)}static $(){return["CompleteUnifyXLoginResponse|1 intent #0|2 outcome #1|3 authkit_authorize_url 9?|4 email_verification_state 9?",Mt,$]}}class mr extends w{constructor(t){super(),this.emailVerificationState="",this.code="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mr,t,r)}static $(){return["VerifyUnifyXLoginEmailRequest|1 email_verification_state 9|2 code 9"]}}class fr extends w{constructor(t){super(),this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fr,t,r)}static $(){return["StartCollapseSourceProofRequest|1 redirect_uri 9|2 login_hint 9?|3 candidate_reference 9?"]}}class dr extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dr,t,r)}static $(){return["StartCollapseSourceProofResponse|1 authorize_url 9"]}}class pr extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pr,t,r)}static $(){return["CompleteCollapseSourceProofRequest|1 code 9|2 state 9"]}}class hr extends w{constructor(t){super(),this.outcome=M.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hr,t,r)}static $(){return["CompleteCollapseSourceProofResponse|1 outcome #0",M]}}class gr extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gr,t,r)}static $(){return["RevokeCollapseSourceProofRequest|1 cursor_user_id 5"]}}class _r extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_r,t,r)}static $(){return["RevokeCollapseSourceProofResponse"]}}class Jr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jr,t,r)}static $(){return["ProvisionUnifyGrokAccountRequest"]}}class wr extends w{constructor(t){super(),this.outcome=O.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wr).fromBinary(t,r)}static fromJson(t,r){return(new wr).fromJson(t,r)}static fromJsonString(t,r){return(new wr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wr,t,r)}static $(){return["ProvisionUnifyGrokAccountResponse|1 intent #0|2 outcome #1",Mt,O]}}class yr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yr,t,r)}static $(){return["GetUnifyCtaRequest"]}}class Sr extends w{constructor(t){super(),this.show=!1,this.audience=D.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sr,t,r)}static $(){return["GetUnifyCtaResponse|1 show 8|2 audience #0|3 href 9?",D]}}class qr extends w{constructor(t){super(),this.continueWithFree=!1,this.legacyPrivacyAcknowledged=!1,this.carryOverHeldPlan=!1,this.heldGrantSubscriptionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qr,t,r)}static $(){return["FinalizeIndividualUnificationRequest|1 checkout_outcome #0?|2 continue_with_free 8|3 marketing_opted_out 8?|4 legacy_privacy_acknowledged 8|5 carry_over_held_plan 8|6 held_grant_subscription_id 9",Br]}}class Br extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Br,t,r)}static $(){return["IndividualUnificationCheckoutOutcome|1 purchase_id 9?|2 subscription_id 9?"]}}class Ir extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.emailUpdateStatus=R.UNSPECIFIED,this.previousSubscriptionRefundRefusal="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ir,t,r)}static $(){return["FinalizeIndividualUnificationResponse|1 merge_status #0|2 merged_at #1?|3 email_update_status #2|4 legacy_billing_settlement #3?|5 x_account_refusal #4?|6 previous_subscription_refund_refusal 9|7 xai_team_id 9?",b,s.Timestamp,R,$t,Hn]}}class Pr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pr).fromBinary(t,r)}static fromJson(t,r){return(new Pr).fromJson(t,r)}static fromJsonString(t,r){return(new Pr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pr,t,r)}static $(){return["GetOrCreateXaiUnificationIntentRequest|1 surface 9?"]}}class br extends w{constructor(t){super(),this.created=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(br,t,r)}static $(){return["GetOrCreateXaiUnificationIntentResponse|1 intent #0|2 created 8",Mt]}}class Rr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rr,t,r)}static $(){return["GetXaiUnificationIntentRequest"]}}class vr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vr,t,r)}static $(){return["XaiUnificationLinkedCursorAccount|1 cursor_user_id 5?|2 email 9?"]}}class xr extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xr,t,r)}static $(){return["GetXaiUnificationIntentResponse|1 intent #0?|2 merge_status #1|3 merged_at #2?|4 linked_cursor_account #3?|5 legacy_privacy_acknowledgement_required 8|6 pending_merge #4?",Mt,b,s.Timestamp,vr,p]}}class kr extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kr,t,r)}static $(){return["SelectXaiUnificationCursorAccountRequest|1 cursor_user_id 5|2 surface 9?"]}}class Er extends w{constructor(t){super(),this.outcome=N.UNSPECIFIED,this.blockReasons=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Er).fromBinary(t,r)}static fromJson(t,r){return(new Er).fromJson(t,r)}static fromJsonString(t,r){return(new Er).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Er,t,r)}static $(){return["SelectXaiUnificationCursorAccountResponse|1 outcome #0|2 intent #1?|3 block_reasons #2*|4 outstanding_invoice_url 9?",N,Mt,q]}}class Cr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cr,t,r)}static $(){return["UnlinkGrokAccountRequest|1 reason 9?"]}}class Tr extends w{constructor(t){super(),this.outcome=G.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tr,t,r)}static $(){return["UnlinkGrokAccountResponse|1 outcome #0|2 message 9|3 next_unlink_allowed_at #1?",G,s.Timestamp]}}class Ur extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ur,t,r)}static $(){return["DeselectXaiUnificationCursorAccountRequest|1 cursor_user_id 5"]}}class Ar extends w{constructor(t){super(),this.outcome=L.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ar,t,r)}static $(){return["DeselectXaiUnificationCursorAccountResponse|1 outcome #0|2 intent #1?",L,Mt]}}class $r extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($r,t,r)}static $(){return["ListXaiUnificationCollapseCandidatesRequest"]}}class Mr extends w{constructor(t){super(),this.redirectUri="",this.returnUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mr).fromBinary(t,r)}static fromJson(t,r){return(new Mr).fromJson(t,r)}static fromJsonString(t,r){return(new Mr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mr,t,r)}static $(){return["StartXaiUnificationCursorAccountProofRequest|1 redirect_uri 9|2 return_uri 9|3 login_hint 9?"]}}class Or extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Or,t,r)}static $(){return["StartXaiUnificationCursorAccountProofResponse|1 authorize_url 9"]}}class Dr extends w{constructor(t){super(),this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dr,t,r)}static $(){return["CompleteXaiUnificationCursorAccountProofRequest|1 code 9?|2 state 9|3 oauth_error 9?"]}}class Nr extends w{constructor(t){super(),this.outcome=F.UNSPECIFIED,this.returnUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nr,t,r)}static $(){return["CompleteXaiUnificationCursorAccountProofResponse|1 outcome #0|2 return_uri 9|3 continuation_state 9?",F]}}class Gr extends w{constructor(t){super(),this.continueWithFree=!1,this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gr,t,r)}static $(){return["AdvanceXaiUnificationIntentRequest|1 checkout_outcome #0?|2 continue_with_free 8|3 existing_subscription_id 9?|4 legacy_privacy_acknowledged 8|5 surface 9?",Br]}}class Lr extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lr,t,r)}static $(){return["AdvanceXaiUnificationIntentResponse|1 intent #0|2 merge_status #1|3 merged_at #2?|4 legacy_privacy_acknowledgement_required 8|5 pending_merge #3?",Mt,b,s.Timestamp,p]}}class Fr extends w{constructor(t){super(),this.redirectUri="",this.returnUri="",this.replaceLinkedShadow=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fr).fromBinary(t,r)}static fromJson(t,r){return(new Fr).fromJson(t,r)}static fromJsonString(t,r){return(new Fr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fr,t,r)}static $(){return["StartXaiCursorAccountLinkRequest|1 redirect_uri 9|2 return_uri 9|3 login_hint 9?|4 replace_linked_shadow 8"]}}class Kr extends w{constructor(t){super(),this.authorizeUrl="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kr).fromBinary(t,r)}static fromJson(t,r){return(new Kr).fromJson(t,r)}static fromJsonString(t,r){return(new Kr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kr,t,r)}static $(){return["StartXaiCursorAccountLinkResponse|1 authorize_url 9|2 legacy_privacy_acknowledgement_required 8|3 replaced_shadow_email 9?|4 replaced_shadow_created_at #0?",s.Timestamp]}}class zr extends w{constructor(t){super(),this.state="",this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zr).fromBinary(t,r)}static fromJson(t,r){return(new zr).fromJson(t,r)}static fromJsonString(t,r){return(new zr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zr,t,r)}static $(){return["CompleteXaiCursorAccountLinkRequest|1 code 9?|2 state 9|3 oauth_error 9?|4 legacy_privacy_acknowledged 8|5 consent_token 9?"]}}class jr extends w{constructor(t){super(),this.outcome=K.UNSPECIFIED,this.returnUri="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jr,t,r)}static $(){return["CompleteXaiCursorAccountLinkResponse|1 outcome #0|2 return_uri 9|3 continuation_state 9?|4 cursor_user_id 5?|5 cursor_email 9?|6 legacy_privacy_acknowledgement_required 8|7 consent_token 9?|8 xai_email 9?|9 replaced_shadow_email 9?",K]}}class Hr extends w{constructor(t){super(),this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hr,t,r)}static $(){return["PeekXaiCursorAccountLinkContinuationRequest|1 state 9"]}}class Wr extends w{constructor(t){super(),this.cursorEmail="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wr,t,r)}static $(){return["PeekXaiCursorAccountLinkContinuationResponse|1 cursor_email 9|2 replaced_shadow_email 9?|3 replaced_shadow_created_at #0?",s.Timestamp]}}class Qr extends w{constructor(t){super(),this.id="",this.status=z.UNSPECIFIED,this.reason="",this.reasonCode="",this.issues=[],this.workflowState=j.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qr,t,r)}static $(){return["EnterpriseGrokMigration|1 id 9|2 status #0|3 reason 9|4 reason_code 9|5 consented_at #1|6 completed_at #1?|7 issues #2*|8 workflow_state #3",z,s.Timestamp,Vr,j]}}class Vr extends w{constructor(t){super(),this.code="",this.message="",this.members=[],this.memberCount=0,this.teamNames=[],this.accounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vr).fromBinary(t,r)}static fromJson(t,r){return(new Vr).fromJson(t,r)}static fromJsonString(t,r){return(new Vr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vr,t,r)}static $(){return["EnterpriseGrokMigrationIssue|1 code 9|2 message 9|3 members 9*|4 member_count 5|5 team_names 9*|6 accounts #0*",Xr]}}class Xr extends w{constructor(t){super(),this.cursorUserId=0,this.email="",this.xaiUserId="",this.reason="",this.xaiTeamId="",this.xaiTeamName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xr,t,r)}static $(){return["EnterpriseGrokMigrationRefusedAccount|1 cursor_user_id 5|2 email 9|3 xai_user_id 9|4 reason 9|5 xai_team_id 9|6 xai_team_name 9"]}}class Yr extends w{constructor(t){super(),this.cursorUserId=0,this.name="",this.email="",this.xaiPlan="",this.additionalXaiUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yr,t,r)}static $(){return["EnterpriseGrokConflictingAccount|1 cursor_user_id 5|2 xai_user_id 9?|3 name 9|4 email 9|5 xai_plan 9|6 last_active_at #0?|7 additional_xai_user_ids 9*",s.Timestamp]}}class Zr extends w{constructor(t){super(),this.status=H.UNSPECIFIED,this.issues=[],this.reason="",this.conflictingAccounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zr,t,r)}static $(){return["EnterpriseGrokMigrationEligibility|1 status #0|2 issues #1*|3 reason 9|4 started_at #2?|5 completed_at #2?|6 conflicting_accounts #3*",H,Vr,s.Timestamp,Yr]}}class te extends w{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(te,t,r)}static $(){return["CheckEnterpriseGrokMigrationEligibilityRequest|1 organization_id 9"]}}class re extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(re,t,r)}static $(){return["CheckEnterpriseGrokMigrationEligibilityResponse|1 eligibility #0",Zr]}}class ee extends w{constructor(t){super(),this.organizationId="",this.acknowledgments=[],this.termsVersion="",this.legacyPrivacyAcknowledged=!1,this.consentedDeleteCursorUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ee,t,r)}static $(){return["StartEnterpriseGrokMigrationRequest|1 organization_id 9|2 acknowledgments 9*|3 terms_version 9|4 marketing_opted_out 8?|5 legacy_privacy_acknowledged 8|6 consented_delete_cursor_user_ids 5*"]}}class ne extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ne,t,r)}static $(){return["StartEnterpriseGrokMigrationResponse|1 migration #0",Qr]}}class se extends w{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new se).fromBinary(t,r)}static fromJson(t,r){return(new se).fromJson(t,r)}static fromJsonString(t,r){return(new se).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(se,t,r)}static $(){return["GetEnterpriseGrokMigrationStatusRequest|1 organization_id 9"]}}class ie extends w{constructor(t){super(),this.legacyPrivacyAcknowledgementRequired=!1,this.conflictingAccounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ie,t,r)}static $(){return["GetEnterpriseGrokMigrationStatusResponse|1 migration #0?|2 legacy_privacy_acknowledgement_required 8|3 eligibility #1?|4 conflicting_accounts #2*",Qr,Zr,Yr]}}class oe extends w{constructor(t){super(),this.teamId=0,this.userId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oe,t,r)}static $(){return["RetryTeamXaiMembershipHoldRequest|1 team_id 5|2 user_id 5"]}}class ae extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ae,t,r)}static $(){return["RetryTeamXaiMembershipHoldResponse|1 migration #0",Qr]}}class ue extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ue,t,r)}static $(){return["GetTeamUnifiedStatusInternalRequest|1 team_id 5"]}}class ce extends w{constructor(t){super(),this.status=W.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ce,t,r)}static $(){return["GetTeamUnifiedStatusInternalResponse|1 status #0",W]}}class le extends w{constructor(t){super(),this.trialId=s.protoInt64.zero,this.teamId=0,this.state=Q.UNSPECIFIED,this.startsAtMs=s.protoInt64.zero,this.endsAtMs=s.protoInt64.zero,this.complatGrantSkipped=!1,this.startedBy="",this.source=V.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(le,t,r)}static $(){return["UnifiedTeamTrial|1 trial_id 3|2 team_id 5|3 state #0|4 starts_at_ms 3|5 ends_at_ms 3|6 target_ends_at_ms 3?|7 complat_grant_skipped 8|8 complat_subscription_id 9?|9 seat_quantity 5?|10 credit_cents 3?|11 credit_expires_at_ms 3?|12 started_by 9|13 source #1|14 closed_at_ms 3?",Q,V]}}class me extends w{constructor(t){super(),this.outcome=X.UNSPECIFIED,this.refusalReason="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(me,t,r)}static $(){return["UnifiedTeamTrialInternalResponse|1 outcome #0|2 trial #1?|3 refusal_reason 9|4 message 9",X,le]}}class fe extends w{constructor(t){super(),this.teamId=0,this.targetEndsAtMs=s.protoInt64.zero,this.creditCents=s.protoInt64.zero,this.seatQuantity=0,this.startedBy="",this.source=V.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fe).fromBinary(t,r)}static fromJson(t,r){return(new fe).fromJson(t,r)}static fromJsonString(t,r){return(new fe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fe,t,r)}static $(){return["StartUnifiedTeamTrialInternalRequest|1 team_id 5|2 target_ends_at_ms 3|3 credit_cents 3|4 seat_quantity 5|5 started_by 9|6 source #0",V]}}class de extends w{constructor(t){super(),this.teamId=0,this.extendedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(de,t,r)}static $(){return["ExtendUnifiedTeamTrialInternalRequest|1 team_id 5|2 target_ends_at_ms 3?|3 credit_cents 3?|4 seat_quantity 5?|5 extended_by 9"]}}class pe extends w{constructor(t){super(),this.teamId=0,this.endedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pe,t,r)}static $(){return["EndUnifiedTeamTrialInternalRequest|1 team_id 5|2 ended_by 9"]}}class he extends w{constructor(t){super(),this.teamId=0,this.contractEndsAtMs=s.protoInt64.zero,this.seatQuantity=0,this.convertedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(he,t,r)}static $(){return["ConvertUnifiedTeamTrialInternalRequest|1 team_id 5|2 contract_ends_at_ms 3|3 seat_quantity 5|4 converted_by 9"]}}class ge extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ge,t,r)}static $(){return["GetUnifiedTeamTrialInternalRequest|1 team_id 5"]}}class _e extends w{constructor(t){super(),this.startEnabled=!1,this.activeSeatCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_e,t,r)}static $(){return["GetUnifiedTeamTrialInternalResponse|1 trial #0?|2 start_enabled 8|3 active_seat_count 5",le]}}class Je extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Je).fromBinary(t,r)}static fromJson(t,r){return(new Je).fromJson(t,r)}static fromJsonString(t,r){return(new Je).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Je,t,r)}static $(){return["GetGrokCreditPackPurchaseAccountRequest"]}}class we extends w{constructor(t){super(),this.eligible=!1,this.xaiUserId="",this.ineligibleReason="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(we,t,r)}static $(){return["GetGrokCreditPackPurchaseAccountResponse|1 eligible 8|2 xai_user_id 9|3 ineligible_reason 9"]}}class ye extends w{constructor(t){super(),this.purchase={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ye,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest|1 apple #0 purchase|2 google #1 purchase",Se,qe]}}class Se extends w{constructor(t){super(),this.transactionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Se,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest.Apple|1 transaction_id 9"]}}class qe extends w{constructor(t){super(),this.purchaseToken="",this.productId="",this.packageName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qe,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest.Google|1 purchase_token 9|2 product_id 9|3 package_name 9"]}}class Be extends w{constructor(t){super(),this.outcome=Y.UNSPECIFIED,this.productId="",this.amountCents=s.protoInt64.zero,this.reason="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Be,t,r)}static $(){return["ReportGrokCreditPackPurchaseResponse|1 outcome #0|2 product_id 9|3 amount_cents 3|4 reason 9",Y]}}class Ie extends w{constructor(t){super(),this.teamId=0,this.userId=0,this.targetTier=n.tE_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ie).fromBinary(t,r)}static fromJson(t,r){return(new Ie).fromJson(t,r)}static fromJsonString(t,r){return(new Ie).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ie,t,r)}static $(){return["StartMergedTeamSeatChangeRequest|1 team_id 5|2 user_id 5|3 target_tier #0",n.tE_]}}class Pe extends w{constructor(t){super(),this.reason=Z.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pe).fromBinary(t,r)}static fromJson(t,r){return(new Pe).fromJson(t,r)}static fromJsonString(t,r){return(new Pe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pe,t,r)}static $(){return["MergedTeamSeatChangeRefusal|1 reason #0|2 message 9",Z]}}class be extends w{constructor(t){super(),this.result={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new be).fromBinary(t,r)}static fromJson(t,r){return(new be).fromJson(t,r)}static fromJsonString(t,r){return(new be).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(be,t,r)}static $(){return["StartMergedTeamSeatChangeResponse|1 checkout_url 9 result|2 refusal #0 result",Pe]}}class Re extends w{constructor(t){super(),this.teamId=0,this.userId=0,this.targetTier=n.tE_.UNSPECIFIED,this.idempotencyKey="",this.direct=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Re,t,r)}static $(){return["ChangeMergedTeamSeatRequest|1 team_id 5|2 user_id 5|3 target_tier #0|4 idempotency_key 9|5 direct 8",n.tE_]}}class ve extends w{constructor(t){super(),this.outcome=tt.UNSPECIFIED,this.message="",this.effectiveAt="",this.manageOnGrokUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ve).fromBinary(t,r)}static fromJson(t,r){return(new ve).fromJson(t,r)}static fromJsonString(t,r){return(new ve).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ve,t,r)}static $(){return["MergedTeamSeatChangeAnswer|1 outcome #0|2 message 9|3 effective_at 9|4 manage_on_grok_url 9|5 payment_challenge #1",tt,n._P7]}}class xe extends w{constructor(t){super(),this.result={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xe).fromBinary(t,r)}static fromJson(t,r){return(new xe).fromJson(t,r)}static fromJsonString(t,r){return(new xe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xe,t,r)}static $(){return["ChangeMergedTeamSeatResponse|1 checkout_url 9 result|2 refusal #0 result|3 answer #1 result",Pe,ve]}}class ke extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ke).fromBinary(t,r)}static fromJson(t,r){return(new ke).fromJson(t,r)}static fromJsonString(t,r){return(new ke).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ke,t,r)}static $(){return["GetMergedTeamSeatChangesRequest|1 team_id 5"]}}class Ee extends w{constructor(t){super(),this.userId=0,this.pendingTier=n.tE_.UNSPECIFIED,this.effectiveAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ee,t,r)}static $(){return["MergedTeamPendingSeatChange|1 user_id 5|2 pending_tier #0|3 effective_at 9",n.tE_]}}class Ce extends w{constructor(t){super(),this.directChangeEnabled=!1,this.pendingChangesAvailable=!1,this.pendingChanges=[],this.seatAvailabilityAvailable=!1,this.availablePaidSeatTiers=[],this.unavailablePaidSeatTiers=[],this.singleSeatPlan=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ce,t,r)}static $(){return["GetMergedTeamSeatChangesResponse|1 direct_change_enabled 8|2 pending_changes_available 8|3 pending_changes #0*|4 seat_availability_available 8|5 available_paid_seat_tiers #1*|6 unavailable_paid_seat_tiers #1*|7 single_seat_plan 8",Ee,n.tE_]}}class Te extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Te,t,r)}static $(){return["ListUnifiedInvoicesRequest|1 team_id 5?"]}}class Ue extends w{constructor(t){super(),this.invoiceId="",this.invoiceReference="",this.kind=rt.UNSPECIFIED,this.status=et.UNSPECIFIED,this.source=nt.UNSPECIFIED,this.issuedAtMs=s.protoInt64.zero,this.amountCents=s.protoInt64.zero,this.currency="",this.description="",this.pdfUrl="",this.pdfAssetKey="",this.hostedInvoiceUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ue,t,r)}static $(){return["UnifiedInvoice|1 invoice_id 9|2 invoice_reference 9|3 kind #0|4 status #1|5 source #2|6 issued_at_ms 3|7 period_start_ms 3?|8 period_end_ms 3?|9 amount_cents 3|10 currency 9|11 description 9|12 pdf_url 9|13 pdf_asset_key 9|14 hosted_invoice_url 9",rt,et,nt]}}class Ae extends w{constructor(t){super(),this.invoices=[],this.unavailableSources=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ae,t,r)}static $(){return["ListUnifiedInvoicesResponse|1 invoices #0*|2 unavailable_sources #1*",Ue,nt]}}class $e extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($e,t,r)}static $(){return["GetXaiCursorTeamMergeStatusRequest|1 team_id 5"]}}class Me extends w{constructor(t){super(),this.enabled=!1,this.merged=!1,this.xaiTeamId="",this.hasPendingProposal=!1,this.proposedXaiTeamId="",this.canConfirmProposal=!1,this.checkoutState=st.UNSPECIFIED,this.cart=[],this.hasPendingPurchase=!1,this.canCreateXaiTeam=!1,this.proposedXaiTeamName="",this.actingAdminGrokEmail="",this.adminReady=!1,this.legacyPrivacyAcknowledgementRequired=!1,this.intentPublicId="",this.processingBlockCode="",this.unifyBlocklisted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Me,t,r)}static $(){return["GetXaiCursorTeamMergeStatusResponse|1 enabled 8|2 merged 8|3 xai_team_id 9|4 merged_at_ms 3?|5 has_pending_proposal 8|6 proposed_xai_team_id 9|7 proposal_expires_at_ms 3?|8 can_confirm_proposal 8|9 checkout_state #0|10 cart #1*|11 has_pending_purchase 8|12 can_create_xai_team 8|13 proposed_xai_team_name 9|14 acting_admin_grok_linked 8?|15 legacy_billing_settlement #2?|16 acting_admin_grok_email 9|17 cursor_stripe_credit_balance_cents 3?|18 admin_ready 8|19 legacy_privacy_acknowledgement_required 8|20 wallet_ready 8?|21 intent_public_id 9|22 processing_block_code 9|23 unify_blocklisted 8",st,Oe,$t]}}class Oe extends w{constructor(t){super(),this.skuId="",this.quantity=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oe,t,r)}static $(){return["XaiCursorTeamCheckoutCartLine|1 sku_id 9|2 quantity 5"]}}class De extends w{constructor(t){super(),this.teamId=0,this.pageSize=0,this.offset=0,this.searchQuery="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(De,t,r)}static $(){return["GetXaiCursorTeamMembershipPreviewRequest|1 team_id 5|2 page_size 5|3 offset 5|4 search_query 9"]}}class Ne extends w{constructor(t){super(),this.userId=0,this.email="",this.name="",this.currentRole=it.UNSPECIFIED,this.intendedRole=it.UNSPECIFIED,this.cursorTeamRole=n.acM.UNSPECIFIED,this.cursorBillingTier=n.Xvt.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ne).fromBinary(t,r)}static fromJson(t,r){return(new Ne).fromJson(t,r)}static fromJsonString(t,r){return(new Ne).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ne,t,r)}static $(){return["XaiCursorTeamMembershipPreviewCursorMember|1 user_id 5|2 email 9|3 name 9|4 selected_sku_id 9?|5 current_role #0|6 intended_role #0|7 cursor_team_role #1|8 cursor_billing_tier #2|9 effective_sku_id 9?",it,n.acM,n.Xvt]}}class Ge extends w{constructor(t){super(),this.userId="",this.email="",this.givenName="",this.familyName="",this.previousSkuId="",this.currentRole=it.UNSPECIFIED,this.intendedRole=it.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ge).fromBinary(t,r)}static fromJson(t,r){return(new Ge).fromJson(t,r)}static fromJsonString(t,r){return(new Ge).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ge,t,r)}static $(){return["XaiCursorTeamMembershipPreviewGrokMember|1 user_id 9|2 email 9|3 given_name 9|4 family_name 9|5 selected_sku_id 9?|6 previous_sku_id 9|7 current_role #0|8 intended_role #0|9 effective_sku_id 9?",it]}}class Le extends w{constructor(t){super(),this.email="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Le).fromBinary(t,r)}static fromJson(t,r){return(new Le).fromJson(t,r)}static fromJsonString(t,r){return(new Le).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Le,t,r)}static $(){return["XaiCursorTeamMembershipPreviewMatch|1 email 9|2 cursor_member #0|3 grok_member #1",Ne,Ge]}}class Fe extends w{constructor(t){super(),this.enabled=!1,this.xaiRosterAvailable=!1,this.matched=[],this.cursorOnly=[],this.grokOnly=[],this.xaiSeatAssignmentsAvailable=!1,this.totalMemberCount=0,this.filteredMemberCount=0,this.nextOffset=0,this.hasMore=!1,this.skuCounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fe,t,r)}static $(){return["GetXaiCursorTeamMembershipPreviewResponse|1 enabled 8|2 xai_roster_available 8|3 matched #0*|4 cursor_only #1*|5 grok_only #2*|6 xai_seat_assignments_available 8|7 total_member_count 5|8 filtered_member_count 5|9 next_offset 5|10 has_more 8|11 sku_counts #3*|12 monthly_total_micros 3?",Le,Ne,Ge,Ke]}}class Ke extends w{constructor(t){super(),this.skuId="",this.memberCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ke,t,r)}static $(){return["XaiCursorTeamMembershipPreviewSkuCount|1 sku_id 9|2 member_count 5"]}}class ze extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",this.role=it.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ze,t,r)}static $(){return["XaiCursorTeamMemberRoleSelection|1 cursor_user_id 5|2 xai_user_id 9|3 role #0",it]}}class je extends w{constructor(t){super(),this.teamId=0,this.roleSelections=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(je,t,r)}static $(){return["UpdateXaiCursorTeamMemberRolesRequest|1 team_id 5|2 role_selections #0*",ze]}}class He extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(He,t,r)}static $(){return["UpdateXaiCursorTeamMemberRolesResponse"]}}class We extends w{constructor(t){super(),this.teamId=0,this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(We,t,r)}static $(){return["StartXaiCursorTeamMergeRequest|1 team_id 5|2 redirect_uri 9"]}}class Qe extends w{constructor(t){super(),this.connectUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qe,t,r)}static $(){return["StartXaiCursorTeamMergeResponse|1 connect_url 9"]}}class Ve extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ve,t,r)}static $(){return["GetXaiCursorTeamMergeGrokTeamsRequest|1 team_id 5"]}}class Xe extends w{constructor(t){super(),this.xaiTeamId="",this.name="",this.planTier="",this.memberCount=0,this.isBillingAdmin=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xe,t,r)}static $(){return["XaiCursorTeamMergeGrokTeam|1 xai_team_id 9|2 name 9|3 plan_tier 9|4 member_count 5|5 is_billing_admin 8"]}}class Ye extends w{constructor(t){super(),this.state=ot.UNSPECIFIED,this.signedInEmail="",this.eligibleTeams=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ye).fromBinary(t,r)}static fromJson(t,r){return(new Ye).fromJson(t,r)}static fromJsonString(t,r){return(new Ye).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ye,t,r)}static $(){return["GetXaiCursorTeamMergeGrokTeamsResponse|1 state #0|2 signed_in_email 9|3 eligible_teams #1*",ot,Xe]}}class Ze extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ze,t,r)}static $(){return["SelectXaiCursorTeamMergeGrokTeamRequest|1 team_id 5|2 xai_team_id 9"]}}class tn extends w{constructor(t){super(),this.success=!1,this.intentPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tn,t,r)}static $(){return["SelectXaiCursorTeamMergeGrokTeamResponse|1 success 8|2 selected_team #0|3 intent_public_id 9",Xe]}}class rn extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",this.skuSelections=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rn,t,r)}static $(){return["ConfirmXaiCursorTeamMergeRequest|1 team_id 5|2 xai_team_id 9|3 sku_selections #0*|4 checkout_outcome #1?",en,Br]}}class en extends w{constructor(t){super(),this.cursorUserId=0,this.skuId="",this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(en,t,r)}static $(){return["XaiCursorTeamMemberSkuSelection|1 cursor_user_id 5|2 sku_id 9|3 xai_user_id 9"]}}class nn extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nn,t,r)}static $(){return["XaiCursorTeamMemberRemoval|1 cursor_user_id 5|2 xai_user_id 9"]}}class sn extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sn,t,r)}static $(){return["XaiCursorTeamMemberPair|1 cursor_user_id 5|2 xai_user_id 9"]}}class on extends w{constructor(t){super(),this.merged=!1,this.xaiTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(on,t,r)}static $(){return["ConfirmXaiCursorTeamMergeResponse|1 merged 8|2 xai_team_id 9"]}}class an extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",this.skuSelections=[],this.removals=[],this.pairs=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(an,t,r)}static $(){return["PrepareXaiCursorTeamMergeCheckoutRequest|1 team_id 5|2 xai_team_id 9|3 sku_selections #0*|4 marketing_opted_out 8?|5 default_sku_id 9?|6 removals #1*|7 pairs #2*|8 legacy_privacy_acknowledged 8",en,nn,sn]}}class un extends w{constructor(t){super(),this.xaiTeamId="",this.cart=[],this.checkoutState=st.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(un,t,r)}static $(){return["PrepareXaiCursorTeamMergeCheckoutResponse|1 xai_team_id 9|2 cart #0*|3 checkout_state #1|4 legacy_privacy_acknowledgement_required 8",Oe,st]}}class cn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cn,t,r)}static $(){return["UnprepareXaiCursorTeamMergeCheckoutRequest|1 team_id 5"]}}class ln extends w{constructor(t){super(),this.xaiTeamId="",this.checkoutState=st.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ln,t,r)}static $(){return["UnprepareXaiCursorTeamMergeCheckoutResponse|1 xai_team_id 9|2 checkout_state #0",st]}}class mn extends w{constructor(t){super(),this.teamId=0,this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mn,t,r)}static $(){return["FinalizeXaiCursorTeamMergeCheckoutRequest|1 team_id 5|2 checkout_outcome #0?|3 legacy_privacy_acknowledged 8",Br]}}class fn extends w{constructor(t){super(),this.checkoutState=st.UNSPECIFIED,this.xaiTeamId="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fn,t,r)}static $(){return["FinalizeXaiCursorTeamMergeCheckoutResponse|1 checkout_state #0|2 xai_team_id 9|3 legacy_billing_settlement #1?|4 legacy_privacy_acknowledgement_required 8",st,$t]}}class dn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dn,t,r)}static $(){return["EnsureXaiCursorTeamForMergeRequest|1 team_id 5"]}}class pn extends w{constructor(t){super(),this.outcome=at.UNSPECIFIED,this.xaiTeamId="",this.created=!1,this.intentPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pn,t,r)}static $(){return["EnsureXaiCursorTeamForMergeResponse|3 outcome #0|1 xai_team_id 9|2 created 8|4 intent_public_id 9",at]}}class hn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hn,t,r)}static $(){return["GetXaiCursorTeamMergePrepaidPreviewRequest|1 team_id 5"]}}class gn extends w{constructor(t){super(),this.available=!1,this.grokBusinessSeats=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gn,t,r)}static $(){return["GetXaiCursorTeamMergePrepaidPreviewResponse|1 available 8|2 prepaid_balance_cents 3?|3 grok_auto_top_up #0?|4 grok_monthly_cap_cents 3?|5 grok_business_seats 8",n.xYM]}}class _n extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_n,t,r)}static $(){return["CancelXaiCursorTeamMergeProposalRequest|1 team_id 5"]}}class Jn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jn,t,r)}static $(){return["CancelXaiCursorTeamMergeProposalResponse"]}}class wn extends w{constructor(t){super(),this.cursorUserId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wn,t,r)}static $(){return["GetXaiEmailEligibilityInternalRequest|1 cursor_user_id 3"]}}class yn extends w{constructor(t){super(),this.kind=ut.UNSPECIFIED,this.accountExists=!1,this.xaiUserId="",this.shouldBeSuggested=!1,this.unificationStatus=ct.UNSPECIFIED,this.isLinkedToDifferentEmail=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yn,t,r)}static $(){return["GetXaiEmailEligibilityInternalResponse|1 kind #0|2 account_exists 8|3 xai_user_id 9|4 should_be_suggested 8|5 unification_status #1|6 is_linked_to_different_email 8",ut,ct]}}class Sn extends w{constructor(t){super(),this.xUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sn,t,r)}static $(){return["LookupGrokAccountsByXUserInternalRequest|1 x_user_id 9"]}}class qn extends w{constructor(t){super(),this.xaiSubject="",this.blocked=!1,this.isShadow=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qn,t,r)}static $(){return["GrokAccountByXUser|1 xai_subject 9|2 blocked 8|3 is_shadow 8"]}}class Bn extends w{constructor(t){super(),this.kind=lt.UNSPECIFIED,this.accounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bn,t,r)}static $(){return["LookupGrokAccountsByXUserInternalResponse|1 kind #0|2 accounts #1*",lt,qn]}}class In extends w{constructor(t){super(),this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(In,t,r)}static $(){return["StartUnifiedCheckoutRequest|1 tier 9|2 yearly 8"]}}class Pn extends w{constructor(t){super(),this.outcome=bn.UNSPECIFIED,this.checkoutUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pn,t,r)}static $(){return["StartUnifiedCheckoutResponse|1 outcome #0|2 checkout_url 9",bn]}}var bn=(0,i.QT)(s.proto3,J,"StartUnifiedCheckoutResponse.Outcome",[[0,"UNSPECIFIED"],[1,"CHECKOUT"],[2,"UNIFY_REQUIRED"],[3,"ALREADY_SUBSCRIBED"],[4,"NOT_AVAILABLE"],[5,"UNAVAILABLE"]],1);class Rn extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rn,t,r)}static $(){return["ParkUnifyGrokOAuthForAppSheetRequest|1 code 9|2 state 9"]}}class vn extends w{constructor(t){super(),this.handle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vn,t,r)}static $(){return["ParkUnifyGrokOAuthForAppSheetResponse|1 handle 9"]}}class xn extends w{constructor(t){super(),this.handle="",this.verifier="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xn,t,r)}static $(){return["CompleteUnifyGrokOAuthFromAppSheetRequest|1 handle 9|2 verifier 9"]}}class kn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kn,t,r)}static $(){return["GetUnifyAlreadyUnifiedMergeOfferRequest"]}}class En extends w{constructor(t){super(),this.offered=!1,this.offerId="",this.destinationEmail="",this.destinationKind=mt.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(En,t,r)}static $(){return["GetUnifyAlreadyUnifiedMergeOfferResponse|1 offered 8|2 offer_id 9|3 destination_email 9|4 destination_kind #0|5 legacy_privacy_acknowledgement_required 8",mt]}}class Cn extends w{constructor(t){super(),this.offerId="",this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cn,t,r)}static $(){return["StartUnifyAlreadyUnifiedMergeRequest|1 offer_id 9|2 legacy_privacy_acknowledged 8"]}}class Tn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tn,t,r)}static $(){return["StartUnifyAlreadyUnifiedMergeResponse"]}}class Un extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Un,t,r)}static $(){return["CancelUnifyAlreadyUnifiedMergeRequest"]}}class An extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(An,t,r)}static $(){return["CancelUnifyAlreadyUnifiedMergeResponse"]}}class $n extends w{constructor(t){super(),this.name="",this.privacyModeForced=!1,this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($n,t,r)}static $(){return["UnifiedTeamStartDraft|1 name 9|2 privacy_mode_forced 8|3 tier 9|4 yearly 8"]}}class Mn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mn,t,r)}static $(){return["ResolveUnifiedTeamStartRequest"]}}class On extends w{constructor(t){super(),this.state=Dn.UNSPECIFIED,this.message="",this.tiers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(On,t,r)}static $(){return["ResolveUnifiedTeamStartResponse|1 state #0|2 team_id 5?|3 draft #1|4 message 9|5 tiers 9*",Dn,$n]}}var Dn=(0,i.QT)(s.proto3,J,"ResolveUnifiedTeamStartResponse.State",[[0,"UNSPECIFIED"],[1,"STRIPE"],[2,"TEAM_READY"],[3,"ALREADY_ON_TEAM"],[4,"NAME_TEAM"],[5,"CHECKOUT"],[6,"AWAITING_PAYMENT"],[7,"CREATING_TEAM"],[8,"UNIFY_REQUIRED"],[9,"ALREADY_ON_PLAN"],[10,"NOT_AVAILABLE"],[11,"UNAVAILABLE"],[12,"CREATE_FAILED"]],1);class Nn extends w{constructor(t){super(),this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nn,t,r)}static $(){return["StartUnifiedTeamCheckoutRequest|1 tier 9|2 yearly 8|3 team #0",n.nxO]}}class Gn extends w{constructor(t){super(),this.state=Dn.UNSPECIFIED,this.checkoutUrl="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gn,t,r)}static $(){return["StartUnifiedTeamCheckoutResponse|1 state #0|2 team_id 5?|3 checkout_url 9|4 message 9",Dn]}}class Ln extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ln,t,r)}static $(){return["CreateGrokSignInLinkRequest|1 return_to 9?|2 cursor_return_path 9?"]}}class Fn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fn,t,r)}static $(){return["CreateGrokSignInLinkResponse|1 sign_in_url 9?"]}}class Kn extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kn,t,r)}static $(){return["ParkUnifyXLoginForAppSheetRequest|1 code 9|2 state 9"]}}class zn extends w{constructor(t){super(),this.handle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zn,t,r)}static $(){return["ParkUnifyXLoginForAppSheetResponse|1 handle 9"]}}class jn extends w{constructor(t){super(),this.handle="",this.verifier="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jn,t,r)}static $(){return["CompleteUnifyXLoginFromAppSheetRequest|1 handle 9|2 verifier 9"]}}class Hn extends w{constructor(t){super(),this.reason="",this.stage=Wn.UNSPECIFIED,this.alreadyLinkedToSelectedGrok=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hn,t,r)}static $(){return["UnificationIntentXAccountRefusal|1 reason 9|2 x_username 9?|3 stage #0|4 already_linked_to_selected_grok 8",Wn]}}var Wn=(0,i.QT)(s.proto3,J,"UnificationIntentXAccountRefusal.Stage",[[0,"UNSPECIFIED"],[1,"SIGN_IN"],[2,"FINALIZE"]],1);class Qn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qn,t,r)}static $(){return["GetUnifyWaitlistStatusRequest"]}}class Vn extends w{constructor(t){super(),this.status=_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vn,t,r)}static $(){return["GetUnifyWaitlistStatusResponse|1 status #0|2 joined_at #1?|3 granted_at #1?",_,s.Timestamp]}}class Xn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xn,t,r)}static $(){return["JoinUnifyWaitlistRequest"]}}class Yn extends w{constructor(t){super(),this.status=_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yn,t,r)}static $(){return["JoinUnifyWaitlistResponse|1 status #0|2 joined_at #1?",_,s.Timestamp]}}class Zn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zn,t,r)}static $(){return["GetPostPurchaseMergeOfferRequest"]}}class ts extends w{constructor(t){super(),this.offered=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ts,t,r)}static $(){return["GetPostPurchaseMergeOfferResponse|1 offered 8|2 super_grok_heavy_ultra_ended_notice #0",n.qKw]}}class rs extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rs,t,r)}static $(){return["GetUnifyMergeNowBannerRequest"]}}class es extends w{constructor(t){super(),this.show=!1,this.cursorPlanStillBilled=!1,this.paidPlanNotice=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(es,t,r)}static $(){return["GetUnifyMergeNowBannerResponse|1 show 8|2 cursor_plan_still_billed 8|3 paid_plan_notice 8"]}}var ns=e("../proto/dist/generated/agent/v1/mcp_pb.js"),ss=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const is="aiserver.v1.";class os extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return is}}class as extends os{constructor(t){super(),this.clientId="",this.redirectUris=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(as,t,r)}static $(){return["McpOAuthStoredData|1 refresh_token 9?|2 client_id 9|3 client_secret 9?|4 redirect_uris 9*|5 access_token 9?"]}}class us extends os{constructor(t){super(),this.state=cs.UNSPECIFIED,this.reason=ls.UNSPECIFIED,this.nextStep=ms.UNSPECIFIED,this.retryAfterSeconds=0,this.missingSetupFields=[],this.owner=fs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(us,t,r)}static $(){return["McpConnectorStatus|1 state #0|2 reason #1|3 next_step #2|4 retry_after_seconds 5|5 missing_setup_fields 9*|6 owner #3|7 placement #4",cs,ls,ms,fs,ds]}}var cs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.State",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NEEDS_SIGN_IN"],[3,"SIGN_IN_ENDED"],[4,"NEEDS_SETUP"],[5,"BLOCKED"],[6,"OFF"],[7,"UNAVAILABLE"],[8,"NOT_ON_THIS_SURFACE"],[9,"CHECKING"],[10,"ERROR"]],1),ls=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Reason",[[0,"UNSPECIFIED"],[1,"SIGN_OUT_EXPIRED"],[2,"SIGN_OUT_REVOKED"],[3,"SIGN_OUT_ORGANIZATION_POLICY"],[4,"SIGN_OUT_MFA_REQUIRED"],[5,"SIGN_OUT_ADMIN_BLOCKED"],[6,"SIGN_OUT_ACCOUNT_DISABLED"],[7,"SIGN_OUT_CLIENT_INVALID"],[8,"SIGN_OUT_ACCOUNT_RESTRICTED"],[9,"SIGN_OUT_PROVIDER_UNAVAILABLE"],[10,"SIGN_OUT_PROVIDER_ERROR"],[20,"BLOCKED_MCP_SERVERS_OFF"],[21,"BLOCKED_MCP_ALLOWLIST"],[22,"BLOCKED_CLOUD_AGENT_ALLOWLIST"],[23,"BLOCKED_DENYLIST"],[24,"BLOCKED_APPLIES_TO"],[25,"BLOCKED_NETWORK_ALLOWLIST"],[30,"SETUP_FIELDS"],[31,"SETUP_OAUTH_CLIENT"],[32,"SETUP_CREDENTIAL"],[33,"SETUP_INVALID_CONFIG"],[34,"SETUP_PROVIDER_ACCESS_OFF"],[40,"RUNS_ON_YOUR_COMPUTER"],[41,"COMMAND"],[42,"SERVERS_BLOCKED"],[43,"SERVERS_SIGN_IN_REFUSED"],[50,"RATE_LIMITED"],[51,"SIGN_IN_RENEWAL"],[52,"UNREACHABLE"],[53,"SIGN_IN_DISCOVERY"],[60,"NOT_FOUND"]],1),ms=(0,i.QT)(s.proto3,is,"McpConnectorStatus.NextStep",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"SIGN_IN"],[3,"SIGN_IN_AGAIN"],[4,"FINISH_SETUP"],[5,"ASK_ADMIN"],[6,"OPEN_CURSOR_APP"],[7,"WAIT"],[8,"SHOW_DETAILS"],[9,"MOVE_TO_CLOUD"],[10,"TURN_ON"]],1),fs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Owner",[[0,"UNSPECIFIED"],[1,"YOU"],[2,"TEAM"],[3,"PLUGIN"],[4,"THIS_COMPUTER"],[5,"THIS_PROJECT"]],1);class ds extends os{constructor(t){super(),this.runsOn=ps.UNSPECIFIED,this.chosenBy=hs.UNSPECIFIED,this.viewerMayChange=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ds,t,r)}static $(){return["McpConnectorStatus.Placement|1 runs_on #0|2 chosen_by #1|3 viewer_may_change 8",ps,hs]}}var ps=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Placement.RunsOn",[[0,"UNSPECIFIED"],[1,"SERVERS"],[2,"YOUR_COMPUTER"]],1),hs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Placement.ChosenBy",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"YOU"],[3,"TEAM_ADMIN"],[4,"TEAM_SETTING"],[5,"CONFIG_FILE"],[6,"UNREACHABLE"]],1);const gs="aiserver.v1.";class _s extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return gs}}var Js=(0,i.QT)(s.proto3,gs,"McpAllowlistImportList",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DENIED"]],1),ws=(0,i.QT)(s.proto3,gs,"McpAllowlistImportSurface",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD"],[3,"LOCAL_AND_CLOUD"]],1),ys=(0,i.QT)(s.proto3,gs,"McpAllowlistImportRowStatus",[[0,"UNSPECIFIED"],[1,"NEW"],[2,"UNCHANGED"],[3,"CONFLICT"]],1),Ss=(0,i.QT)(s.proto3,gs,"McpToolAccess",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"READ_ONLY"],[3,"SPECIFIC"]],1),qs=(0,i.QT)(s.proto3,gs,"TeamMcpPlacementDefault",[[0,"UNSPECIFIED"],[1,"UNSET"],[2,"CLIENT"]],1),Bs=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockExecutorKind",[[0,"UNSPECIFIED"],[1,"LOCAL_IDE"],[2,"REMOTE_EXTENSION_HOST"]],1),Is=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockBeginOutcome",[[0,"UNSPECIFIED"],[1,"SKIPPED"],[2,"WOULD_ACQUIRE"],[3,"WOULD_WAIT"],[4,"REDIS_ERROR"]],1),Ps=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockReleaseReason",[[0,"UNSPECIFIED"],[1,"COMPLETE"],[2,"ERROR"],[3,"ABANDONED"]],1),bs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteId",[[0,"UNSPECIFIED"],[1,"GOOGLE_WORKSPACE"],[2,"MICROSOFT_365"]],1),Rs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteMemberOutcome",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NOT_GRANTED"],[3,"INSTALL_REFUSED"],[4,"CLIENT_PLACED"],[5,"INSTALL_FAILED"],[6,"ALREADY_CONNECTED"],[7,"NOT_CONNECTED"],[8,"DISABLED"],[9,"STORE_FAILED"]],1),vs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteCoverage",[[0,"UNSPECIFIED"],[1,"FULL"],[2,"PARTIAL"],[3,"NONE"]],1),xs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteExposure",[[0,"NONE"],[1,"PASS"],[2,"FAIL"]],1),ks=(0,i.QT)(s.proto3,gs,"McpCloudVerdict",[[0,"UNSPECIFIED"],[1,"USABLE"],[2,"SIGN_IN"],[3,"MOVE_TO_CLOUD"],[4,"LOCAL_ONLY"],[5,"NEEDS_SETUP"],[6,"RETRY"]],1),Es=(0,i.QT)(s.proto3,gs,"McpSignInRefusalKind",[[0,"UNSPECIFIED"],[1,"STDIO"],[2,"CLIENT_ONLY"],[3,"SETUP_REQUIRED"],[4,"OAUTH_CLIENT_UNCONFIGURED"],[5,"REGISTRATION_UNAVAILABLE"],[6,"REGISTRATION_REJECTED"],[7,"RATE_LIMITED"],[8,"OAUTH_WEB_PAGE"],[9,"EGRESS_BLOCKED"],[10,"STATIC_CREDENTIAL"],[11,"ACCESS_DISABLED"],[12,"REFRESH_UNAVAILABLE"],[13,"REFRESH_RACE"],[14,"FRESH_TOKEN_REJECTED"],[15,"TRANSPORT_FAILURE"],[16,"INVALID_CONFIG"],[17,"NOT_FOUND"],[18,"PROBE_FAILED"]],1),Cs=(0,i.QT)(s.proto3,gs,"McpTransportFailureReason",[[0,"UNSPECIFIED"],[1,"DNS"],[2,"REFUSED"],[3,"TLS"],[4,"TIMEOUT"],[5,"HTTP_5XX"]],1),Ts=(0,i.QT)(s.proto3,gs,"McpConnectorAuthState",[[0,"UNSPECIFIED"],[1,"SIGNED_IN"],[2,"SIGNED_OUT"],[3,"UNAVAILABLE"]],1);class Us extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Us,t,r)}static $(){return["GetOrganizationGroupMcpSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class As extends _s{constructor(t){super(),this.separate=!1,this.allowedMcpServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(As,t,r)}static $(){return["GroupCloudMcpRules|1 separate 8|2 allowed_mcp_servers #0*",n.ufl]}}class $s extends _s{constructor(t){super(),this.mcpRuleSurfacesAvailable=!1,this.firstRuleAddsGrokConnectorsRule=!1,this.firstCloudRuleAddsGrokConnectorsRule=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($s,t,r)}static $(){return["GetOrganizationGroupMcpSettingsResponse|1 allowed_mcp_configuration #0|2 cloud_mcp_rules #1|3 mcp_rule_surfaces_available 8|4 first_rule_adds_grok_connectors_rule 8|5 first_cloud_rule_adds_grok_connectors_rule 8",n.ZM7,As]}}class Ms extends _s{constructor(t){super(),this.organizationId="",this.groupId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ms,t,r)}static $(){return["UpdateOrganizationGroupMcpSettingsRequest|1 organization_id 9|2 group_id 3|3 allowed_mcp_configuration #0|4 cloud_mcp_rules #1?",n.ZM7,As]}}class Os extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Os,t,r)}static $(){return["UpdateOrganizationGroupMcpSettingsResponse"]}}class Ds extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ds,t,r)}static $(){return["ExportOrganizationGroupMcpAllowlistRequest|1 organization_id 9|2 group_public_id 9"]}}class Ns extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ns,t,r)}static $(){return["ExportOrganizationGroupMcpAllowlistResponse|1 file_json 9"]}}class Gs extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gs,t,r)}static $(){return["ExportTeamMcpAllowlistRequest|1 team_id 5"]}}class Ls extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ls,t,r)}static $(){return["ExportTeamMcpAllowlistResponse|1 file_json 9"]}}class Fs extends _s{constructor(t){super(),this.path="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fs,t,r)}static $(){return["McpAllowlistImportIssue|1 path 9|2 message 9"]}}class Ks extends _s{constructor(t){super(),this.key="",this.list=Js.UNSPECIFIED,this.status=ys.UNSPECIFIED,this.existingList=Js.UNSPECIFIED,this.surface=ws.UNSPECIFIED,this.firstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ks,t,r)}static $(){return["McpAllowlistImportRow|1 key 9|2 list #0|3 status #1|4 incoming #2|5 existing #2?|6 existing_list #0|7 surface #3|8 first_rule_surface #3",Js,ys,n.ufl,ws]}}class zs extends _s{constructor(t){super(),this.rows=[],this.baseFingerprint="",this.targetInheritsTeamPolicy=!1,this.groupListsNarrowTeamPolicy=!1,this.addsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,this.addedBuiltinRulePatterns=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zs,t,r)}static $(){return["McpAllowlistImportPlan|1 rows #0*|2 base_fingerprint 9|3 target_inherits_team_policy 8|4 group_lists_narrow_team_policy 8|5 adds_grok_connectors_rule 8|6 cloud_drops_grok_connector_rules 8|7 added_builtin_rule_patterns 9*",Ks]}}class js extends _s{constructor(t){super(),this.issues=[],this.applied=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(js,t,r)}static $(){return["McpAllowlistImportResult|1 issues #0*|2 plan #1|3 applied 8",Fs,zs]}}class Hs extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],this.acknowledgeReplacesTeamPolicy=!1,this.acknowledgeFirstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hs,t,r)}static $(){return["ImportOrganizationGroupMcpAllowlistRequest|1 organization_id 9|2 group_public_id 9|3 file_json 9|4 dry_run 8|5 base_fingerprint 9|6 use_file_row_keys 9*|7 acknowledge_replaces_team_policy 8|8 acknowledge_first_rule_surface #0",ws]}}class Ws extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ws,t,r)}static $(){return["ImportOrganizationGroupMcpAllowlistResponse|1 result #0",js]}}class Qs extends _s{constructor(t){super(),this.teamId=0,this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qs,t,r)}static $(){return["ImportTeamMcpAllowlistRequest|1 team_id 5|2 file_json 9|3 dry_run 8|4 base_fingerprint 9|5 use_file_row_keys 9*"]}}class Vs extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vs,t,r)}static $(){return["ImportTeamMcpAllowlistResponse|1 result #0",js]}}class Xs extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xs).fromBinary(t,r)}static fromJson(t,r){return(new Xs).fromJson(t,r)}static fromJsonString(t,r){return(new Xs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xs,t,r)}static $(){return["GetTeamCloudAgentMcpAllowlistRequest|1 team_id 5"]}}class Ys extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ys,t,r)}static $(){return["GetTeamCloudAgentMcpAllowlistResponse|1 mcp_allowlist_cloud_mirrors_local 8?|2 cloud_allowed_mcp_configuration #0?|3 cloud_allowed_mcp_configuration_draft #0?",n.ZM7]}}class Zs extends _s{constructor(t){super(),this.teamId=0,this.startsWithDefaultRules=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zs,t,r)}static $(){return["UpdateTeamCloudAgentMcpAllowlistRequest|1 team_id 5|2 mcp_allowlist_cloud_mirrors_local 8?|3 cloud_allowed_mcp_configuration #0?|4 saved_mcp_allowlist #0?|5 starts_with_default_rules 8",n.ZM7]}}class ti extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ti,t,r)}static $(){return["UpdateTeamCloudAgentMcpAllowlistResponse|1 mcp_allowlist_cloud_mirrors_local 8?|2 cloud_allowed_mcp_configuration #0?",n.ZM7]}}class ri extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ri,t,r)}static $(){return["McpAllowlistRulePattern|1 server_url 9?|2 command 9?|3 off 8?"]}}class ei extends _s{constructor(t){super(),this.teamId=0,this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ei,t,r)}static $(){return["ListMcpAllowlistRuleMatchesRequest|1 team_id 5|2 rules #0*|3 include_member_servers 8?",ri]}}class ni extends _s{constructor(t){super(),this.kind=si.UNSPECIFIED,this.serverId=s.protoInt64.zero,this.serverName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ni,t,r)}static $(){return["McpAllowlistRuleMatch|1 kind #0|2 server_id 3|3 server_name 9|4 plugin_id 3?|5 plugin_name 9?",si]}}var si=(0,i.QT)(s.proto3,gs,"McpAllowlistRuleMatch.Kind",[[0,"UNSPECIFIED"],[1,"PLUGIN"],[2,"TEAM_MCP"]],1);class ii extends _s{constructor(t){super(),this.host="",this.memberCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ii,t,r)}static $(){return["McpAllowlistMemberServerMatch|1 host 9|2 member_count 5"]}}class oi extends _s{constructor(t){super(),this.matches=[],this.memberMatches=[],this.memberServersMatched=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oi,t,r)}static $(){return["McpAllowlistRuleMatches|1 matches #0*|2 match_count 5?|3 member_matches #1*|4 member_servers_matched 8",ni,ii]}}class ai extends _s{constructor(t){super(),this.rules=[],this.memberServersIncluded=!1,this.memberServersPartial=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ai,t,r)}static $(){return["ListMcpAllowlistRuleMatchesResponse|1 rules #0*|2 member_servers_included 8|3 member_servers_partial 8",oi]}}class ui extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ui,t,r)}static $(){return["GetTeamGroupMcpSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class ci extends _s{constructor(t){super(),this.baseList=li.UNSPECIFIED,this.groupEffect=mi.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ci,t,r)}static $(){return["MemberEffectiveMcpPolicySurface|1 allowed_mcp_configuration #0|2 base_list #1|3 group_effect #2",n.ZM7,li,mi]}}var li=(0,i.QT)(s.proto3,gs,"MemberEffectiveMcpPolicySurface.BaseList",[[0,"UNSPECIFIED"],[1,"MCP_ALLOWLIST"],[2,"CLOUD_AGENT_ALLOWLIST"]],1),mi=(0,i.QT)(s.proto3,gs,"MemberEffectiveMcpPolicySurface.GroupEffect",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"NARROWS"],[3,"REPLACES"]],1);class fi extends _s{constructor(t){super(),this.kind=di.UNSPECIFIED,this.teamGroupId=s.protoInt64.zero,this.directoryGroupId=0,this.owningTeamId=0,this.appliesToLocal=!1,this.appliesToCloud=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fi).fromBinary(t,r)}static fromJson(t,r){return(new fi).fromJson(t,r)}static fromJsonString(t,r){return(new fi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fi,t,r)}static $(){return["MemberMcpPolicyGroup|1 kind #0|2 team_group_id 3|3 directory_group_id 5|4 owning_team_id 5|5 applies_to_local 8|6 applies_to_cloud 8",di]}}var di=(0,i.QT)(s.proto3,gs,"MemberMcpPolicyGroup.Kind",[[0,"UNSPECIFIED"],[1,"TEAM_GROUP"],[2,"DIRECTORY_GROUP"]],1);class pi extends _s{constructor(t){super(),this.teamId=0,this.userId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pi,t,r)}static $(){return["GetTeamMemberEffectiveMcpPolicyRequest|1 team_id 5|2 user_id 5"]}}class hi extends _s{constructor(t){super(),this.groups=[],this.withheld=gi.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hi,t,r)}static $(){return["GetTeamMemberEffectiveMcpPolicyResponse|1 local #0|2 cloud #0|3 groups #1*|4 withheld #2",ci,fi,gi]}}var gi=(0,i.QT)(s.proto3,gs,"GetTeamMemberEffectiveMcpPolicyResponse.Withheld",[[0,"UNSPECIFIED"],[1,"ORGANIZATION_GROUP_RULES"],[2,"DIRECTORY_GROUP_RULES"]],1);class _i extends _s{constructor(t){super(),this.mcpRuleSurfacesAvailable=!1,this.firstRuleAddsGrokConnectorsRule=!1,this.firstCloudRuleAddsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_i,t,r)}static $(){return["GetTeamGroupMcpSettingsResponse|1 allowed_mcp_configuration #0|2 cloud_mcp_rules #1|3 mcp_rule_surfaces_available 8|4 first_rule_adds_grok_connectors_rule 8|5 first_cloud_rule_adds_grok_connectors_rule 8|6 cloud_drops_grok_connector_rules 8",n.ZM7,As]}}class Ji extends _s{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ji,t,r)}static $(){return["UpdateTeamGroupMcpSettingsRequest|1 team_id 5|2 group_id 3|3 allowed_mcp_configuration #0|4 cloud_mcp_rules #1?",n.ZM7,As]}}class wi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wi).fromBinary(t,r)}static fromJson(t,r){return(new wi).fromJson(t,r)}static fromJsonString(t,r){return(new wi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wi,t,r)}static $(){return["UpdateTeamGroupMcpSettingsResponse"]}}class yi extends _s{constructor(t){super(),this.teamId=0,this.builtinServer="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yi).fromBinary(t,r)}static fromJson(t,r){return(new yi).fromJson(t,r)}static fromJsonString(t,r){return(new yi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yi,t,r)}static $(){return["ListBuiltinMcpServerToolsRequest|1 team_id 5|2 builtin_server 9"]}}class Si extends _s{constructor(t){super(),this.tools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Si).fromBinary(t,r)}static fromJson(t,r){return(new Si).fromJson(t,r)}static fromJsonString(t,r){return(new Si).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Si,t,r)}static $(){return["ListBuiltinMcpServerToolsResponse|1 tools #0*",ns.gd]}}class qi extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qi,t,r)}static $(){return["ExportTeamGroupMcpAllowlistRequest|1 team_id 5|2 group_public_id 9"]}}class Bi extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bi,t,r)}static $(){return["ExportTeamGroupMcpAllowlistResponse|1 file_json 9"]}}class Ii extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],this.acknowledgeReplacesTeamPolicy=!1,this.acknowledgeFirstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ii,t,r)}static $(){return["ImportTeamGroupMcpAllowlistRequest|1 team_id 5|2 group_public_id 9|3 file_json 9|4 dry_run 8|5 base_fingerprint 9|6 use_file_row_keys 9*|7 acknowledge_replaces_team_policy 8|8 acknowledge_first_rule_surface #0",ws]}}class Pi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pi,t,r)}static $(){return["ImportTeamGroupMcpAllowlistResponse|1 result #0",js]}}class bi extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.redactSecrets=!1,this.expandPluginVariables=!1,this.localOverrideRowsOnly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bi,t,r)}static $(){return["GetMcpConfigRequest|1 team_scope 8|2 team_id 5|3 redact_secrets 8|4 expand_plugin_variables 8|5 local_override_rows_only 8"]}}class Ri extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ri).fromBinary(t,r)}static fromJson(t,r){return(new Ri).fromJson(t,r)}static fromJsonString(t,r){return(new Ri).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ri,t,r)}static $(){return["McpServerMetadata|1 plugin_id 3?|2 server_id 3|3 team_list_client_skip_reason 9?"]}}class vi extends _s{constructor(t){super(),this.configJson="",this.serverMetadataByName={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vi).fromBinary(t,r)}static fromJson(t,r){return(new vi).fromJson(t,r)}static fromJsonString(t,r){return(new vi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vi,t,r)}static $(){return["GetMcpConfigResponse|1 config_json 9|2 server_metadata_by_name 9,#0",Ri]}}class xi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xi).fromBinary(t,r)}static fromJson(t,r){return(new xi).fromJson(t,r)}static fromJsonString(t,r){return(new xi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xi,t,r)}static $(){return["GetEffectiveMcpConfigForUserRequest"]}}class ki extends _s{constructor(t){super(),this.configJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ki,t,r)}static $(){return["GetEffectiveMcpConfigForUserResponse|1 config_json 9"]}}class Ei extends _s{constructor(t){super(),this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ei,t,r)}static $(){return["GetAvailableMcpServersRequest|1 grok_bot_plugin_scope #0?|2 grok_bot_agent_id 9?|3 team_tailnet_rows_per_team 8|4 service_account_id 9?|5 grok_bot_session_id 9?",n.q0X]}}class Ci extends _s{constructor(t){super(),this.servers=[],this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ci,t,r)}static $(){return["GetAvailableMcpServersResponse|1 servers #0*|2 team_tailnet_rows_per_team 8",Ti]}}class Ti extends _s{constructor(t){super(),this.id=0,this.name="",this.isTeamServer=!1,this.enabled=!1,this.type="",this.args=[],this.isUnseen=!1,this.isRequired=!1,this.managedByTeamPluginPolicy=!1,this.disabledByTeamAdminPolicy=!1,this.accounts=[],this.hasStaticCredentialHeaders=!1,this.servedBy=n.JLr.UNSPECIFIED,this.needsGrant=!1,this.credentialIsCursorAccount=!1,this.singleAccount=!1,this.needsPluginSetup=!1,this.dataCenters=[],this.serverIdentifierAliases=[],this.grokSsoSignIn=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ti,t,r)}static $(){return["GetAvailableMcpServersResponse.McpServerInfo|1 id 5|2 name 9|3 is_team_server 8|4 enabled 8|5 type 9|6 command 9?|7 args 9*|8 url 9?|9 plugin_id 3?|10 is_unseen 8|11 user_has_access_token 8?|12 is_required 8|13 managed_by_team_plugin_policy 8|14 disabled_by_team_admin_policy 8|15 server_identifier 9?|16 owning_team_id 5?|17 accounts #0*|18 has_static_credential_headers 8|19 served_by #1|20 cursor_scm_provider 9?|21 logo_url 9?|22 needs_grant 8|23 credential_is_cursor_account 8|24 merge_connector_id 9?|25 grok_connector_id 9?|26 single_account 8|27 needs_plugin_setup 8|28 data_centers #2*|29 server_identifier_aliases 9*|30 plugin_display_name 9?|31 plugin_team 8?|32 disabled_by_cloud_agent_mcp_allowlist 8?|33 access #3?|34 blocked_reason #4?|35 grok_sso_sign_in 8|36 blocked_reason_text #5?|37 connector_status #6",Ai,n.JLr,Ui,Oi,ss.Zl,$i,us]}}class Ui extends _s{constructor(t){super(),this.id="",this.label="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ui,t,r)}static $(){return["GetAvailableMcpServersResponse.McpDataCenter|1 id 9|2 label 9"]}}class Ai extends _s{constructor(t){super(),this.accountKey="",this.serverIdentifier="",this.userHasAccessToken=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ai,t,r)}static $(){return["GetAvailableMcpServersResponse.McpAccountInfo|1 account_key 9|2 server_identifier 9|3 user_has_access_token 8|4 account_email 9?|5 display_name 9?|6 display_detail 9?"]}}class $i extends _s{constructor(t){super(),this.shortLine="",this.detailLine="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $i).fromBinary(t,r)}static fromJson(t,r){return(new $i).fromJson(t,r)}static fromJsonString(t,r){return(new $i).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($i,t,r)}static $(){return["McpBlockedReasonText|1 short_line 9|2 detail_line 9"]}}class Mi extends _s{constructor(t){super(),this.allowed=!1,this.blockedReason=ss.Zl.UNSPECIFIED,this.toolAccess=Ss.UNSPECIFIED,this.allowedToolNames=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mi).fromBinary(t,r)}static fromJson(t,r){return(new Mi).fromJson(t,r)}static fromJsonString(t,r){return(new Mi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mi,t,r)}static $(){return["McpSurfaceAccess|1 allowed 8|2 blocked_reason #0|3 tool_access #1|4 allowed_tool_names 9*",ss.Zl,Ss]}}class Oi extends _s{constructor(t){super(),this.appliesTo=n.Vsr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oi).fromBinary(t,r)}static fromJson(t,r){return(new Oi).fromJson(t,r)}static fromJsonString(t,r){return(new Oi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oi,t,r)}static $(){return["McpServerAccess|1 applies_to #0|2 local #1|3 cloud #1",n.Vsr,Mi]}}class Di extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.serverIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Di).fromBinary(t,r)}static fromJson(t,r){return(new Di).fromJson(t,r)}static fromJsonString(t,r){return(new Di).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Di,t,r)}static $(){return["GetMcpServerUsageSummaryRequest|1 team_scope 8|2 team_id 5|3 server_ids 3*"]}}class Ni extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,this.enabledUserCount=0,this.automationCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ni).fromBinary(t,r)}static fromJson(t,r){return(new Ni).fromJson(t,r)}static fromJsonString(t,r){return(new Ni).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ni,t,r)}static $(){return["McpServerUsageSummary|1 server_id 3|2 enabled_user_count 5|3 automation_count 5"]}}class Gi extends _s{constructor(t){super(),this.summaries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gi).fromBinary(t,r)}static fromJson(t,r){return(new Gi).fromJson(t,r)}static fromJsonString(t,r){return(new Gi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gi,t,r)}static $(){return["GetMcpServerUsageSummaryResponse|1 summaries #0*",Ni]}}class Li extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.configJson="",this.serverRenames={},this.serverIdsByName={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Li).fromBinary(t,r)}static fromJson(t,r){return(new Li).fromJson(t,r)}static fromJsonString(t,r){return(new Li).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Li,t,r)}static $(){return["SetMcpConfigRequest|1 team_scope 8|2 team_id 5|3 config_json 9|4 server_renames 9,9|5 server_ids_by_name 9,3"]}}class Fi extends _s{constructor(t){super(),this.addedTeamServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fi).fromBinary(t,r)}static fromJson(t,r){return(new Fi).fromJson(t,r)}static fromJsonString(t,r){return(new Fi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fi,t,r)}static $(){return["SetMcpConfigResponse|1 added_team_servers #0*",sa]}}class Ki extends _s{constructor(t){super(),this.serverName="",this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ki).fromBinary(t,r)}static fromJson(t,r){return(new Ki).fromJson(t,r)}static fromJsonString(t,r){return(new Ki).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ki,t,r)}static $(){return["MoveUserMcpServerToTeamRequest|1 server_name 9|2 team_id 5"]}}class zi extends _s{constructor(t){super(),this.addedTeamServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zi).fromBinary(t,r)}static fromJson(t,r){return(new zi).fromJson(t,r)}static fromJsonString(t,r){return(new zi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zi,t,r)}static $(){return["MoveUserMcpServerToTeamResponse|1 added_team_servers #0*",sa]}}class ji extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ji).fromBinary(t,r)}static fromJson(t,r){return(new ji).fromJson(t,r)}static fromJsonString(t,r){return(new ji).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ji,t,r)}static $(){return["GetTeamMcpPlacementDefaultRequest|1 team_id 5"]}}class Hi extends _s{constructor(t){super(),this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hi).fromBinary(t,r)}static fromJson(t,r){return(new Hi).fromJson(t,r)}static fromJsonString(t,r){return(new Hi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hi,t,r)}static $(){return["GetTeamMcpPlacementDefaultResponse|1 placement_default #0",qs]}}class Wi extends _s{constructor(t){super(),this.teamId=0,this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wi).fromBinary(t,r)}static fromJson(t,r){return(new Wi).fromJson(t,r)}static fromJsonString(t,r){return(new Wi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wi,t,r)}static $(){return["UpdateTeamMcpPlacementDefaultRequest|1 team_id 5|2 placement_default #0",qs]}}class Qi extends _s{constructor(t){super(),this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qi).fromBinary(t,r)}static fromJson(t,r){return(new Qi).fromJson(t,r)}static fromJsonString(t,r){return(new Qi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qi,t,r)}static $(){return["UpdateTeamMcpPlacementDefaultResponse|1 placement_default #0",qs]}}class Vi extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vi).fromBinary(t,r)}static fromJson(t,r){return(new Vi).fromJson(t,r)}static fromJsonString(t,r){return(new Vi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vi,t,r)}static $(){return["MigrateTeamMcpServersToDefaultMarketplaceRequest|1 team_id 5"]}}class Xi extends _s{constructor(t){super(),this.migratedCount=0,this.skippedCount=0,this.defaultMarketplaceId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xi).fromBinary(t,r)}static fromJson(t,r){return(new Xi).fromJson(t,r)}static fromJsonString(t,r){return(new Xi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xi,t,r)}static $(){return["MigrateTeamMcpServersToDefaultMarketplaceResponse|1 migrated_count 5|2 skipped_count 5|3 default_marketplace_id 3"]}}class Yi extends _s{constructor(t){super(),this.enabledServerIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yi).fromBinary(t,r)}static fromJson(t,r){return(new Yi).fromJson(t,r)}static fromJsonString(t,r){return(new Yi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yi,t,r)}static $(){return["UpdateUserDefaultMcpSettingsRequest|1 enabled_server_ids 5*"]}}class Zi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zi).fromBinary(t,r)}static fromJson(t,r){return(new Zi).fromJson(t,r)}static fromJsonString(t,r){return(new Zi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zi,t,r)}static $(){return["UpdateUserDefaultMcpSettingsResponse"]}}class to extends _s{constructor(t){super(),this.serverKey="",this.reads=ro.UNSPECIFIED,this.writes=ro.UNSPECIFIED,this.disabledTools=[],this.onlyIfAbsent=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new to).fromBinary(t,r)}static fromJson(t,r){return(new to).fromJson(t,r)}static fromJsonString(t,r){return(new to).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(to,t,r)}static $(){return["UserMcpToolChoice|1 server_key 9|2 reads #0|3 writes #0|4 disabled_tools 9*|5 only_if_absent 8",ro]}}var ro=(0,i.QT)(s.proto3,gs,"UserMcpToolChoice.GroupSelector",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"OFF"],[3,"CUSTOM"]],1);class eo extends _s{constructor(t){super(),this.choices=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eo).fromBinary(t,r)}static fromJson(t,r){return(new eo).fromJson(t,r)}static fromJsonString(t,r){return(new eo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(eo,t,r)}static $(){return["SetUserMcpToolChoicesRequest|1 choices #0*",to]}}class no extends _s{constructor(t){super(),this.results=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new no).fromBinary(t,r)}static fromJson(t,r){return(new no).fromJson(t,r)}static fromJsonString(t,r){return(new no).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(no,t,r)}static $(){return["SetUserMcpToolChoicesResponse|1 results #0*",so]}}var so=(0,i.QT)(s.proto3,gs,"SetUserMcpToolChoicesResponse.Result",[[0,"UNSPECIFIED"],[1,"STORED"],[2,"REMOVED"],[3,"KEPT"],[4,"REFUSED"]],1);class io extends _s{constructor(t){super(),this.serverIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new io).fromBinary(t,r)}static fromJson(t,r){return(new io).fromJson(t,r)}static fromJsonString(t,r){return(new io).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(io,t,r)}static $(){return["MarkMcpServersSeenRequest|1 server_ids 5*"]}}class oo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oo).fromBinary(t,r)}static fromJson(t,r){return(new oo).fromJson(t,r)}static fromJsonString(t,r){return(new oo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oo,t,r)}static $(){return["MarkMcpServersSeenResponse"]}}class ao extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ao,t,r)}static $(){return["StoreMcpOAuthTokenRequest|1 server_url 9|2 refresh_token 9?|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 access_token 9?|7 service_account_id 9?|8 client_token_created_at_ms 3?|9 source 9?|10 account_key 9"]}}class uo extends _s{constructor(t){super(),this.applied=!1,this.skippedBecauseBackendNewer=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uo,t,r)}static $(){return["StoreMcpOAuthTokenResponse|1 updated_at_ms 3?|2 applied 8|3 skipped_because_backend_newer 8"]}}class co extends _s{constructor(t){super(),this.serverUrls=[],this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(co,t,r)}static $(){return["GetMcpOAuthTokensRequest|1 server_urls 9*|2 service_account_id 9?|3 account_key 9"]}}class lo extends _s{constructor(t){super(),this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lo,t,r)}static $(){return["GetMcpOAuthTokensResponse|1 entries #0*",mo]}}class mo extends _s{constructor(t){super(),this.serverUrl="",this.updatedAtMs=s.protoInt64.zero,this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mo,t,r)}static $(){return["GetMcpOAuthTokensResponse.Entry|1 server_url 9|2 token_data #0|3 updated_at_ms 3|4 account_key 9",as]}}class fo extends _s{constructor(t){super(),this.teamId=0,this.serverId=s.protoInt64.zero,this.oauthRedirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fo,t,r)}static $(){return["PreviewTeamMcpToolsRequest|1 team_id 5|2 server_id 3|3 oauth_redirect_uri 9"]}}class po extends _s{constructor(t){super(),this.status="",this.tools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(po,t,r)}static $(){return["PreviewTeamMcpToolsResponse|1 status 9|2 auth_url 9?|3 error 9?|4 tools #0*",ns.gd]}}class ho extends _s{constructor(t){super(),this.serverUrl="",this.executorKind=Bs.UNSPECIFIED,this.executorId="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ho,t,r)}static $(){return["McpOAuthRefreshLockBeginRequest|1 server_url 9|2 executor_kind #0|3 executor_id 9|4 observed_updated_at_ms 3?|5 service_account_id 9?|6 account_key 9",Bs]}}class go extends _s{constructor(t){super(),this.outcome=Is.UNSPECIFIED,this.shouldEnforce=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(go,t,r)}static $(){return["McpOAuthRefreshLockBeginResponse|1 outcome #0|2 lease_handle 9?|3 should_enforce 8",Is]}}class _o extends _s{constructor(t){super(),this.leaseHandle="",this.reason=Ps.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_o,t,r)}static $(){return["McpOAuthRefreshLockReleaseRequest|1 lease_handle 9|2 reason #0",Ps]}}class Jo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jo,t,r)}static $(){return["McpOAuthRefreshLockReleaseResponse"]}}class wo extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wo,t,r)}static $(){return["DeleteMcpOAuthTokenRequest|1 server_url 9|2 service_account_id 9?|3 source 9?|4 account_key 9|5 server_identifier 9?"]}}class yo extends _s{constructor(t){super(),this.outcome=So.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yo,t,r)}static $(){return["DeleteMcpOAuthTokenResponse|1 outcome #0",So]}}var So=(0,i.QT)(s.proto3,gs,"DeleteMcpOAuthTokenResponse.Outcome",[[0,"UNSPECIFIED"],[1,"DELETED"],[2,"NOT_FOUND"]],1);class qo extends _s{constructor(t){super(),this.serverUrls=[],this.targets=[],this.serverIdentifiers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qo,t,r)}static $(){return["ValidateMcpOAuthTokensRequest|1 server_urls 9*|2 service_account_id 9?|3 targets #0*|4 server_identifiers 9*",Bo]}}class Bo extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bo,t,r)}static $(){return["ValidateMcpOAuthTokensRequest.Target|1 server_url 9|2 account_key 9"]}}class Io extends _s{constructor(t){super(),this.results=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Io,t,r)}static $(){return["ValidateMcpOAuthTokensResponse|1 results #0*",Po]}}class Po extends _s{constructor(t){super(),this.serverUrl="",this.hasValidToken=!1,this.accountKey="",this.servedBy=n.JLr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Po,t,r)}static $(){return["ValidateMcpOAuthTokensResponse.Result|1 server_url 9|2 has_valid_token 8|3 account_key 9|4 server_identifier 9?|5 served_by #0|6 auth_state #1?",n.JLr,Ts]}}class bo extends _s{constructor(t){super(),this.suiteId=bs.UNSPECIFIED,this.memberPluginIds=[],this.driveCoversEditors=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bo,t,r)}static $(){return["ConnectorSuiteOffer|1 suite_id #0|2 member_plugin_ids 3*|3 drive_covers_editors 8",bs]}}class Ro extends _s{constructor(t){super(),this.suiteId=bs.UNSPECIFIED,this.memberPluginIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ro,t,r)}static $(){return["ConnectorSuiteSelection|1 suite_id #0|2 member_plugin_ids 3*",bs]}}class vo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.serverUrl="",this.outcome=Rs.UNSPECIFIED,this.coverage=vs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vo,t,r)}static $(){return["ConnectorSuiteMemberResult|1 plugin_id 3|2 server_url 9|3 outcome #0|4 coverage #1",Rs,vs]}}class xo extends _s{constructor(t){super(),this.serverIds=[],this.oauthRedirectUri="",this.forceReauth=!1,this.accountKey="",this.serverIdentifiers=[],this.statusOnly=!1,this.showMcpAccessDisabledStatus=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xo,t,r)}static $(){return["CheckHttpMcpStatusRequest|1 server_ids 5*|2 oauth_redirect_uri 9|3 team_id 5?|4 service_account_id 9?|5 force_reauth 8|6 service_account_type 9?|7 post_auth_return_url 9?|8 account_key 9|9 server_identifiers 9*|10 grok_bot_plugin_scope #0?|11 grok_bot_agent_id 9?|12 status_only 8|13 show_mcp_access_disabled_status 8|14 user_initiated 8?|15 data_center 9?|16 share_with_bot_agent_id 9?|17 share_with_bot_plugin_id 3?|18 share_acknowledged_warning_version 5?|19 texted_sign_in 8?|20 grok_bot_session_id 9?|21 connector_suite_capable 8?|22 connector_suite #1?",n.q0X,Ro]}}class ko extends _s{constructor(t){super(),this.statuses=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ko,t,r)}static $(){return["CheckHttpMcpStatusResponse|1 statuses #0*",Eo]}}class Eo extends _s{constructor(t){super(),this.id=0,this.isAvailable=!1,this.requiresAuth=!1,this.hasValidToken=!1,this.servedBy=n.JLr.UNSPECIFIED,this.signedIn=!1,this.cloudVerdict=ks.UNSPECIFIED,this.connectorSuiteExposure=xs.NONE,this.grokSsoSignIn=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Eo,t,r)}static $(){return["CheckHttpMcpStatusResponse.ServerStatus|1 id 5|2 is_available 8|3 requires_auth 8|4 auth_url 9?|5 error 9?|6 has_valid_token 8|7 server_identifier 9?|8 served_by #0|9 sign_out #1?|10 sign_in_refusal #2?|11 signed_in 8|12 cloud_verdict #3|13 connector_suite_offer #4?|14 connector_suite_exposure #5|15 grok_sso_sign_in 8|16 connector_status #6",n.JLr,n.eJC,Co,ks,bo,xs,us]}}class Co extends _s{constructor(t){super(),this.kind=Es.UNSPECIFIED,this.missingSetupFields=[],this.sharedBackoff=!1,this.transportFailureReason=Cs.UNSPECIFIED,this.runsLocally=!1,this.retryAfterSeconds=0,this.quietReconnect=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Co,t,r)}static $(){return["McpSignInRefusal|1 kind #0|2 missing_setup_fields 9*|3 shared_backoff 8|4 transport_failure_reason #1|5 runs_locally 8|6 retry_after_seconds 5|7 sign_in_start_held_seconds 5?|8 quiet_reconnect 8",Es,Cs]}}class To extends _s{constructor(t){super(),this.serverUrl="",this.codeVerifier="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(To,t,r)}static $(){return["StoreMcpOAuthPendingStateRequest|1 server_url 9|2 code_verifier 9|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 service_account_id 9?|7 account_key 9"]}}class Uo extends _s{constructor(t){super(),this.stateId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uo,t,r)}static $(){return["StoreMcpOAuthPendingStateResponse|1 state_id 9"]}}class Ao extends _s{constructor(t){super(),this.stateId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ao,t,r)}static $(){return["GetMcpOAuthPendingStateRequest|1 state_id 9"]}}class $o extends _s{constructor(t){super(),this.serverUrl="",this.codeVerifier="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($o,t,r)}static $(){return["GetMcpOAuthPendingStateResponse|1 server_url 9|2 code_verifier 9|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 service_account_id 9?|7 post_auth_return_url 9?|8 account_key 9"]}}class Mo extends _s{constructor(t){super(),this.stateId="",this.authorizationCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mo,t,r)}static $(){return["CompleteMcpOAuthRequest|1 state_id 9|2 authorization_code 9|3 oauth_error 9?"]}}class Oo extends _s{constructor(t){super(),this.postAuthReturnUrl="",this.accountKey="",this.connectorSuiteResult=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oo,t,r)}static $(){return["CompleteMcpOAuthResponse|1 post_auth_return_url 9|2 account_key 9|3 tailnet_pending_reason 9?|4 tailnet_pending_detail 9?|5 connector_suite_result #0*|6 continue_authorization_url 9?",vo]}}class Do extends _s{constructor(t){super(),this.stateId="",this.authorizationCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Do,t,r)}static $(){return["HandOffMcpOAuthCodeRequest|1 state_id 9|2 authorization_code 9"]}}class No extends _s{constructor(t){super(),this.codeHandle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(No,t,r)}static $(){return["HandOffMcpOAuthCodeResponse|1 code_handle 9"]}}class Go extends _s{constructor(t){super(),this.serverId=0,this.accountKey="",this.newAccountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Go,t,r)}static $(){return["RenameMcpOAuthAccountRequest|1 server_id 5|2 account_key 9|3 new_account_key 9|4 grok_bot_plugin_scope #0?|5 grok_bot_agent_id 9?|6 grok_bot_session_id 9?",n.q0X]}}class Lo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lo,t,r)}static $(){return["RenameMcpOAuthAccountResponse"]}}class Fo extends _s{constructor(t){super(),this.serverId=0,this.accountKey="",this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fo,t,r)}static $(){return["DeleteMcpOAuthAccountRequest|1 server_id 5|2 account_key 9|3 server_url 9|4 grok_bot_plugin_scope #0?|5 grok_bot_agent_id 9?|6 grok_bot_session_id 9?",n.q0X]}}class Ko extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ko,t,r)}static $(){return["DeleteMcpOAuthAccountResponse"]}}class zo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zo,t,r)}static $(){return["GetPluginMcpConfigRequest|1 plugin_id 3"]}}class jo extends _s{constructor(t){super(),this.configJson="",this.commitSha="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jo,t,r)}static $(){return["GetPluginMcpConfigResponse|1 config_json 9|2 commit_sha 9"]}}class Ho extends _s{constructor(t){super(),this.pluginIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ho,t,r)}static $(){return["BatchGetPluginMcpConfigRequest|1 plugin_ids 3*"]}}class Wo extends _s{constructor(t){super(),this.configJson="",this.commitSha="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wo,t,r)}static $(){return["PluginMcpConfigEntry|1 config_json 9|2 commit_sha 9"]}}class Qo extends _s{constructor(t){super(),this.configs={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qo,t,r)}static $(){return["BatchGetPluginMcpConfigResponse|1 configs 3,#0",Wo]}}class Vo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.scope="",this.substitutions={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vo,t,r)}static $(){return["AddMcpServersFromPluginRequest|1 plugin_id 3|2 scope 9|3 team_id 5?|4 commit_sha 9?|5 server_name 9?|6 substitutions 9,9|7 oauth_redirect_uri 9?"]}}class Xo extends _s{constructor(t){super(),this.addedServerIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xo,t,r)}static $(){return["AddMcpServersFromPluginResponse|1 added_server_ids 3*"]}}class Yo extends _s{constructor(t){super(),this.url="",this.headers={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yo,t,r)}static $(){return["ProbeMcpUrlRequest|1 url 9|2 headers 9,9|3 oauth_redirect_uri 9?|4 auth_client_id 9?|5 auth_client_secret 9?"]}}class Zo extends _s{constructor(t){super(),this.isAvailable=!1,this.requiresAuth=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zo,t,r)}static $(){return["ProbeMcpUrlResponse|1 is_available 8|2 requires_auth 8|3 auth_url 9?|4 error 9?"]}}class ta extends _s{constructor(t){super(),this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ta,t,r)}static $(){return["GetMcpBackendAccessTokenRequest|1 server_url 9"]}}class ra extends _s{constructor(t){super(),this.needsAuth=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ra,t,r)}static $(){return["GetMcpBackendAccessTokenResponse|1 needs_auth 8|2 access_token 9?"]}}class ea extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.mcpConfigJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ea,t,r)}static $(){return["UpdatePluginMcpConfigRequest|1 plugin_id 3|2 mcp_config_json 9|3 team_id 5?"]}}class na extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(na,t,r)}static $(){return["UpdatePluginMcpConfigResponse|1 plugin #0",n.k_1]}}class sa extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sa,t,r)}static $(){return["TeamMcpServerAddCheck|1 server_id 3|2 name 9|3 local #0|4 cloud #0",n.mne]}}class ia extends _s{constructor(t){super(),this.marketplaceId=s.protoInt64.zero,this.action={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ia,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest|1 marketplace_id 3|2 team_id 5?|3 set_policies #0 action|4 remove_marketplace #1 action|5 set_policies_across_marketplaces #2 action",oa,aa,ua]}}class oa extends _s{constructor(t){super(),this.policies=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oa,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesPreview|1 policies #0*",n.G_8]}}class aa extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(aa,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.RemoveMarketplacePreview"]}}class ua extends _s{constructor(t){super(),this.marketplaces=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ua,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesAcrossMarketplacesPreview|1 marketplaces #0*",ca]}}class ca extends _s{constructor(t){super(),this.marketplaceId=s.protoInt64.zero,this.policies=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ca,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesAcrossMarketplacesPreview.MarketplacePolicies|1 marketplace_id 3|2 policies #0*",n.G_8]}}class la extends _s{constructor(t){super(),this.impactedPlugins=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(la,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactResponse|1 impacted_plugins #0*",ma]}}class ma extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.pluginName="",this.mcpServerNames=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ma,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactResponse.ImpactedPlugin|1 plugin_id 3|2 plugin_name 9|3 mcp_server_names 9*"]}}var fa=e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js");const da="aiserver.v1.";class pa extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return da}}var ha=(0,i.QT)(s.proto3,da,"GrokBotAccessRole",[[0,"UNSPECIFIED"],[1,"USER"],[2,"MANAGER"]],1);class ga extends pa{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ga,t,r)}static $(){return["GrokBotAccessTeamPrincipal"]}}class _a extends pa{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_a,t,r)}static $(){return["GrokBotAccessOrganizationPrincipal"]}}class Ja extends pa{constructor(t){super(),this.principal={case:void 0},this.role=ha.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ja,t,r)}static $(){return["GrokBotAccessPrincipal|1 team #0 principal|2 user_id 5 principal|3 group_id 3 principal|5 other_team_id 5 principal|6 organization #1 principal|4 role #2|7 invited_as_email 9?",ga,_a,ha]}}class wa extends pa{constructor(t){super(),this.principals=[],this.teamRowOn=!1,this.availableRoles=[],this.expectedStateToken="",this.groupsEnabled=!1,this.teamRowOffAllowed=!1,this.crossTeamSharingEnabled=!1,this.callerMayEditCrossTeamRows=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wa,t,r)}static $(){return["GrokBotAgentAccessState|1 principals #0*|2 team_row_on 8|3 available_roles #1*|4 expected_state_token 9|5 groups_enabled 8|6 team_row_off_allowed 8|7 cross_team_sharing_enabled 8|8 caller_may_edit_cross_team_rows 8",Ja,ha]}}class ya extends pa{constructor(t){super(),this.principals=[],this.expectedStateToken="",this.listsCrossTierPrincipals=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ya,t,r)}static $(){return["GrokBotAgentAccessUpdate|1 principals #0*|2 expected_state_token 9|3 lists_cross_tier_principals 8",Ja]}}const Sa="aiserver.v1.";class qa extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Sa}}var Ba=(0,i.QT)(s.proto3,Sa,"GrokBotTransferRole",[[0,"UNSPECIFIED"],[1,"VIEWER"],[2,"USER"],[3,"MANAGER"]],1),Ia=(0,i.QT)(s.proto3,Sa,"GrokBotTransferActorRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"SOURCE_ADMIN"],[3,"ORG_ADMIN"],[4,"CURSOR_SUPPORT"]],1),Pa=(0,i.QT)(s.proto3,Sa,"GrokBotTransferGroupDropReason",[[0,"UNSPECIFIED"],[1,"MANUAL"],[2,"NOT_LINKED_ON_DESTINATION"],[3,"CURSOR_GROUP_SOURCE"]],1),ba=(0,i.QT)(s.proto3,Sa,"GrokBotTransferTeamRowSource",[[0,"UNSPECIFIED"],[1,"SOURCE_TEAM_ROW"],[2,"OTHER_TEAM_SHARE"],[3,"BOTH"]],1),Ra=(0,i.QT)(s.proto3,Sa,"GrokBotTransferWarningKind",[[0,"UNSPECIFIED"],[1,"CROSS_TEAM_SHARING_MISMATCH"],[2,"TEAMS_ADMIN_GRANT_MISSING"],[3,"DESTINATION_TEAM_ROW_MANAGER"],[4,"OWNER_NOT_ON_DESTINATION"]],1),va=(0,i.QT)(s.proto3,Sa,"GrokBotTransferOutcome",[[0,"UNSPECIFIED"],[1,"TRANSFERRED"],[2,"ALREADY_ON_TEAM"],[3,"NOT_PERMITTED"],[4,"NOT_ELIGIBLE"],[5,"DESTINATION_NOT_READY"],[6,"PLAN_STALE"],[7,"BUSY"],[8,"STARTED"],[9,"FAILED"]],1),xa=(0,i.QT)(s.proto3,Sa,"GrokBotTransferState",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"DONE"],[3,"FAILED"],[4,"ROLLED_BACK"]],1);class ka extends qa{constructor(t){super(),this.teamId=0,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ka,t,r)}static $(){return["GrokBotTransferTeamRef|1 team_id 5|2 name 9"]}}class Ea extends qa{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ea,t,r)}static $(){return["GrokBotTransferUserRef|1 user_id 5|2 name 9|3 email 9|4 role #0",Ba]}}class Ca extends qa{constructor(t){super(),this.groupId=s.protoInt64.zero,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ca,t,r)}static $(){return["GrokBotTransferGroupRef|1 group_id 3|2 name 9"]}}class Ta extends qa{constructor(t){super(),this.destinationGroups=[],this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ta,t,r)}static $(){return["GrokBotTransferCarriedGroup|1 source_group #0|2 destination_groups #0*|3 role #1",Ca,Ba]}}class Ua extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,this.reason=Pa.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ua,t,r)}static $(){return["GrokBotTransferDroppedGroup|1 group #0|2 role #1|3 reason #2",Ca,Ba,Pa]}}class Aa extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,this.destinationMemberCount=0,this.from=ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Aa,t,r)}static $(){return["GrokBotTransferDestinationTeamRow|1 role #0|2 destination_member_count 5|3 from #1",Ba,ba]}}class $a extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($a,t,r)}static $(){return["GrokBotTransferShareRow|1 role #0",Ba]}}class Ma extends qa{constructor(t){super(),this.otherTeams=[],this.managedByOrgAdmins=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ma).fromBinary(t,r)}static fromJson(t,r){return(new Ma).fromJson(t,r)}static fromJsonString(t,r){return(new Ma).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ma,t,r)}static $(){return["GrokBotTransferOrgWideShares|1 organization_row #0|2 destination_team_row_from_share #0|3 other_teams #1*|4 managed_by_org_admins 8",$a,ka]}}class Oa extends qa{constructor(t){super(),this.roomId="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oa,t,r)}static $(){return["GrokBotTransferRoomRef|1 room_id 9|2 name 9"]}}class Da extends qa{constructor(t){super(),this.linked=!1,this.slackTeamId="",this.workspaceName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Da,t,r)}static $(){return["GrokBotTransferSlack|1 linked 8|2 slack_team_id 9|3 workspace_name 9"]}}class Na extends qa{constructor(t){super(),this.installed=!1,this.tenantId="",this.destinationAdminGrantPresent=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Na,t,r)}static $(){return["GrokBotTransferTeamsInstall|1 installed 8|2 tenant_id 9|3 destination_admin_grant_present 8"]}}class Ga extends qa{constructor(t){super(),this.kind=Ra.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ga,t,r)}static $(){return["GrokBotTransferWarning|1 kind #0|2 message 9",Ra]}}class La extends qa{constructor(t){super(),this.agentId="",this.agentName="",this.ownerOnDestination=!1,this.keptUsers=[],this.droppedUsers=[],this.carriedGroups=[],this.droppedGroups=[],this.autoAddRemoved=0,this.routinesMoved=0,this.roomsUnseated=[],this.pluginsMoved=0,this.teamMcpMoved=0,this.warnings=[],this.planHash="",this.actorRole=Ia.UNSPECIFIED,this.notifiesSourceAdmins=!1,this.organizationName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(La,t,r)}static $(){return["GrokBotTransferPlan|1 agent_id 9|2 agent_name 9|3 source_team #0|4 destination_team #0|5 owner #1|6 owner_on_destination 8|7 kept_users #1*|8 dropped_users #1*|9 destination_team_row #2|10 carried_groups #3*|11 dropped_groups #4*|12 org_wide_shares #5|13 auto_add_removed 5|14 routines_moved 5|15 rooms_unseated #6*|16 plugins_moved 5|17 team_mcp_moved 5|18 slack #7|19 teams #8|20 warnings #9*|21 plan_hash 9|22 actor_role #10|23 notifies_source_admins 8|24 organization_name 9",ka,Ea,Aa,Ta,Ua,Ma,Oa,Da,Na,Ga,Ia]}}class Fa extends qa{constructor(t){super(),this.agentId="",this.refusal=va.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fa,t,r)}static $(){return["GrokBotTransferPreviewItem|1 agent_id 9|2 refusal #0|3 message 9|4 plan #1",va,La]}}class Ka extends qa{constructor(t){super(),this.agentId="",this.planHash="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ka,t,r)}static $(){return["GrokBotTransferPlanRef|1 agent_id 9|2 plan_hash 9"]}}class za extends qa{constructor(t){super(),this.agentId="",this.outcome=va.UNSPECIFIED,this.transferId="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(za,t,r)}static $(){return["GrokBotTransferItemResult|1 agent_id 9|2 outcome #0|3 transfer_id 9|4 message 9",va]}}class ja extends qa{constructor(t){super(),this.transferId="",this.agentId="",this.sourceTeamId=0,this.destinationTeamId=0,this.state=xa.UNSPECIFIED,this.step="",this.errorCode="",this.createdAtMs=s.protoInt64.zero,this.updatedAtMs=s.protoInt64.zero,this.bulkOperationId="",this.actorRole=Ia.UNSPECIFIED,this.moved=!1,this.resumable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ja,t,r)}static $(){return["GrokBotTransferStatus|1 transfer_id 9|2 agent_id 9|3 source_team_id 5|4 destination_team_id 5|5 state #0|6 step 9|7 error_code 9|8 created_at_ms 3|9 updated_at_ms 3|10 bulk_operation_id 9|11 actor_role #1|12 moved 8|13 resumable 8",xa,Ia]}}class Ha extends qa{constructor(t){super(),this.memberCount=0,this.ready=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ha,t,r)}static $(){return["GrokBotTransferDestination|1 team #0|2 member_count 5|3 ready 8",ka]}}var Wa=e("../proto/dist/generated/aiserver/v1/utils_pb.js");const Qa="aiserver.v1.";class Va extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Qa}}var Xa=(0,i.QT)(s.proto3,Qa,"SandEgressHttpHeaderOp",[[0,"UNSPECIFIED"],[1,"SET"],[2,"APPEND"],[3,"REMOVE"]],1),Ya=(0,i.QT)(s.proto3,Qa,"GrokBotRoiPreviewSort",[[0,"UNSPECIFIED"],[1,"OUTPUTS"],[2,"USAGE"],[3,"COST_PER_OUTPUT"]],1),Za=(0,i.QT)(s.proto3,Qa,"TeamGrokBotRoiBotPersonRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"MANAGER"],[3,"COLLABORATOR"]],1),tu=(0,i.QT)(s.proto3,Qa,"GrokBotGroupTriState",[[0,"UNSPECIFIED"],[1,"INHERIT"],[2,"ON"],[3,"OFF"]],1),ru=(0,i.QT)(s.proto3,Qa,"GrokBotSlackWorkspaceAccessScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"]],1),eu=(0,i.QT)(s.proto3,Qa,"SandSetupChecklistItemState",[[0,"UNSPECIFIED"],[1,"CHECKED"],[2,"SKIPPED"],[3,"CLEARED"]],1),nu=(0,i.QT)(s.proto3,Qa,"SandOnboardingCompletionSource",[[0,"UNSPECIFIED"],[1,"DASHBOARD_SETTINGS"],[2,"PORTAL_ONBOARDING"]],1),su=(0,i.QT)(s.proto3,Qa,"SandBillingBrand",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),iu=(0,i.QT)(s.proto3,Qa,"SandSeatTierUpgradeRequestOrigin",[[0,"UNSPECIFIED"],[1,"USAGE_WARNING"],[2,"USAGE_LIMIT"]],1),ou=(0,i.QT)(s.proto3,Qa,"GrokBotUsageSource",[[0,"UNSPECIFIED"],[1,"USER"],[2,"AUTOMATION"],[3,"AGENT"],[4,"GROUP"],[5,"OTHER"]],1),au=(0,i.QT)(s.proto3,Qa,"GrokBotIdpClientAuthMethod",[[0,"UNSPECIFIED"],[1,"CLIENT_SECRET_BASIC"],[2,"CLIENT_SECRET_POST"],[3,"PRIVATE_KEY_JWT"],[4,"NONE"]],1),uu=(0,i.QT)(s.proto3,Qa,"GrokBotIdJagConnectorPolicyMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LISTED"]],1),cu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotScimOktaSignInMethod",[[0,"UNSPECIFIED"],[1,"SAML_HOP"],[2,"SAML_BEARER"]],1),lu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotScimOktaClientAuthMethod",[[0,"UNSPECIFIED"],[1,"CLIENT_SECRET_BASIC"],[2,"CLIENT_SECRET_POST"]],1),mu=(0,i.QT)(s.proto3,Qa,"GrokBotPublishedWorkerImageState",[[0,"UNSPECIFIED"],[1,"UNAVAILABLE"],[2,"NONE_YET"],[3,"PUBLISHED"],[4,"UNREACHABLE"],[5,"UNREADABLE"]],1),fu=(0,i.QT)(s.proto3,Qa,"GrokBotPublishedWorkerImageFailure",[[0,"UNSPECIFIED"],[1,"UNREACHABLE"],[2,"UNREADABLE"]],1),du=(0,i.QT)(s.proto3,Qa,"GrokBotCustomerHostedWorkerSetupState",[[0,"UNSPECIFIED"],[1,"IDLE"],[2,"OK"],[3,"APPLYING"],[4,"DEGRADED"],[5,"FAILED"],[6,"KILLED"],[7,"UNAVAILABLE"]],1),pu=(0,i.QT)(s.proto3,Qa,"GrokBotCustomerHostedWorkerSetupUnavailableReason",[[0,"UNSPECIFIED"],[1,"NOT_DESIGNATED"],[2,"POOL_MISMATCH"],[3,"POOL_PURPOSE"],[4,"POOL_NOT_TRANSPORTABLE"],[5,"SETUP_TOO_LARGE"],[6,"SETUP_INVALID"]],1),hu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotDashboardRole",[[0,"UNSPECIFIED"],[1,"VIEWER"],[2,"MANAGER"]],1);class gu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gu,t,r)}static $(){return["GetTeamSandNetworkSettingsRequest|1 team_id 5"]}}class _u extends Va{constructor(t){super(),this.emptyAllowlistGuardEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_u,t,r)}static $(){return["GetTeamSandNetworkSettingsResponse|1 sand_network_controls #0|3 organization_network_blocklist #1|4 empty_allowlist_guard_enabled 8",n.JE6,n.cxP]}}class Ju extends Va{constructor(t){super(),this.op=Xa.UNSPECIFIED,this.name="",this.value="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ju,t,r)}static $(){return["SandEgressHttpHeaderTransform|1 op #0|2 name 9|3 value 9",Xa]}}class wu extends Va{constructor(t){super(),this.name="",this.hosts=[],this.transforms=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wu,t,r)}static $(){return["SandEgressHttpRule|1 name 9|2 hosts 9*|3 transforms #0*",Ju]}}class yu extends Va{constructor(t){super(),this.rules=[],this.allTrafficTransforms=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yu,t,r)}static $(){return["SandEgressHttpRules|1 rules #0*|2 all_traffic_transforms #1*",wu,Ju]}}class Su extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Su,t,r)}static $(){return["GetTeamSandEgressHttpRulesRequest|1 team_id 5"]}}class qu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qu).fromBinary(t,r)}static fromJson(t,r){return(new qu).fromJson(t,r)}static fromJsonString(t,r){return(new qu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qu,t,r)}static $(){return["GetTeamSandEgressHttpRulesResponse|1 rules #0",yu]}}class Bu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bu,t,r)}static $(){return["UpdateTeamSandEgressHttpRulesRequest|1 team_id 5|2 rules #0",yu]}}class Iu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Iu,t,r)}static $(){return["UpdateTeamSandEgressHttpRulesResponse"]}}class Pu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pu,t,r)}static $(){return["GetTeamGrokBotTrialRequest|1 team_id 5"]}}class bu extends Va{constructor(t){super(),this.active=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bu,t,r)}static $(){return["GetTeamGrokBotTrialResponse|1 active 8|2 expires_at #0",s.Timestamp]}}class Ru extends Va{constructor(t){super(),this.state=vu.UNSPECIFIED,this.shareability=xu.UNSPECIFIED,this.ownerUserId=0,this.kind=ku.UNSPECIFIED,this.nameQuery="",this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ru,t,r)}static $(){return["TeamGrokBotAdminAgentFilter|1 state #0|2 shareability #1|3 owner_user_id 5|4 kind #2|5 name_query 9|6 agent_id 9",vu,xu,ku]}}var vu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.State",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"DELETED"]],1),xu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.Shareability",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM_SHARED"]],1),ku=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.Kind",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"ROOM"]],1);class Eu extends Va{constructor(t){super(),this.teamId=0,this.pageSize=0,this.pageToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Eu,t,r)}static $(){return["ListTeamGrokBotAgentsAdminRequest|1 team_id 5|2 page_size 5|3 page_token 9|4 filter #0",Ru]}}class Cu extends Va{constructor(t){super(),this.roomId="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cu,t,r)}static $(){return["TeamGrokBotAdminRoomRef|1 room_id 9|2 name 9"]}}class Tu extends Va{constructor(t){super(),this.agentId="",this.name="",this.description="",this.ownerUserEmail="",this.ownerUserId=0,this.isTeamAgent=!1,this.kind="",this.rooms=[],this.ownerDisplayName="",this.avatarUrl="",this.avatarShape="",this.avatarColor="",this.isPublished=!1,this.deletable=!1,this.teamApprovedByUserId=0,this.transferable=!1,this.transferringToUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tu,t,r)}static $(){return["TeamGrokBotAdminAgentRow|1 agent_id 9|2 name 9|3 description 9|4 owner_user_email 9|5 owner_user_id 5|6 is_team_agent 8|7 kind 9|8 created_at #0|9 deleted_at #0|10 rooms #1*|11 owner_display_name 9|12 avatar_url 9|13 avatar_shape 9|14 avatar_color 9|15 audience #2|16 is_published 8|17 deletable 8|18 team_approved_at #0|19 team_approved_by_user_id 5|20 transferable 8|21 transferring_to_user_id 5",s.Timestamp,Cu,el]}}class Uu extends Va{constructor(t){super(),this.rows=[],this.nextPageToken="",this.teamDefaultBotsEnabled=!1,this.ownershipTransferEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uu,t,r)}static $(){return["ListTeamGrokBotAgentsAdminResponse|1 rows #0*|2 next_page_token 9|3 team_default_bots_enabled 8|4 ownership_transfer_enabled 8",Tu]}}class Au extends Va{constructor(t){super(),this.teamId=0,this.page=0,this.pageSize=0,this.summaryOnly=!1,this.sort=Ya.UNSPECIFIED,this.ascending=!1,this.usageIncludesUntracked=!1,this.search="",this.reuseOrCoinShadow=!1,this.skipUsage=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Au,t,r)}static $(){return["GetTeamGrokBotRoiPreviewRequest|1 team_id 5|3 page 5|4 page_size 5|5 summary_only 8|6 sort #0|7 ascending 8|8 usage_includes_untracked 8|9 search 9|10 reuse_or_coin_shadow 8|11 skip_usage 8",Ya]}}class $u extends Va{constructor(t){super(),this.label="",this.count=s.protoInt64.zero,this.primary=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($u,t,r)}static $(){return["TeamGrokBotRoiPreviewNoun|1 label 9|2 count 3|3 primary 8"]}}class Mu extends Va{constructor(t){super(),this.agentId="",this.name="",this.ownerUserEmail="",this.isTeamAgent=!1,this.nouns=[],this.generationStatus="",this.roiNotRead=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mu,t,r)}static $(){return["TeamGrokBotRoiPreviewRow|1 agent_id 9|2 name 9|3 owner_user_email 9|4 is_team_agent 8|5 nouns #0*|6 generation_status 9|7 usage_cents 3?|8 tracking_started_at_ms 3?|9 untracked_usage_cents 3?|10 roi_not_read 8|11 output_count 3?",$u]}}class Ou extends Va{constructor(t){super(),this.enabled=!1,this.rows=[],this.windowDays=0,this.roiBotCount=0,this.allBotCount=0,this.page=0,this.pageSize=0,this.inventoryTruncated=!1,this.usageShown=!1,this.usageFailed=!1,this.memberScope=!1,this.windowStartMs=s.protoInt64.zero,this.cohortTruncated=!1,this.appliedSort=Ya.UNSPECIFIED,this.ownerSearchFailed=!1,this.reuseOrCoinShadow=!1,this.botDrilldownEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ou,t,r)}static $(){return["GetTeamGrokBotRoiPreviewResponse|1 enabled 8|2 rows #0*|3 window_days 5|4 roi_bot_count 5|5 all_bot_count 5|6 page 5|7 page_size 5|8 inventory_truncated 8|9 usage_shown 8|10 usage_failed 8|11 member_scope 8|12 tracking_started_at_ms 3?|13 window_start_ms 3|14 cohort_truncated 8|15 applied_sort #1|16 owner_search_failed 8|17 reuse_or_coin_shadow 8|18 bot_drilldown_enabled 8",Mu,Ya]}}class Du extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Du,t,r)}static $(){return["GetTeamGrokBotRoiBotRequest|1 team_id 5|2 agent_id 9"]}}class Nu extends Va{constructor(t){super(),this.day="",this.count=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nu,t,r)}static $(){return["TeamGrokBotRoiBotOutputDay|1 day 9|2 count 3"]}}class Gu extends Va{constructor(t){super(),this.label="",this.level="",this.primary=!1,this.days=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gu,t,r)}static $(){return["TeamGrokBotRoiBotOutput|1 label 9|2 level 9|3 primary 8|4 days #0*",Nu]}}class Lu extends Va{constructor(t){super(),this.day="",this.activeUsers=0,this.trailingSevenDayActiveUsers=0,this.userTurns=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lu,t,r)}static $(){return["TeamGrokBotRoiBotUsageDay|1 day 9|2 active_users 5|3 trailing_seven_day_active_users 5|4 user_turns 5"]}}class Fu extends Va{constructor(t){super(),this.userId=0,this.displayName="",this.userTurns=0,this.isExternal=!1,this.activeDays=0,this.role=Za.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fu,t,r)}static $(){return["TeamGrokBotRoiBotPerson|1 user_id 5|2 display_name 9|3 user_turns 5|4 is_external 8|5 active_days 5|6 role #0",Za]}}class Ku extends Va{constructor(t){super(),this.windowDays=0,this.people=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ku,t,r)}static $(){return["TeamGrokBotRoiBotPeopleWindow|1 window_days 5|2 people #0*",Fu]}}class zu extends Va{constructor(t){super(),this.enabled=!1,this.agentId="",this.name="",this.ownerDisplayName="",this.ownerUserEmail="",this.isTeamAgent=!1,this.windowDays=0,this.windowStartMs=s.protoInt64.zero,this.outputs=[],this.generationStatus="",this.outputsFailed=!1,this.usageDays=[],this.peopleShown=!1,this.people=[],this.usageFailed=!1,this.usageHidden=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zu,t,r)}static $(){return["GetTeamGrokBotRoiBotResponse|1 enabled 8|2 agent_id 9|3 name 9|4 owner_display_name 9|5 owner_user_email 9|6 is_team_agent 8|7 window_days 5|8 window_start_ms 3|9 outputs #0*|10 generation_status 9|11 tracking_started_at_ms 3?|12 outputs_failed 8|13 usage_days #1*|14 people_shown 8|15 people #2*|16 usage_failed 8|18 usage_hidden 8",Gu,Lu,Ku]}}class ju extends Va{constructor(t){super(),this.teamId=0,this.confirmEmptyAllowlist=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ju,t,r)}static $(){return["UpdateTeamSandNetworkSettingsRequest|1 team_id 5|2 sand_network_controls #0|3 confirm_empty_allowlist 8",n.JE6]}}class Hu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hu,t,r)}static $(){return["UpdateTeamSandNetworkSettingsResponse"]}}class Wu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wu,t,r)}static $(){return["GetTeamSandTrustedCaCertificatesRequest|1 team_id 5"]}}class Qu extends Va{constructor(t){super(),this.certificates=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qu,t,r)}static $(){return["GetTeamSandTrustedCaCertificatesResponse|1 certificates 9*"]}}class Vu extends Va{constructor(t){super(),this.teamId=0,this.certificates=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vu,t,r)}static $(){return["UpdateTeamSandTrustedCaCertificatesRequest|1 team_id 5|2 certificates 9*"]}}class Xu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xu,t,r)}static $(){return["UpdateTeamSandTrustedCaCertificatesResponse"]}}class Yu extends Va{constructor(t){super(),this.hosts=[],this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yu,t,r)}static $(){return["SandLocalEgressPrivateDestinationRule|1 hosts 9*|2 cidrs 9*"]}}class Zu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zu,t,r)}static $(){return["GetTeamSandLocalEgressPrivateDestinationsRequest|1 team_id 5"]}}class tc extends Va{constructor(t){super(),this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tc,t,r)}static $(){return["GetTeamSandLocalEgressPrivateDestinationsResponse|1 rules #0*",Yu]}}class rc extends Va{constructor(t){super(),this.teamId=0,this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rc,t,r)}static $(){return["UpdateTeamSandLocalEgressPrivateDestinationsRequest|1 team_id 5|2 rules #0*",Yu]}}class ec extends Va{constructor(t){super(),this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ec,t,r)}static $(){return["UpdateTeamSandLocalEgressPrivateDestinationsResponse|1 rules #0*",Yu]}}class nc extends Va{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nc,t,r)}static $(){return["GetTeamGroupSandNetworkSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class sc extends Va{constructor(t){super(),this.emptyAllowlistGuardEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sc,t,r)}static $(){return["GetTeamGroupSandNetworkSettingsResponse|1 sand_network_controls #0|2 team_sand_network_controls #0|4 organization_network_blocklist #1|5 empty_allowlist_guard_enabled 8",n.JE6,n.cxP]}}class ic extends Va{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,this.confirmEmptyAllowlist=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ic,t,r)}static $(){return["UpdateTeamGroupSandNetworkSettingsRequest|1 team_id 5|2 group_id 3|3 sand_network_controls #0|4 confirm_empty_allowlist 8",n.JE6]}}class oc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oc,t,r)}static $(){return["UpdateTeamGroupSandNetworkSettingsResponse"]}}class ac extends Va{constructor(t){super(),this.cloudAgents=tu.UNSPECIFIED,this.localExecutionCeiling=n.odJ.UNSPECIFIED,this.localEgressAllowed=tu.UNSPECIFIED,this.enforceAutoReview=tu.UNSPECIFIED,this.agentEmail=tu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ac).fromBinary(t,r)}static fromJson(t,r){return(new ac).fromJson(t,r)}static fromJsonString(t,r){return(new ac).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ac,t,r)}static $(){return["GrokBotGroupCapabilities|1 cloud_agents #0|2 local_execution_ceiling #1|3 local_egress_allowed #0|4 enforce_auto_review #0|5 auto_review_rules #2|6 agent_email #0",tu,n.odJ,Fc]}}class uc extends Va{constructor(t){super(),this.cloudAgentsAllowed=!1,this.localExecutionCeiling=n.odJ.UNSPECIFIED,this.localEgressAllowed=!1,this.enforceAutoReview=!1,this.agentEmailAllowed=!1,this.localEgressMode=n.SDZ.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uc).fromBinary(t,r)}static fromJson(t,r){return(new uc).fromJson(t,r)}static fromJsonString(t,r){return(new uc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uc,t,r)}static $(){return["GrokBotTeamCapabilities|1 cloud_agents_allowed 8|2 local_execution_ceiling #0|3 local_egress_allowed 8|4 enforce_auto_review 8|5 auto_review_rules #1|6 agent_email_allowed 8|7 local_egress_mode #2",n.odJ,Fc,n.SDZ]}}class cc extends Va{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cc,t,r)}static $(){return["GetTeamGroupGrokBotCapabilitiesRequest|1 team_id 5|2 group_public_id 9"]}}class lc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lc,t,r)}static $(){return["GetTeamGroupGrokBotCapabilitiesResponse|1 capabilities #0|2 team_capabilities #1",ac,uc]}}class mc extends Va{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,this.cloudAgents=tu.UNSPECIFIED,this.localEgressAllowed=tu.UNSPECIFIED,this.enforceAutoReview=tu.UNSPECIFIED,this.agentEmail=tu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mc,t,r)}static $(){return["UpdateTeamGroupGrokBotCapabilitiesRequest|1 team_id 5|2 group_id 3|3 cloud_agents #0|4 local_execution_ceiling #1?|5 local_egress_allowed #0|6 enforce_auto_review #0|7 auto_review_rules #2|8 agent_email #0",tu,n.odJ,Fc]}}class fc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fc,t,r)}static $(){return["UpdateTeamGroupGrokBotCapabilitiesResponse"]}}class dc extends Va{constructor(t){super(),this.serverIdentifiers=[],this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dc,t,r)}static $(){return["ListSandMcpToolsRequest|1 server_identifiers 9*|2 mcp_config_json 9?|3 grok_bot_plugin_scope #0?|4 team_tailnet_rows_per_team 8",n.q0X]}}class pc extends Va{constructor(t){super(),this.servers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pc,t,r)}static $(){return["ListSandMcpToolsResponse|1 servers #0*|2 mcp_allowlist #1?",hc,n.YUq]}}class hc extends Va{constructor(t){super(),this.serverIdentifier="",this.status="",this.tools=[],this.accountLabel="",this.rowServerIdentifier="",this.servedBy=n.JLr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hc).fromBinary(t,r)}static fromJson(t,r){return(new hc).fromJson(t,r)}static fromJsonString(t,r){return(new hc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hc,t,r)}static $(){return["ListSandMcpToolsResponse.Server|1 server_identifier 9|2 status 9|3 tools #0*|4 account_label 9|5 row_server_identifier 9|6 served_by #1|7 status_detail 9?|8 grok_connector_id 9?|9 sign_out #2?|10 status_reason 9?",ns.gd,n.JLr,n.eJC]}}class gc extends Va{constructor(t){super(),this.serverIdentifier="",this.toolName="",this.toolCallId="",this.agentId="",this.turnId="",this.eventSequence=s.protoInt64.zero,this.mcpAnalyticsReportedByCaller=!1,this.modelName="",this.refuseSharedPaymentTokenArguments=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gc).fromBinary(t,r)}static fromJson(t,r){return(new gc).fromJson(t,r)}static fromJsonString(t,r){return(new gc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gc,t,r)}static $(){return["ExecuteSandMcpToolRequest|1 server_identifier 9|2 tool_name 9|3 args #0|4 tool_call_id 9|5 agent_id 9|6 turn_id 9|7 mcp_config_json 9?|8 grok_bot_plugin_scope #1?|9 event_sequence 3|10 mcp_analytics_reported_by_caller 8|11 model_name 9|12 refuse_shared_payment_token_arguments 8",s.Struct,n.q0X]}}class _c extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _c).fromBinary(t,r)}static fromJson(t,r){return(new _c).fromJson(t,r)}static fromJsonString(t,r){return(new _c).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_c,t,r)}static $(){return["ClassifySandAutoReviewRequest|1 args #0|2 attempt_index 13?|3 mode 9?",fa.Th]}}class Jc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jc).fromBinary(t,r)}static fromJson(t,r){return(new Jc).fromJson(t,r)}static fromJsonString(t,r){return(new Jc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jc,t,r)}static $(){return["ClassifySandAutoReviewResponse|1 result #0",fa.bN]}}class wc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wc).fromBinary(t,r)}static fromJson(t,r){return(new wc).fromJson(t,r)}static fromJsonString(t,r){return(new wc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wc,t,r)}static $(){return["ExecuteSandMcpToolResponse|1 result #0|2 credential_owner_user_id 5?",ss.iz]}}class yc extends Va{constructor(t){super(),this.serverIdentifier="",this.uri="",this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yc).fromBinary(t,r)}static fromJson(t,r){return(new yc).fromJson(t,r)}static fromJsonString(t,r){return(new yc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yc,t,r)}static $(){return["ReadSandMcpResourceRequest|1 server_identifier 9|2 uri 9|3 agent_id 9|4 mcp_config_json 9?|5 grok_bot_plugin_scope #0?",n.q0X]}}class Sc extends Va{constructor(t){super(),this.contents=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sc).fromBinary(t,r)}static fromJson(t,r){return(new Sc).fromJson(t,r)}static fromJsonString(t,r){return(new Sc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sc,t,r)}static $(){return["ReadSandMcpResourceResponse|1 contents #0*|2 error 9?",qc]}}class qc extends Va{constructor(t){super(),this.uri="",this.body={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qc).fromBinary(t,r)}static fromJson(t,r){return(new qc).fromJson(t,r)}static fromJsonString(t,r){return(new qc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qc,t,r)}static $(){return["ReadSandMcpResourceResponse.Content|1 uri 9|2 mime_type 9?|3 text 9 body|4 blob 12 body|5 meta_json 9?"]}}class Bc extends Va{constructor(t){super(),this.eventId="",this.occurredAtMs=s.protoInt64.zero,this.agentId="",this.turnId="",this.boxId="",this.eventSequence=s.protoInt64.zero,this.toolCallId="",this.initiatedBy="",this.action={case:void 0},this.rootTurnId="",this.subagentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bc).fromBinary(t,r)}static fromJson(t,r){return(new Bc).fromJson(t,r)}static fromJsonString(t,r){return(new Bc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bc,t,r)}static $(){return["SandAuditEvent|1 event_id 9|2 occurred_at_ms 3|3 agent_id 9|4 turn_id 9|5 box_id 9|10 event_sequence 3|11 tool_call_id 9|19 initiated_by 9|6 mcp_tool_call #0 action|7 shell_command #1 action|8 browser_navigation #2 action|9 computer_use_session #3 action|12 tool_result #4 action|15 message_delivery #5 action|21 file_transfer #6 action|22 guardrail #7 action|14 automation_run #8 action|23 skill_activated #9 action|13 tool_decision #10 action|20 delegation #11 action|16 root_turn_id 9|17 subagent_id 9",Ic,Pc,bc,Rc,vc,xc,kc,Ec,Cc,Tc,Uc,Ac]}}class Ic extends Va{constructor(t){super(),this.toolCallId="",this.serverIdentifier="",this.serverName="",this.toolName="",this.status="",this.durationMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ic).fromBinary(t,r)}static fromJson(t,r){return(new Ic).fromJson(t,r)}static fromJsonString(t,r){return(new Ic).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ic,t,r)}static $(){return["SandAuditEvent.McpToolCall|1 tool_call_id 9|2 server_identifier 9|3 server_name 9|4 tool_name 9|5 status 9|6 duration_ms 3"]}}class Pc extends Va{constructor(t){super(),this.command="",this.kind="",this.target="",this.allowed=!1,this.blockedReason="",this.classificationReasons=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pc).fromBinary(t,r)}static fromJson(t,r){return(new Pc).fromJson(t,r)}static fromJsonString(t,r){return(new Pc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pc,t,r)}static $(){return["SandAuditEvent.ShellCommand|1 command 9|2 kind 9|3 target 9|4 allowed 8|5 blocked_reason 9|6 classification_reasons 9*|7 machine_id 9?|8 exit_code 5?|9 duration_ms 3?"]}}class bc extends Va{constructor(t){super(),this.url="",this.pageTitle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bc).fromBinary(t,r)}static fromJson(t,r){return(new bc).fromJson(t,r)}static fromJsonString(t,r){return(new bc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bc,t,r)}static $(){return["SandAuditEvent.BrowserNavigation|1 url 9|2 page_title 9"]}}class Rc extends Va{constructor(t){super(),this.toolCallId="",this.actionCount=s.protoInt64.zero,this.actionCounts={},this.durationMs=s.protoInt64.zero,this.screenshotCount=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rc).fromBinary(t,r)}static fromJson(t,r){return(new Rc).fromJson(t,r)}static fromJsonString(t,r){return(new Rc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rc,t,r)}static $(){return["SandAuditEvent.ComputerUseSession|1 tool_call_id 9|2 action_count 3|3 action_counts 9,3|4 duration_ms 3|5 screenshot_count 3"]}}class vc extends Va{constructor(t){super(),this.toolName="",this.outcome="",this.durationMs=s.protoInt64.zero,this.errorCategory="",this.targetHost="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vc).fromBinary(t,r)}static fromJson(t,r){return(new vc).fromJson(t,r)}static fromJsonString(t,r){return(new vc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vc,t,r)}static $(){return["SandAuditEvent.ToolResult|1 tool_name 9|2 outcome 9|3 duration_ms 3|4 error_category 9|5 target_host 9"]}}class xc extends Va{constructor(t){super(),this.destinationType="",this.destinationId="",this.result="",this.failureCategory="",this.messageId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xc).fromBinary(t,r)}static fromJson(t,r){return(new xc).fromJson(t,r)}static fromJsonString(t,r){return(new xc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xc,t,r)}static $(){return["SandAuditEvent.MessageDelivery|1 destination_type 9|2 destination_id 9|3 result 9|4 failure_category 9|5 message_id 9"]}}class kc extends Va{constructor(t){super(),this.direction="",this.target="",this.outcome="",this.errorCategory="",this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kc).fromBinary(t,r)}static fromJson(t,r){return(new kc).fromJson(t,r)}static fromJsonString(t,r){return(new kc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kc,t,r)}static $(){return["SandAuditEvent.FileTransfer|1 direction 9|2 target 9|3 byte_count 3?|4 outcome 9|5 error_category 9|6 machine_id 9"]}}class Ec extends Va{constructor(t){super(),this.kind="",this.detector="",this.action="",this.count=s.protoInt64.zero,this.targetHost="",this.source="",this.toolName="",this.resolution="",this.decisionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ec).fromBinary(t,r)}static fromJson(t,r){return(new Ec).fromJson(t,r)}static fromJsonString(t,r){return(new Ec).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ec,t,r)}static $(){return["SandAuditEvent.Guardrail|1 kind 9|2 detector 9|3 action 9|4 count 3|5 target_host 9|6 source 9|7 tool_name 9|8 resolution 9|9 duration_ms 3?|10 decision_id 9"]}}class Cc extends Va{constructor(t){super(),this.automationId="",this.runId="",this.trigger="",this.outcome="",this.durationMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cc).fromBinary(t,r)}static fromJson(t,r){return(new Cc).fromJson(t,r)}static fromJsonString(t,r){return(new Cc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cc,t,r)}static $(){return["SandAuditEvent.AutomationRun|1 automation_id 9|2 run_id 9|3 trigger 9|4 outcome 9|5 duration_ms 3"]}}class Tc extends Va{constructor(t){super(),this.skillName="",this.trigger="",this.source="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tc).fromBinary(t,r)}static fromJson(t,r){return(new Tc).fromJson(t,r)}static fromJsonString(t,r){return(new Tc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tc,t,r)}static $(){return["SandAuditEvent.SkillActivated|1 skill_name 9|2 trigger 9|3 source 9"]}}class Uc extends Va{constructor(t){super(),this.decisionId="",this.toolName="",this.source="",this.approvalMode="",this.outcome="",this.ruleId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uc).fromBinary(t,r)}static fromJson(t,r){return(new Uc).fromJson(t,r)}static fromJsonString(t,r){return(new Uc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uc,t,r)}static $(){return["SandAuditEvent.ToolDecision|1 decision_id 9|2 tool_name 9|3 source 9|4 approval_mode 9|5 outcome 9|6 rule_id 9"]}}class Ac extends Va{constructor(t){super(),this.direction="",this.target="",this.targetId="",this.outcome="",this.kind="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ac).fromBinary(t,r)}static fromJson(t,r){return(new Ac).fromJson(t,r)}static fromJsonString(t,r){return(new Ac).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ac,t,r)}static $(){return["SandAuditEvent.Delegation|1 direction 9|2 target 9|3 target_id 9|4 outcome 9|5 duration_ms 3?|6 kind 9"]}}class $c extends Va{constructor(t){super(),this.events=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $c).fromBinary(t,r)}static fromJson(t,r){return(new $c).fromJson(t,r)}static fromJsonString(t,r){return(new $c).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($c,t,r)}static $(){return["RecordSandAuditEventsRequest|1 events #0*",Bc]}}class Mc extends Va{constructor(t){super(),this.recordedCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mc).fromBinary(t,r)}static fromJson(t,r){return(new Mc).fromJson(t,r)}static fromJsonString(t,r){return(new Mc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mc,t,r)}static $(){return["RecordSandAuditEventsResponse|1 recorded_count 5"]}}class Oc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oc).fromBinary(t,r)}static fromJson(t,r){return(new Oc).fromJson(t,r)}static fromJsonString(t,r){return(new Oc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oc,t,r)}static $(){return["SandShareBotExportSettings|1 policy 9?"]}}class Dc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dc).fromBinary(t,r)}static fromJson(t,r){return(new Dc).fromJson(t,r)}static fromJsonString(t,r){return(new Dc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dc,t,r)}static $(){return["GetTeamSandShareBotExportSettingsRequest|1 team_id 5"]}}class Nc extends Va{constructor(t){super(),this.effectivePolicy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nc).fromBinary(t,r)}static fromJson(t,r){return(new Nc).fromJson(t,r)}static fromJsonString(t,r){return(new Nc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nc,t,r)}static $(){return["GetTeamSandShareBotExportSettingsResponse|1 settings #0|2 effective_policy 9",Oc]}}class Gc extends Va{constructor(t){super(),this.teamId=0,this.policy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gc).fromBinary(t,r)}static fromJson(t,r){return(new Gc).fromJson(t,r)}static fromJsonString(t,r){return(new Gc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gc,t,r)}static $(){return["UpdateTeamSandShareBotExportSettingsRequest|1 team_id 5|2 policy 9"]}}class Lc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lc).fromBinary(t,r)}static fromJson(t,r){return(new Lc).fromJson(t,r)}static fromJsonString(t,r){return(new Lc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lc,t,r)}static $(){return["UpdateTeamSandShareBotExportSettingsResponse"]}}class Fc extends Va{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fc).fromBinary(t,r)}static fromJson(t,r){return(new Fc).fromJson(t,r)}static fromJsonString(t,r){return(new Fc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fc,t,r)}static $(){return["GrokBotAutoReviewRules|1 allow_instructions 9*|2 block_instructions 9*"]}}class Kc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kc).fromBinary(t,r)}static fromJson(t,r){return(new Kc).fromJson(t,r)}static fromJsonString(t,r){return(new Kc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kc,t,r)}static $(){return["UpdateTeamGrokBotCapabilitiesRequest|1 team_id 5|2 action_recording 8?|3 enforce_auto_review 8?|4 auto_review_rules #0|5 local_execution_ceiling #1?|6 local_egress_allowed 8?|7 agent_email_allowed 8?|8 box_sudo_disallowed 8?|24 box_vnc_disallowed 8?|9 cloud_agent_secret_forwarding_allowed 8?|10 meetings_allowed 8?|11 pages_team_sharing_allowed 8?|12 bot_messaging_allowed 8?|13 pages_team_sharing_level #2?|14 connector_writes_need_approval 8?|15 connector_write_trust #3|16 team_bot_sharing #4?|17 delegated_auth_allowed 8?|18 texting_allowed 8?|19 wall_snapshots_allowed 8?|20 local_execution_controls #5|21 local_egress_mode #6?|22 proactivity_allowed 8?|23 designated_bot_sharers #7",Fc,n.odJ,n.wfI,jc,n.Rq9,n.WEP,n.SDZ,zc]}}class zc extends Va{constructor(t){super(),this.userIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zc).fromBinary(t,r)}static fromJson(t,r){return(new zc).fromJson(t,r)}static fromJsonString(t,r){return(new zc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zc,t,r)}static $(){return["GrokBotDesignatedBotSharers|1 user_ids 3*"]}}class jc extends Va{constructor(t){super(),this.serverUrl="",this.trusted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jc).fromBinary(t,r)}static fromJson(t,r){return(new jc).fromJson(t,r)}static fromJsonString(t,r){return(new jc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jc,t,r)}static $(){return["GrokBotConnectorWriteTrust|1 server_url 9|2 trusted 8"]}}class Hc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hc).fromBinary(t,r)}static fromJson(t,r){return(new Hc).fromJson(t,r)}static fromJsonString(t,r){return(new Hc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hc,t,r)}static $(){return["UpdateTeamGrokBotCapabilitiesResponse"]}}class Wc extends Va{constructor(t){super(),this.kind={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wc).fromBinary(t,r)}static fromJson(t,r){return(new Wc).fromJson(t,r)}static fromJsonString(t,r){return(new Wc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wc,t,r)}static $(){return["GrokBotConnectorAudience|1 everyone #0 kind|2 members #1 kind",Qc,Vc]}}class Qc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qc).fromBinary(t,r)}static fromJson(t,r){return(new Qc).fromJson(t,r)}static fromJsonString(t,r){return(new Qc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qc,t,r)}static $(){return["GrokBotConnectorAudience.Everyone"]}}class Vc extends Va{constructor(t){super(),this.emails=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vc).fromBinary(t,r)}static fromJson(t,r){return(new Vc).fromJson(t,r)}static fromJsonString(t,r){return(new Vc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vc,t,r)}static $(){return["GrokBotConnectorAudience.Members|1 emails 9*"]}}class Xc extends Va{constructor(t){super(),this.connectorName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xc).fromBinary(t,r)}static fromJson(t,r){return(new Xc).fromJson(t,r)}static fromJsonString(t,r){return(new Xc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xc,t,r)}static $(){return["GrokBotConnectorAudienceEntry|1 connector_name 9|2 audience #0",Wc]}}class Yc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yc).fromBinary(t,r)}static fromJson(t,r){return(new Yc).fromJson(t,r)}static fromJsonString(t,r){return(new Yc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yc,t,r)}static $(){return["GetTeamGrokBotConnectorAudiencesRequest|1 team_id 5"]}}class Zc extends Va{constructor(t){super(),this.connectors=[],this.adminControlsAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zc).fromBinary(t,r)}static fromJson(t,r){return(new Zc).fromJson(t,r)}static fromJsonString(t,r){return(new Zc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zc,t,r)}static $(){return["GetTeamGrokBotConnectorAudiencesResponse|1 connectors #0*|2 admin_controls_available 8",Xc]}}class tl extends Va{constructor(t){super(),this.teamId=0,this.connectorName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tl).fromBinary(t,r)}static fromJson(t,r){return(new tl).fromJson(t,r)}static fromJsonString(t,r){return(new tl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tl,t,r)}static $(){return["UpdateTeamGrokBotConnectorAudienceRequest|1 team_id 5|2 connector_name 9|3 audience #0",Wc]}}class rl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rl).fromBinary(t,r)}static fromJson(t,r){return(new rl).fromJson(t,r)}static fromJsonString(t,r){return(new rl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rl,t,r)}static $(){return["UpdateTeamGrokBotConnectorAudienceResponse"]}}class el extends Va{constructor(t){super(),this.allTeam=!1,this.groupIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new el).fromBinary(t,r)}static fromJson(t,r){return(new el).fromJson(t,r)}static fromJsonString(t,r){return(new el).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(el,t,r)}static $(){return["TeamGrokBotDefaultAudience|1 all_team 8|2 group_ids 3*"]}}class nl extends Va{constructor(t){super(),this.agentId="",this.name="",this.description="",this.avatarShape="",this.avatarColor="",this.ownerDisplayName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nl).fromBinary(t,r)}static fromJson(t,r){return(new nl).fromJson(t,r)}static fromJsonString(t,r){return(new nl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nl,t,r)}static $(){return["TeamGrokBotDefaultAgent|1 agent_id 9|2 name 9|3 description 9|4 avatar_url 9?|5 avatar_shape 9|6 avatar_color 9|7 owner_display_name 9|8 audience #0",el]}}class sl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sl).fromBinary(t,r)}static fromJson(t,r){return(new sl).fromJson(t,r)}static fromJsonString(t,r){return(new sl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sl,t,r)}static $(){return["GetTeamGrokBotSlackWorkspaceAccessRequest|1 team_id 5"]}}class il extends Va{constructor(t){super(),this.allowed=!1,this.scope=ru.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new il).fromBinary(t,r)}static fromJson(t,r){return(new il).fromJson(t,r)}static fromJsonString(t,r){return(new il).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(il,t,r)}static $(){return["GetTeamGrokBotSlackWorkspaceAccessResponse|1 allowed 8|2 scope #0",ru]}}class ol extends Va{constructor(t){super(),this.teamId=0,this.allowed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ol).fromBinary(t,r)}static fromJson(t,r){return(new ol).fromJson(t,r)}static fromJsonString(t,r){return(new ol).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ol,t,r)}static $(){return["SetTeamGrokBotSlackWorkspaceAccessRequest|1 team_id 5|2 allowed 8"]}}class al extends Va{constructor(t){super(),this.allowed=!1,this.scope=ru.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new al).fromBinary(t,r)}static fromJson(t,r){return(new al).fromJson(t,r)}static fromJsonString(t,r){return(new al).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(al,t,r)}static $(){return["SetTeamGrokBotSlackWorkspaceAccessResponse|1 allowed 8|2 scope #0",ru]}}class ul extends Va{constructor(t){super(),this.teamId=0,this.pageToken="",this.query="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ul).fromBinary(t,r)}static fromJson(t,r){return(new ul).fromJson(t,r)}static fromJsonString(t,r){return(new ul).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ul,t,r)}static $(){return["ListTeamGrokBotDefaultAgentsRequest|1 team_id 5|2 page_size 5?|3 page_token 9|4 query 9"]}}class cl extends Va{constructor(t){super(),this.agents=[],this.nextPageToken="",this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cl).fromBinary(t,r)}static fromJson(t,r){return(new cl).fromJson(t,r)}static fromJsonString(t,r){return(new cl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cl,t,r)}static $(){return["ListTeamGrokBotDefaultAgentsResponse|1 agents #0*|2 next_page_token 9|3 enabled 8",nl]}}class ll extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ll).fromBinary(t,r)}static fromJson(t,r){return(new ll).fromJson(t,r)}static fromJsonString(t,r){return(new ll).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ll,t,r)}static $(){return["SetTeamGrokBotDefaultAudienceRequest|1 team_id 5|2 agent_id 9|3 audience #0",el]}}class ml extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ml).fromBinary(t,r)}static fromJson(t,r){return(new ml).fromJson(t,r)}static fromJsonString(t,r){return(new ml).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ml,t,r)}static $(){return["SetTeamGrokBotDefaultAudienceResponse|1 audience #0",el]}}class fl extends Va{constructor(t){super(),this.teamId=0,this.agentId="",this.teamApproved=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fl).fromBinary(t,r)}static fromJson(t,r){return(new fl).fromJson(t,r)}static fromJsonString(t,r){return(new fl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fl,t,r)}static $(){return["SetTeamGrokBotAgentTeamApprovedRequest|1 team_id 5|2 agent_id 9|3 team_approved 8"]}}class dl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dl).fromBinary(t,r)}static fromJson(t,r){return(new dl).fromJson(t,r)}static fromJsonString(t,r){return(new dl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dl,t,r)}static $(){return["SetTeamGrokBotAgentTeamApprovedResponse|1 team_approved_at #0",s.Timestamp]}}class pl extends Va{constructor(t){super(),this.agentId="",this.creatorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pl).fromBinary(t,r)}static fromJson(t,r){return(new pl).fromJson(t,r)}static fromJsonString(t,r){return(new pl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pl,t,r)}static $(){return["TeamGrokBotAgentAccess|1 agent_id 9|2 state #0|3 creator_user_id 5",wa]}}class hl extends Va{constructor(t){super(),this.teamId=0,this.agentIds=[],this.listsCrossTierPrincipals=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hl).fromBinary(t,r)}static fromJson(t,r){return(new hl).fromJson(t,r)}static fromJsonString(t,r){return(new hl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hl,t,r)}static $(){return["ListTeamGrokBotAgentAccessRequest|1 team_id 5|2 agent_ids 9*|3 lists_cross_tier_principals 8"]}}class gl extends Va{constructor(t){super(),this.agents=[],this.enabled=!1,this.settingUpAgentIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gl).fromBinary(t,r)}static fromJson(t,r){return(new gl).fromJson(t,r)}static fromJsonString(t,r){return(new gl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gl,t,r)}static $(){return["ListTeamGrokBotAgentAccessResponse|1 agents #0*|2 enabled 8|3 setting_up_agent_ids 9*",pl]}}class _l extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _l).fromBinary(t,r)}static fromJson(t,r){return(new _l).fromJson(t,r)}static fromJsonString(t,r){return(new _l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_l,t,r)}static $(){return["SetTeamGrokBotAgentAccessRequest|1 team_id 5|2 agent_id 9|3 update #0",ya]}}class Jl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jl).fromBinary(t,r)}static fromJson(t,r){return(new Jl).fromJson(t,r)}static fromJsonString(t,r){return(new Jl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jl,t,r)}static $(){return["SetTeamGrokBotAgentAccessResponse|1 access #0",pl]}}class wl extends Va{constructor(t){super(),this.teamId=0,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wl).fromBinary(t,r)}static fromJson(t,r){return(new wl).fromJson(t,r)}static fromJsonString(t,r){return(new wl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wl,t,r)}static $(){return["TeamGrokBotAccessTeam|1 team_id 5|2 name 9|3 icon_url 9?"]}}class yl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yl).fromBinary(t,r)}static fromJson(t,r){return(new yl).fromJson(t,r)}static fromJsonString(t,r){return(new yl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yl,t,r)}static $(){return["ListTeamGrokBotAccessTeamsRequest|1 team_id 5"]}}class Sl extends Va{constructor(t){super(),this.enabled=!1,this.organizationName="",this.teams=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sl).fromBinary(t,r)}static fromJson(t,r){return(new Sl).fromJson(t,r)}static fromJsonString(t,r){return(new Sl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sl,t,r)}static $(){return["ListTeamGrokBotAccessTeamsResponse|1 enabled 8|2 organization_name 9|3 teams #0*",wl]}}class ql extends Va{constructor(t){super(),this.teamId=0,this.agentIds=[],this.destinationTeamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ql).fromBinary(t,r)}static fromJson(t,r){return(new ql).fromJson(t,r)}static fromJsonString(t,r){return(new ql).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ql,t,r)}static $(){return["PreviewTeamGrokBotAgentTransferRequest|1 team_id 5|2 agent_ids 9*|3 destination_team_id 5"]}}class Bl extends Va{constructor(t){super(),this.items=[],this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bl).fromBinary(t,r)}static fromJson(t,r){return(new Bl).fromJson(t,r)}static fromJsonString(t,r){return(new Bl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bl,t,r)}static $(){return["PreviewTeamGrokBotAgentTransferResponse|1 items #0*|2 enabled 8",Fa]}}class Il extends Va{constructor(t){super(),this.teamId=0,this.items=[],this.destinationTeamId=0,this.idempotencyKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Il).fromBinary(t,r)}static fromJson(t,r){return(new Il).fromJson(t,r)}static fromJsonString(t,r){return(new Il).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Il,t,r)}static $(){return["TransferTeamGrokBotAgentsRequest|1 team_id 5|2 items #0*|3 destination_team_id 5|4 idempotency_key 9",Ka]}}class Pl extends Va{constructor(t){super(),this.items=[],this.bulkOperationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pl).fromBinary(t,r)}static fromJson(t,r){return(new Pl).fromJson(t,r)}static fromJsonString(t,r){return(new Pl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pl,t,r)}static $(){return["TransferTeamGrokBotAgentsResponse|1 items #0*|2 bulk_operation_id 9",za]}}class bl extends Va{constructor(t){super(),this.teamId=0,this.transferIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bl).fromBinary(t,r)}static fromJson(t,r){return(new bl).fromJson(t,r)}static fromJsonString(t,r){return(new bl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bl,t,r)}static $(){return["GetTeamGrokBotAgentTransfersRequest|1 team_id 5|2 transfer_ids 9*"]}}class Rl extends Va{constructor(t){super(),this.transfers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rl).fromBinary(t,r)}static fromJson(t,r){return(new Rl).fromJson(t,r)}static fromJsonString(t,r){return(new Rl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rl,t,r)}static $(){return["GetTeamGrokBotAgentTransfersResponse|1 transfers #0*",ja]}}class vl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vl).fromBinary(t,r)}static fromJson(t,r){return(new vl).fromJson(t,r)}static fromJsonString(t,r){return(new vl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vl,t,r)}static $(){return["ListTeamGrokBotTransferDestinationsRequest|1 team_id 5"]}}class xl extends Va{constructor(t){super(),this.destinations=[],this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xl).fromBinary(t,r)}static fromJson(t,r){return(new xl).fromJson(t,r)}static fromJsonString(t,r){return(new xl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xl,t,r)}static $(){return["ListTeamGrokBotTransferDestinationsResponse|1 destinations #0*|2 enabled 8",Ha]}}class kl extends Va{constructor(t){super(),this.teamId=0,this.agentId="",this.newOwnerUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kl).fromBinary(t,r)}static fromJson(t,r){return(new kl).fromJson(t,r)}static fromJsonString(t,r){return(new kl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kl,t,r)}static $(){return["StartTeamGrokBotOwnershipTransferRequest|1 team_id 5|2 agent_id 9|3 new_owner_user_id 5"]}}class El extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new El).fromBinary(t,r)}static fromJson(t,r){return(new El).fromJson(t,r)}static fromJsonString(t,r){return(new El).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(El,t,r)}static $(){return["StartTeamGrokBotOwnershipTransferResponse"]}}class Cl extends Va{constructor(t){super(),this.teamId=0,this.completed=!1,this.source=nu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cl).fromBinary(t,r)}static fromJson(t,r){return(new Cl).fromJson(t,r)}static fromJsonString(t,r){return(new Cl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cl,t,r)}static $(){return["UpdateTeamSandOnboardingCompletedRequest|1 team_id 5|2 completed 8|3 source #0",nu]}}class Tl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tl).fromBinary(t,r)}static fromJson(t,r){return(new Tl).fromJson(t,r)}static fromJsonString(t,r){return(new Tl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tl,t,r)}static $(){return["UpdateTeamSandOnboardingCompletedResponse"]}}class Ul extends Va{constructor(t){super(),this.teamId=0,this.itemId="",this.state=eu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ul).fromBinary(t,r)}static fromJson(t,r){return(new Ul).fromJson(t,r)}static fromJsonString(t,r){return(new Ul).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ul,t,r)}static $(){return["UpdateTeamSandSetupChecklistItemRequest|1 team_id 5|2 item_id 9|3 state #0",eu]}}class Al extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Al).fromBinary(t,r)}static fromJson(t,r){return(new Al).fromJson(t,r)}static fromJsonString(t,r){return(new Al).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Al,t,r)}static $(){return["UpdateTeamSandSetupChecklistItemResponse"]}}class $l extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $l).fromBinary(t,r)}static fromJson(t,r){return(new $l).fromJson(t,r)}static fromJsonString(t,r){return(new $l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($l,t,r)}static $(){return["MarkTeamSandOnboardingSeenRequest|1 team_id 5"]}}class Ml extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ml).fromBinary(t,r)}static fromJson(t,r){return(new Ml).fromJson(t,r)}static fromJsonString(t,r){return(new Ml).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ml,t,r)}static $(){return["MarkTeamSandOnboardingSeenResponse"]}}class Ol extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ol).fromBinary(t,r)}static fromJson(t,r){return(new Ol).fromJson(t,r)}static fromJsonString(t,r){return(new Ol).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ol,t,r)}static $(){return["GetTeamGrokBotEligibleUserIdsRequest|1 team_id 5"]}}class Dl extends Va{constructor(t){super(),this.userIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dl).fromBinary(t,r)}static fromJson(t,r){return(new Dl).fromJson(t,r)}static fromJsonString(t,r){return(new Dl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dl,t,r)}static $(){return["GetTeamGrokBotEligibleUserIdsResponse|1 user_ids 5*"]}}class Nl extends Va{constructor(t){super(),this.teamId=0,this.userIds=[],this.groupPublicIds=[],this.directoryGroupIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nl).fromBinary(t,r)}static fromJson(t,r){return(new Nl).fromJson(t,r)}static fromJsonString(t,r){return(new Nl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nl,t,r)}static $(){return["SendTeamSandOnboardingInvitesRequest|1 team_id 5|2 user_ids 5*|3 group_public_ids 9*|4 directory_group_ids 5*"]}}class Gl extends Va{constructor(t){super(),this.sentCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gl).fromBinary(t,r)}static fromJson(t,r){return(new Gl).fromJson(t,r)}static fromJsonString(t,r){return(new Gl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gl,t,r)}static $(){return["SendTeamSandOnboardingInvitesResponse|1 sent_count 5"]}}class Ll extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ll).fromBinary(t,r)}static fromJson(t,r){return(new Ll).fromJson(t,r)}static fromJsonString(t,r){return(new Ll).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ll,t,r)}static $(){return["GetEnterpriseGrokBotTeamTrialInternalRequest|1 team_id 5"]}}class Fl extends Va{constructor(t){super(),this.trialTeam=!1,this.live=!1,this.grantCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fl).fromBinary(t,r)}static fromJson(t,r){return(new Fl).fromJson(t,r)}static fromJsonString(t,r){return(new Fl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fl,t,r)}static $(){return["GetEnterpriseGrokBotTeamTrialInternalResponse|1 trial_team 8|2 eligible_at #0?|3 expires_at #0?|4 revoked_at #0?|5 live 8|6 grant_count 5",s.Timestamp]}}class Kl extends Va{constructor(t){super(),this.teamId=0,this.requestedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kl).fromBinary(t,r)}static fromJson(t,r){return(new Kl).fromJson(t,r)}static fromJsonString(t,r){return(new Kl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kl,t,r)}static $(){return["SetEnterpriseGrokBotTeamTrialExpirationInternalRequest|1 team_id 5|2 expires_at #0|3 requested_by 9",s.Timestamp]}}class zl extends Va{constructor(t){super(),this.grantsUpdated=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zl).fromBinary(t,r)}static fromJson(t,r){return(new zl).fromJson(t,r)}static fromJsonString(t,r){return(new zl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zl,t,r)}static $(){return["SetEnterpriseGrokBotTeamTrialExpirationInternalResponse|1 expires_at #0|2 grants_updated 5",s.Timestamp]}}class jl extends Va{constructor(t){super(),this.expectedCurrentPeriodStartMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jl).fromBinary(t,r)}static fromJson(t,r){return(new jl).fromJson(t,r)}static fromJsonString(t,r){return(new jl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jl,t,r)}static $(){return["UseSandBankedResetRequest|1 expected_current_period_start_ms 3"]}}class Hl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hl).fromBinary(t,r)}static fromJson(t,r){return(new Hl).fromJson(t,r)}static fromJsonString(t,r){return(new Hl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hl,t,r)}static $(){return["UseSandBankedResetResponse|1 new_current_period_start #0",s.Timestamp]}}class Wl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wl).fromBinary(t,r)}static fromJson(t,r){return(new Wl).fromJson(t,r)}static fromJsonString(t,r){return(new Wl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wl,t,r)}static $(){return["ListSandBankedResetsRequest"]}}class Ql extends Va{constructor(t){super(),this.id=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ql).fromBinary(t,r)}static fromJson(t,r){return(new Ql).fromJson(t,r)}static fromJsonString(t,r){return(new Ql).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ql,t,r)}static $(){return["SandBankedReset|1 id 3|2 created_at #0|3 expires_at #0?",s.Timestamp]}}class Vl extends Va{constructor(t){super(),this.resets=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vl).fromBinary(t,r)}static fromJson(t,r){return(new Vl).fromJson(t,r)}static fromJsonString(t,r){return(new Vl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vl,t,r)}static $(){return["ListSandBankedResetsResponse|1 resets #0*",Ql]}}class Xl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xl).fromBinary(t,r)}static fromJson(t,r){return(new Xl).fromJson(t,r)}static fromJsonString(t,r){return(new Xl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xl,t,r)}static $(){return["GetSandAccessStatusRequest"]}}class Yl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yl).fromBinary(t,r)}static fromJson(t,r){return(new Yl).fromJson(t,r)}static fromJsonString(t,r){return(new Yl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yl,t,r)}static $(){return["ShouldShowGrokBotTrainingOptInPopupRequest"]}}class Zl extends Va{constructor(t){super(),this.show=!1,this.promptSeen=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zl).fromBinary(t,r)}static fromJson(t,r){return(new Zl).fromJson(t,r)}static fromJsonString(t,r){return(new Zl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zl,t,r)}static $(){return["ShouldShowGrokBotTrainingOptInPopupResponse|1 show 8|2 upgrade_option #0?|3 prompt_seen 8",tm]}}class tm extends Va{constructor(t){super(),this.show=!1,this.reason=rm.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tm).fromBinary(t,r)}static fromJson(t,r){return(new tm).fromJson(t,r)}static fromJsonString(t,r){return(new tm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tm,t,r)}static $(){return["SandUpgradeOption|1 show 8|2 reason #0",rm]}}var rm=(0,i.QT)(s.proto3,Qa,"SandUpgradeOption.Reason",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"TOP_TIER"],[3,"TEAM_MANAGED"],[4,"NO_UPGRADE_PATH"],[5,"UNKNOWN"]],1);class em extends Va{constructor(t){super(),this.kind=nm.UNSPECIFIED,this.planName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new em).fromBinary(t,r)}static fromJson(t,r){return(new em).fromJson(t,r)}static fromJsonString(t,r){return(new em).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(em,t,r)}static $(){return["SandUpgradeOffer|1 kind #0|2 plan_name 9|3 percent_off 5?|4 redeem_by_ms 3?|5 currency_code 9?|6 pay_upfront #1?",nm,sm]}}var nm=(0,i.QT)(s.proto3,Qa,"SandUpgradeOffer.Kind",[[0,"UNSPECIFIED"],[1,"FREE_TRIAL"],[2,"PAY_UPFRONT"],[3,"DISCOUNT"]],1);class sm extends Va{constructor(t){super(),this.period=im.UNSPECIFIED,this.periodsCovered=0,this.amountMicros=s.protoInt64.zero,this.listPriceMicros=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sm).fromBinary(t,r)}static fromJson(t,r){return(new sm).fromJson(t,r)}static fromJsonString(t,r){return(new sm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sm,t,r)}static $(){return["SandUpgradeOffer.PayUpfront|1 period #0|2 periods_covered 5|3 amount_micros 3|4 list_price_micros 3|5 periods_paid 5?",im]}}var im=(0,i.QT)(s.proto3,Qa,"SandUpgradeOffer.PayUpfront.Period",[[0,"UNSPECIFIED"],[1,"MONTH"],[2,"YEAR"]],1);class om extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new om).fromBinary(t,r)}static fromJson(t,r){return(new om).fromJson(t,r)}static fromJsonString(t,r){return(new om).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(om,t,r)}static $(){return["GetSandUpgradeOfferRequest"]}}class am extends Va{constructor(t){super(),this.readFailed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new am).fromBinary(t,r)}static fromJson(t,r){return(new am).fromJson(t,r)}static fromJsonString(t,r){return(new am).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(am,t,r)}static $(){return["GetSandUpgradeOfferResponse|1 offer #0|2 read_failed 8",em]}}class um extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new um).fromBinary(t,r)}static fromJson(t,r){return(new um).fromJson(t,r)}static fromJsonString(t,r){return(new um).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(um,t,r)}static $(){return["MarkGrokBotTrainingOptInPromptSeenRequest"]}}class cm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cm).fromBinary(t,r)}static fromJson(t,r){return(new cm).fromJson(t,r)}static fromJsonString(t,r){return(new cm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cm,t,r)}static $(){return["MarkGrokBotTrainingOptInPromptSeenResponse"]}}class lm extends Va{constructor(t){super(),this.amountCents=0,this.grantTtlDays=0,this.challenge="",this.platform="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lm).fromBinary(t,r)}static fromJson(t,r){return(new lm).fromJson(t,r)}static fromJsonString(t,r){return(new lm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lm,t,r)}static $(){return["AttestedTrialOffer|1 amount_cents 5|2 grant_ttl_days 5|3 challenge 9|4 platform 9"]}}class mm extends Va{constructor(t){super(),this.state=fm.UNSPECIFIED,this.purchaseChannel=dm.UNSPECIFIED,this.blockReason=pm.UNSPECIFIED,this.purchasableTiers=[],this.unpaidAdminNeedsPaidSeat=!1,this.privacyDisclaimerRequired=!1,this.canSkipOnboarding=!1,this.proAndSuperGrokPlansGrantAccess=!1,this.isUnified=!1,this.billingBrand=su.UNSPECIFIED,this.speechUiHidden=!1,this.grokConnectorsOnly=!1,this.grokConnectorsOnlyAllows=[],this.grokConnectorsOnlyBuiltinEntries=[],this.grokConnectorsOnlyTeamPlugins=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mm).fromBinary(t,r)}static fromJson(t,r){return(new mm).fromJson(t,r)}static fromJsonString(t,r){return(new mm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mm,t,r)}static $(){return["GetSandAccessStatusResponse|1 state #0|2 purchase_channel #1|3 block_reason #2|4 purchasable_tiers 9*|6 is_paid_trial_plan 8?|7 unpaid_admin_needs_paid_seat 8|9 privacy_disclaimer_required 8|10 can_skip_onboarding 8|11 pro_and_super_grok_plans_grant_access 8|12 is_unified 8|13 billing_brand #3|14 attested_trial_offer #4|15 unified_access_paywall #5|16 unified_trial_plans_offer #6|17 super_grok_heavy_ultra_ended_notice #7|18 speech_ui_hidden 8|19 post_sign_in_step #8|20 grok_connectors_only 8|21 account_merge_prompt #9|22 grok_connectors_only_allows 9*|23 grok_connectors_only_builtin_entries #10*|24 grok_connectors_only_team_plugins 8",fm,dm,pm,su,lm,Jm,wm,n.qKw,_m,gm,hm]}}var fm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandAccessState",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"UNAVAILABLE"],[3,"PAYMENT_REQUIRED"]],1),dm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandPurchaseChannel",[[0,"UNSPECIFIED"],[1,"IN_APP"],[2,"MANAGE_IN_CURSOR"],[3,"MANAGE_ON_WEB"]],1),pm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandAccessBlockReason",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"TEAM_PRIVACY_MODE"],[3,"TEAM_SETUP_REQUIRED"],[4,"TEAM_ACCESS_REQUIRED"],[5,"NOT_OFFERED"],[6,"FREE_TRIAL_AVAILABLE"],[7,"PAYWALL_INDIVIDUAL"],[8,"PAYWALL_TEAM_MEMBER"],[9,"PAYWALL_TEAM_ADMIN"],[10,"UNDER_MINIMUM_AGE"]],1);class hm extends Va{constructor(t){super(),this.serverIdentifier="",this.displayName="",this.description="",this.categoryKey="",this.websiteUrl="",this.supersedesMarketplacePluginNames=[],this.iconUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hm).fromBinary(t,r)}static fromJson(t,r){return(new hm).fromJson(t,r)}static fromJsonString(t,r){return(new hm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hm,t,r)}static $(){return["SandBuiltinCatalogEntry|1 server_identifier 9|2 display_name 9|3 description 9|4 category_key 9|5 website_url 9|6 supersedes_marketplace_plugin_names 9*|7 icon_url 9"]}}class gm extends Va{constructor(t){super(),this.title="",this.body="",this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gm).fromBinary(t,r)}static fromJson(t,r){return(new gm).fromJson(t,r)}static fromJsonString(t,r){return(new gm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gm,t,r)}static $(){return["SandAccountMergePrompt|1 title 9|2 body 9|3 action_label 9|4 href 9"]}}class _m extends Va{constructor(t){super(),this.path="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _m).fromBinary(t,r)}static fromJson(t,r){return(new _m).fromJson(t,r)}static fromJsonString(t,r){return(new _m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_m,t,r)}static $(){return["SandPostSignInStep|1 path 9"]}}class Jm extends Va{constructor(t){super(),this.title="",this.body="",this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jm).fromBinary(t,r)}static fromJson(t,r){return(new Jm).fromJson(t,r)}static fromJsonString(t,r){return(new Jm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jm,t,r)}static $(){return["SandUnifiedAccessPaywall|1 title 9|2 body 9|3 action_label 9|4 href 9"]}}class wm extends Va{constructor(t){super(),this.title="",this.price="",this.features=[],this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wm).fromBinary(t,r)}static fromJson(t,r){return(new wm).fromJson(t,r)}static fromJsonString(t,r){return(new wm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wm,t,r)}static $(){return["SandUnifiedTrialPlansOffer|1 title 9|2 price 9|3 features 9*|4 action_label 9|5 href 9|6 action #0?",Wa.bV]}}class ym extends Va{constructor(t){super(),this.toolId="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ym).fromBinary(t,r)}static fromJson(t,r){return(new ym).fromJson(t,r)}static fromJsonString(t,r){return(new ym).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ym,t,r)}static $(){return["SandMachineLocalTool|1 tool_id 9|2 state 9"]}}class Sm extends Va{constructor(t){super(),this.label="",this.kind="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sm).fromBinary(t,r)}static fromJson(t,r){return(new Sm).fromJson(t,r)}static fromJsonString(t,r){return(new Sm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sm,t,r)}static $(){return["RegisterSandMachineRequest|1 label 9|2 local_tool_permission 9?|3 messages_enabled 8?|4 kind 9"]}}class qm extends Va{constructor(t){super(),this.credential="",this.expiresAtMs=s.protoInt64.zero,this.credentialHeld=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qm).fromBinary(t,r)}static fromJson(t,r){return(new qm).fromJson(t,r)}static fromJsonString(t,r){return(new qm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qm,t,r)}static $(){return["RegisterSandMachineResponse|1 credential 9|2 expires_at_ms 3|3 credential_held 8"]}}class Bm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bm).fromBinary(t,r)}static fromJson(t,r){return(new Bm).fromJson(t,r)}static fromJsonString(t,r){return(new Bm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bm,t,r)}static $(){return["ListSandMachinesRequest"]}}class Im extends Va{constructor(t){super(),this.machineId="",this.label="",this.messagesEnabled=!1,this.kind="",this.connected=!1,this.lastRegisteredAtMs=s.protoInt64.zero,this.mobileLocalTools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Im).fromBinary(t,r)}static fromJson(t,r){return(new Im).fromJson(t,r)}static fromJsonString(t,r){return(new Im).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Im,t,r)}static $(){return["SandMachine|1 machine_id 9|2 label 9|3 local_tool_permission 9?|4 messages_enabled 8|5 kind 9|6 connected 8|7 last_heartbeat_at_ms 3?|8 last_registered_at_ms 3|9 mobile_local_tools #0*",ym]}}class Pm extends Va{constructor(t){super(),this.machines=[],this.currentMachineRemoved=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pm).fromBinary(t,r)}static fromJson(t,r){return(new Pm).fromJson(t,r)}static fromJsonString(t,r){return(new Pm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pm,t,r)}static $(){return["ListSandMachinesResponse|1 machines #0*|2 current_machine_removed 8",Im]}}class bm extends Va{constructor(t){super(),this.machineId="",this.label="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bm).fromBinary(t,r)}static fromJson(t,r){return(new bm).fromJson(t,r)}static fromJsonString(t,r){return(new bm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bm,t,r)}static $(){return["UpdateSandMachineLabelRequest|1 machine_id 9|2 label 9"]}}class Rm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rm).fromBinary(t,r)}static fromJson(t,r){return(new Rm).fromJson(t,r)}static fromJsonString(t,r){return(new Rm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rm,t,r)}static $(){return["UpdateSandMachineLabelResponse|1 machine #0",Im]}}class vm extends Va{constructor(t){super(),this.machineId="",this.localToolPermission="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vm).fromBinary(t,r)}static fromJson(t,r){return(new vm).fromJson(t,r)}static fromJsonString(t,r){return(new vm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vm,t,r)}static $(){return["UpdateSandMachineLocalToolPermissionRequest|1 machine_id 9|2 local_tool_permission 9"]}}class xm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xm).fromBinary(t,r)}static fromJson(t,r){return(new xm).fromJson(t,r)}static fromJsonString(t,r){return(new xm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xm,t,r)}static $(){return["UpdateSandMachineLocalToolPermissionResponse|1 machine #0",Im]}}class km extends Va{constructor(t){super(),this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new km).fromBinary(t,r)}static fromJson(t,r){return(new km).fromJson(t,r)}static fromJsonString(t,r){return(new km).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(km,t,r)}static $(){return["GetSandMachineMessagesEnabledRequest|1 machine_id 9"]}}class Em extends Va{constructor(t){super(),this.messagesEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Em).fromBinary(t,r)}static fromJson(t,r){return(new Em).fromJson(t,r)}static fromJsonString(t,r){return(new Em).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Em,t,r)}static $(){return["GetSandMachineMessagesEnabledResponse|1 messages_enabled 8"]}}class Cm extends Va{constructor(t){super(),this.machineId="",this.messagesEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cm).fromBinary(t,r)}static fromJson(t,r){return(new Cm).fromJson(t,r)}static fromJsonString(t,r){return(new Cm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cm,t,r)}static $(){return["UpdateSandMachineMessagesEnabledRequest|1 machine_id 9|2 messages_enabled 8"]}}class Tm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tm).fromBinary(t,r)}static fromJson(t,r){return(new Tm).fromJson(t,r)}static fromJsonString(t,r){return(new Tm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tm,t,r)}static $(){return["UpdateSandMachineMessagesEnabledResponse|1 machine #0",Im]}}class Um extends Va{constructor(t){super(),this.agentId="",this.entryId="",this.tryAgain=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Um).fromBinary(t,r)}static fromJson(t,r){return(new Um).fromJson(t,r)}static fromJsonString(t,r){return(new Um).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Um,t,r)}static $(){return["RetrySandMessagesPermissionRequest|1 agent_id 9|2 entry_id 9|3 try_again 8"]}}class Am extends Va{constructor(t){super(),this.woken=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Am).fromBinary(t,r)}static fromJson(t,r){return(new Am).fromJson(t,r)}static fromJsonString(t,r){return(new Am).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Am,t,r)}static $(){return["RetrySandMessagesPermissionResponse|1 woken 8"]}}class $m extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $m).fromBinary(t,r)}static fromJson(t,r){return(new $m).fromJson(t,r)}static fromJsonString(t,r){return(new $m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($m,t,r)}static $(){return["RequestSandTeamAccessRequest|1 team_id 5"]}}class Mm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mm).fromBinary(t,r)}static fromJson(t,r){return(new Mm).fromJson(t,r)}static fromJsonString(t,r){return(new Mm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mm,t,r)}static $(){return["RequestSandTeamAccessResponse"]}}class Om extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Om).fromBinary(t,r)}static fromJson(t,r){return(new Om).fromJson(t,r)}static fromJsonString(t,r){return(new Om).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Om,t,r)}static $(){return["GetSandMarketingIdentityRequest"]}}class Dm extends Va{constructor(t){super(),this.xaiUserId="",this.workspace=Nm.UNSPECIFIED,this.externalId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dm).fromBinary(t,r)}static fromJson(t,r){return(new Dm).fromJson(t,r)}static fromJsonString(t,r){return(new Dm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dm,t,r)}static $(){return["GetSandMarketingIdentityResponse|1 xai_user_id 9|2 workspace #0|3 external_id 9",Nm]}}var Nm=(0,i.QT)(s.proto3,Qa,"GetSandMarketingIdentityResponse.SandMarketingWorkspace",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"LEGACY"],[3,"UNIFIED"]],1);class Gm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gm).fromBinary(t,r)}static fromJson(t,r){return(new Gm).fromJson(t,r)}static fromJsonString(t,r){return(new Gm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gm,t,r)}static $(){return["GetSandUsageStatusRequest"]}}class Lm extends Va{constructor(t){super(),this.origin=iu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lm).fromBinary(t,r)}static fromJson(t,r){return(new Lm).fromJson(t,r)}static fromJsonString(t,r){return(new Lm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lm,t,r)}static $(){return["RequestSandSeatTierUpgradeRequest|1 origin #0",iu]}}class Fm extends Va{constructor(t){super(),this.success=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fm).fromBinary(t,r)}static fromJson(t,r){return(new Fm).fromJson(t,r)}static fromJsonString(t,r){return(new Fm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fm,t,r)}static $(){return["RequestSandSeatTierUpgradeResponse|1 success 8|2 error_message 9?"]}}class Km extends Va{constructor(t){super(),this.disabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Km).fromBinary(t,r)}static fromJson(t,r){return(new Km).fromJson(t,r)}static fromJsonString(t,r){return(new Km).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Km,t,r)}static $(){return["SandUpgradeRecommendation|1 cta #0|2 disabled 8|3 supporting_text 9?|4 kind 9?",Wa.Bo]}}class zm extends Va{constructor(t){super(),this.includedLimitZero=!1,this.availableBankedResetCount=s.protoInt64.zero,this.usesPooledEnterpriseAllowance=!1,this.hasAvailableUsage=!1,this.hasNonZeroIncludedLimit=!1,this.sandTrialCancelable=!1,this.upgradeRecommendations=[],this.isTeamSeat=!1,this.cursorPlanName="",this.isUnified=!1,this.billingBrand=su.UNSPECIFIED,this.unifiedUpsellButtons=[],this.accountMergePausingBots=!1,this.unifyPendingMergeUnread=!1,this.prepaidBalanceUnknown=!1,this.managedByTeamAdmin=!1,this.planUpgrades=[],this.additionalUsageLimitUnknown=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zm).fromBinary(t,r)}static fromJson(t,r){return(new zm).fromJson(t,r)}static fromJsonString(t,r){return(new zm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zm,t,r)}static $(){return["GetSandUsageStatusResponse|1 current_period_start #0|2 next_reset_timestamp_utc #0|3 usage_percent 1?|4 included_limit_zero 8|5 available_banked_reset_count 3|6 uses_pooled_enterprise_allowance 8|7 has_available_usage 8|8 has_non_zero_included_limit 8|9 upgrade_recommendation #1?|10 sand_trial_expires_at #0?|11 sand_trial_cancelable 8|12 upgrade_recommendations #1*|13 on_demand_settings #2?|14 included_usage_super_grok_plan 9?|15 grok_plan_label 9?|16 is_team_seat 8|17 cursor_plan_name 9|18 is_unified 8|19 billing_brand #3|20 unified_plan_migration #4?|21 unified_billing_url 9?|22 unified_upsell_buttons #5*|23 unify_pending_merge #6?|24 account_merge_pausing_bots 8|25 unify_pending_merge_unread 8|26 next_banked_reset_redeem_at #0?|27 upgrade_option #7?|28 prepaid_available_cents 3?|29 prepaid_balance_unknown 8|30 managed_by_team_admin 8|32 would_refuse_send 8?|31 plan_upgrades #8*|40 additional_usage_limit #9?|41 additional_usage_limit_unknown 8",s.Timestamp,Km,af,su,of,Wa.Bo,p,tm,Wm,jm]}}class jm extends Va{constructor(t){super(),this.state=Hm.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jm).fromBinary(t,r)}static fromJson(t,r){return(new jm).fromJson(t,r)}static fromJsonString(t,r){return(new jm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jm,t,r)}static $(){return["SandAdditionalUsageLimit|1 state #0|2 limit_cents 3?|3 spent_cents 3?|4 resets_at #1",Hm,s.Timestamp]}}var Hm=(0,i.QT)(s.proto3,Qa,"SandAdditionalUsageLimit.State",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"OFF"],[3,"LIMITED"]],1);class Wm extends Va{constructor(t){super(),this.planName="",this.planId="",this.url="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wm).fromBinary(t,r)}static fromJson(t,r){return(new Wm).fromJson(t,r)}static fromJsonString(t,r){return(new Wm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wm,t,r)}static $(){return["SandPlanUpgrade|1 plan_name 9|2 plan_id 9|3 url 9"]}}class Qm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qm).fromBinary(t,r)}static fromJson(t,r){return(new Qm).fromJson(t,r)}static fromJsonString(t,r){return(new Qm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qm,t,r)}static $(){return["GetGrokBotUsageBreakdownRequest|1 enterprise_team_id 5?"]}}class Vm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.source=ou.UNSPECIFIED,this.ppm=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vm).fromBinary(t,r)}static fromJson(t,r){return(new Vm).fromJson(t,r)}static fromJsonString(t,r){return(new Vm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vm,t,r)}static $(){return["GrokBotUsageSourcePpm|1 day_ms 3|2 source #0|3 ppm 5",ou]}}class Xm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.ppm=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xm).fromBinary(t,r)}static fromJson(t,r){return(new Xm).fromJson(t,r)}static fromJsonString(t,r){return(new Xm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xm,t,r)}static $(){return["GrokBotUsageBotPpm|1 day_ms 3|2 bot_id 9?|3 ppm 5"]}}class Ym extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.bySource=[],this.byBot=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ym).fromBinary(t,r)}static fromJson(t,r){return(new Ym).fromJson(t,r)}static fromJsonString(t,r){return(new Ym).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ym,t,r)}static $(){return["GrokBotUsagePpmSplits|1 period_start_ms 3|2 period_end_ms 3|3 by_source #0*|4 by_bot #1*",Vm,Xm]}}class Zm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.source=ou.UNSPECIFIED,this.cents=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zm).fromBinary(t,r)}static fromJson(t,r){return(new Zm).fromJson(t,r)}static fromJsonString(t,r){return(new Zm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zm,t,r)}static $(){return["GrokBotUsageSourceCents|1 day_ms 3|2 source #0|3 cents 3",ou]}}class tf extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.cents=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tf).fromBinary(t,r)}static fromJson(t,r){return(new tf).fromJson(t,r)}static fromJsonString(t,r){return(new tf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tf,t,r)}static $(){return["GrokBotUsageBotCents|1 day_ms 3|2 bot_id 9?|3 cents 3"]}}class rf extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.bySource=[],this.byBot=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rf).fromBinary(t,r)}static fromJson(t,r){return(new rf).fromJson(t,r)}static fromJsonString(t,r){return(new rf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rf,t,r)}static $(){return["GrokBotUsageCentsSplits|1 period_start_ms 3|2 period_end_ms 3|3 by_source #0*|4 by_bot #1*",Zm,tf]}}class ef extends Va{constructor(t){super(),this.breakdown={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ef).fromBinary(t,r)}static fromJson(t,r){return(new ef).fromJson(t,r)}static fromJsonString(t,r){return(new ef).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ef,t,r)}static $(){return["GetGrokBotUsageBreakdownResponse|1 billed_cents #0 breakdown|2 weekly_limit_ppm #1 breakdown|3 billing_cycle_ppm #1 breakdown",rf,Ym]}}class nf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nf).fromBinary(t,r)}static fromJson(t,r){return(new nf).fromJson(t,r)}static fromJsonString(t,r){return(new nf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nf,t,r)}static $(){return["GetSandEnterpriseSpendLimitRequest|1 team_id 5"]}}class sf extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.spentCents=s.protoInt64.zero,this.onDemandOnly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sf).fromBinary(t,r)}static fromJson(t,r){return(new sf).fromJson(t,r)}static fromJsonString(t,r){return(new sf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sf,t,r)}static $(){return["GetSandEnterpriseSpendLimitResponse|1 period_start_ms 3|2 period_end_ms 3|3 spent_cents 3|4 limit_cents 3?|5 on_demand_only 8"]}}class of extends Va{constructor(t){super(),this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new of).fromBinary(t,r)}static fromJson(t,r){return(new of).fromJson(t,r)}static fromJsonString(t,r){return(new of).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(of,t,r)}static $(){return["SandUnifiedPlanMigrationOffer|1 href 9"]}}class af extends Va{constructor(t){super(),this.visible=!1,this.eligible=!1,this.enabled=!1,this.dashboardUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new af).fromBinary(t,r)}static fromJson(t,r){return(new af).fromJson(t,r)}static fromJsonString(t,r){return(new af).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(af,t,r)}static $(){return["SandOnDemandSettings|1 visible 8|2 eligible 8|3 enabled 8|4 dashboard_url 9"]}}class uf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uf).fromBinary(t,r)}static fromJson(t,r){return(new uf).fromJson(t,r)}static fromJsonString(t,r){return(new uf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uf,t,r)}static $(){return["StartSandTrialRequest"]}}class cf extends Va{constructor(t){super(),this.challenge="",this.attestation={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cf).fromBinary(t,r)}static fromJson(t,r){return(new cf).fromJson(t,r)}static fromJsonString(t,r){return(new cf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cf,t,r)}static $(){return["ClaimSandTrialWithDeviceAttestationRequest|1 challenge 9|2 ios_device_check #0 attestation|3 android_play_integrity #1 attestation",lf,mf]}}class lf extends Va{constructor(t){super(),this.deviceToken="",this.bundleId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lf).fromBinary(t,r)}static fromJson(t,r){return(new lf).fromJson(t,r)}static fromJsonString(t,r){return(new lf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lf,t,r)}static $(){return["ClaimSandTrialIosDeviceCheck|1 device_token 9|2 bundle_id 9"]}}class mf extends Va{constructor(t){super(),this.integrityToken="",this.packageName="",this.deviceIdHash="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mf).fromBinary(t,r)}static fromJson(t,r){return(new mf).fromJson(t,r)}static fromJsonString(t,r){return(new mf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mf,t,r)}static $(){return["ClaimSandTrialAndroidPlayIntegrity|1 integrity_token 9|2 package_name 9|3 device_id_hash 9"]}}class ff extends Va{constructor(t){super(),this.outcome=df.UNSPECIFIED,this.amountCents=0,this.grantExpiresAtMs=s.protoInt64.zero,this.retryAfterSeconds=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ff).fromBinary(t,r)}static fromJson(t,r){return(new ff).fromJson(t,r)}static fromJsonString(t,r){return(new ff).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ff,t,r)}static $(){return["ClaimSandTrialWithDeviceAttestationResponse|1 outcome #0|2 amount_cents 5|3 grant_expires_at_ms 3|4 retry_after_seconds 5",df]}}var df=(0,i.QT)(s.proto3,Qa,"ClaimSandTrialWithDeviceAttestationResponse.ClaimSandTrialOutcome",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"ALREADY_GRANTED"],[3,"REJECTED_DUPLICATE_DEVICE"],[4,"REJECTED_ATTESTATION"],[5,"INELIGIBLE"],[6,"RETRY_LATER"]],1);class pf extends Va{constructor(t){super(),this.attestation={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pf).fromBinary(t,r)}static fromJson(t,r){return(new pf).fromJson(t,r)}static fromJsonString(t,r){return(new pf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pf,t,r)}static $(){return["ResetSandTrialDeviceAttestationRequest|1 ios_device_check #0 attestation|2 android_play_integrity #1 attestation",lf,mf]}}class hf extends Va{constructor(t){super(),this.result=gf.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hf).fromBinary(t,r)}static fromJson(t,r){return(new hf).fromJson(t,r)}static fromJsonString(t,r){return(new hf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hf,t,r)}static $(){return["ResetSandTrialDeviceAttestationResponse|1 result #0",gf]}}var gf=(0,i.QT)(s.proto3,Qa,"ResetSandTrialDeviceAttestationResponse.ResetSandTrialDeviceResult",[[0,"UNSPECIFIED"],[1,"OK"],[2,"REFUSED_BUNDLE"],[3,"REFUSED_GATE"],[4,"ERROR"]],1);class _f extends Va{constructor(t){super(),this.outcome={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _f).fromBinary(t,r)}static fromJson(t,r){return(new _f).fromJson(t,r)}static fromJsonString(t,r){return(new _f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_f,t,r)}static $(){return["StartSandTrialResponse|1 activated #0 outcome|2 card_verification_required #1 outcome",Jf,wf]}}class Jf extends Va{constructor(t){super(),this.amountCents=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jf).fromBinary(t,r)}static fromJson(t,r){return(new Jf).fromJson(t,r)}static fromJsonString(t,r){return(new Jf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jf,t,r)}static $(){return["StartSandTrialResponse.Activated|1 amount_cents 5|2 expires_at #0",s.Timestamp]}}class wf extends Va{constructor(t){super(),this.checkoutUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wf).fromBinary(t,r)}static fromJson(t,r){return(new wf).fromJson(t,r)}static fromJsonString(t,r){return(new wf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wf,t,r)}static $(){return["StartSandTrialResponse.CardVerificationRequired|1 checkout_url 9"]}}class yf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yf).fromBinary(t,r)}static fromJson(t,r){return(new yf).fromJson(t,r)}static fromJsonString(t,r){return(new yf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yf,t,r)}static $(){return["IsEligibleForSandTrialRequest"]}}class Sf extends Va{constructor(t){super(),this.isEligible=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sf).fromBinary(t,r)}static fromJson(t,r){return(new Sf).fromJson(t,r)}static fromJsonString(t,r){return(new Sf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sf,t,r)}static $(){return["IsEligibleForSandTrialResponse|1 is_eligible 8"]}}class qf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qf).fromBinary(t,r)}static fromJson(t,r){return(new qf).fromJson(t,r)}static fromJsonString(t,r){return(new qf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qf,t,r)}static $(){return["CancelSandTrialRequest"]}}class Bf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bf).fromBinary(t,r)}static fromJson(t,r){return(new Bf).fromJson(t,r)}static fromJsonString(t,r){return(new Bf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bf,t,r)}static $(){return["CancelSandTrialResponse"]}}class If extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new If).fromBinary(t,r)}static fromJson(t,r){return(new If).fromJson(t,r)}static fromJsonString(t,r){return(new If).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(If,t,r)}static $(){return["GetSandTrialClaimStatusRequest"]}}class Pf extends Va{constructor(t){super(),this.status=bf.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pf).fromBinary(t,r)}static fromJson(t,r){return(new Pf).fromJson(t,r)}static fromJsonString(t,r){return(new Pf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pf,t,r)}static $(){return["GetSandTrialClaimStatusResponse|1 status #0",bf]}}var bf=(0,i.QT)(s.proto3,Qa,"GetSandTrialClaimStatusResponse.SandTrialClaimStatus",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"PENDING_CARD"],[3,"GRANTED"],[4,"REJECTED_DUPLICATE_CARD"],[5,"BLOCKED"]],1);class Rf extends Va{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rf).fromBinary(t,r)}static fromJson(t,r){return(new Rf).fromJson(t,r)}static fromJsonString(t,r){return(new Rf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rf,t,r)}static $(){return["GetOrganizationGrokBotWallSnapshotControlsRequest|1 organization_id 9"]}}class vf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vf).fromBinary(t,r)}static fromJson(t,r){return(new vf).fromJson(t,r)}static fromJsonString(t,r){return(new vf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vf,t,r)}static $(){return["GetOrganizationGrokBotWallSnapshotControlsResponse|1 controls #0",n.lgO]}}class xf extends Va{constructor(t){super(),this.organizationId="",this.allowed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xf).fromBinary(t,r)}static fromJson(t,r){return(new xf).fromJson(t,r)}static fromJsonString(t,r){return(new xf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xf,t,r)}static $(){return["UpdateOrganizationGrokBotWallSnapshotControlsRequest|1 organization_id 9|2 allowed 8"]}}class kf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kf).fromBinary(t,r)}static fromJson(t,r){return(new kf).fromJson(t,r)}static fromJsonString(t,r){return(new kf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kf,t,r)}static $(){return["UpdateOrganizationGrokBotWallSnapshotControlsResponse|1 controls #0",n.lgO]}}class Ef extends Va{constructor(t){super(),this.automationId="",this.slackTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ef).fromBinary(t,r)}static fromJson(t,r){return(new Ef).fromJson(t,r)}static fromJsonString(t,r){return(new Ef).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ef,t,r)}static $(){return["SetSandAutomationSlackWorkspaceRequest|1 automation_id 9|2 slack_team_id 9"]}}class Cf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cf).fromBinary(t,r)}static fromJson(t,r){return(new Cf).fromJson(t,r)}static fromJsonString(t,r){return(new Cf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cf,t,r)}static $(){return["SetSandAutomationSlackWorkspaceResponse"]}}class Tf extends Va{constructor(t){super(),this.resource="",this.authorizationServerIssuer="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.clientSecretSet=!1,this.audience="",this.scope="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tf).fromBinary(t,r)}static fromJson(t,r){return(new Tf).fromJson(t,r)}static fromJsonString(t,r){return(new Tf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tf,t,r)}static $(){return["GrokBotIdJagAllowedConnector|1 resource 9|2 authorization_server_issuer 9|3 client_id 9|4 client_auth_method #0|5 client_secret 9?|6 client_secret_set 8|7 client_secret_updated_at_ms 3?|8 audience 9|9 scope 9",au]}}class Uf extends Va{constructor(t){super(),this.issuerUrl="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.clientSecretSet=!1,this.idJagConnectorPolicyMode=uu.UNSPECIFIED,this.idJagAllowedConnectors=[],this.idJagConsentFallbackAllowed=!1,this.configVersion=s.protoInt64.zero,this.updatedAtMs=s.protoInt64.zero,this.connectionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uf).fromBinary(t,r)}static fromJson(t,r){return(new Uf).fromJson(t,r)}static fromJsonString(t,r){return(new Uf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uf,t,r)}static $(){return["GrokBotIdpConnection|1 issuer_url 9|2 client_id 9|3 client_auth_method #0|4 client_secret_set 8|5 client_secret_updated_at_ms 3?|10 id_jag_connector_policy_mode #1|11 id_jag_allowed_connectors #2*|7 id_jag_consent_fallback_allowed 8|8 config_version 3|9 updated_at_ms 3|12 connection_id 9",au,uu,Tf]}}class Af extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Af).fromBinary(t,r)}static fromJson(t,r){return(new Af).fromJson(t,r)}static fromJsonString(t,r){return(new Af).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Af,t,r)}static $(){return["GetTeamGrokBotIdpConnectionRequest|1 team_id 5"]}}class $f extends Va{constructor(t){super(),this.available=!1,this.privateKeyJwtAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $f).fromBinary(t,r)}static fromJson(t,r){return(new $f).fromJson(t,r)}static fromJsonString(t,r){return(new $f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($f,t,r)}static $(){return["GetTeamGrokBotIdpConnectionResponse|1 available 8|2 connection #0|3 private_key_jwt_available 8",Uf]}}class Mf extends Va{constructor(t){super(),this.teamId=0,this.issuerUrl="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.idJagConnectorPolicyMode=uu.UNSPECIFIED,this.idJagAllowedConnectors=[],this.idJagConsentFallbackAllowed=!1,this.sendsConnectorClients=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mf).fromBinary(t,r)}static fromJson(t,r){return(new Mf).fromJson(t,r)}static fromJsonString(t,r){return(new Mf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mf,t,r)}static $(){return["UpdateTeamGrokBotIdpConnectionRequest|1 team_id 5|2 issuer_url 9|3 client_id 9|4 client_auth_method #0|5 client_secret 9?|9 id_jag_connector_policy_mode #1|10 id_jag_allowed_connectors #2*|7 id_jag_consent_fallback_allowed 8|8 expected_config_version 3?|11 expected_connection_id 9?|12 sends_connector_clients 8",au,uu,Tf]}}class Of extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Of).fromBinary(t,r)}static fromJson(t,r){return(new Of).fromJson(t,r)}static fromJsonString(t,r){return(new Of).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Of,t,r)}static $(){return["UpdateTeamGrokBotIdpConnectionResponse|1 connection #0",Uf]}}class Df extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Df).fromBinary(t,r)}static fromJson(t,r){return(new Df).fromJson(t,r)}static fromJsonString(t,r){return(new Df).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Df,t,r)}static $(){return["DeleteTeamGrokBotIdpConnectionRequest|1 team_id 5"]}}class Nf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nf).fromBinary(t,r)}static fromJson(t,r){return(new Nf).fromJson(t,r)}static fromJsonString(t,r){return(new Nf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nf,t,r)}static $(){return["DeleteTeamGrokBotIdpConnectionResponse"]}}class Gf extends Va{constructor(t){super(),this.id="",this.prefix="",this.createdByUserId=s.protoInt64.zero,this.createdAtEpochMillis=s.protoInt64.zero,this.expiresAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gf).fromBinary(t,r)}static fromJson(t,r){return(new Gf).fromJson(t,r)}static fromJsonString(t,r){return(new Gf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gf,t,r)}static $(){return["TeamGrokBotScimToken|1 id 9|2 prefix 9|3 created_by_user_id 3|4 created_at_epoch_millis 3|5 expires_at_epoch_millis 3|6 last_used_at_epoch_millis 3?"]}}class Lf extends Va{constructor(t){super(),this.id="",this.enabled=!1,this.baseUrl="",this.ipAllowlist=[],this.tokens=[],this.createdAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lf).fromBinary(t,r)}static fromJson(t,r){return(new Lf).fromJson(t,r)}static fromJsonString(t,r){return(new Lf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lf,t,r)}static $(){return["TeamGrokBotScimDirectory|1 id 9|2 enabled 8|3 base_url 9|4 ip_allowlist 9*|5 last_request_at_epoch_millis 3?|6 last_error_at_epoch_millis 3?|7 last_error_detail 9?|8 tokens #0*|9 created_at_epoch_millis 3",Gf]}}class Ff extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ff).fromBinary(t,r)}static fromJson(t,r){return(new Ff).fromJson(t,r)}static fromJsonString(t,r){return(new Ff).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ff,t,r)}static $(){return["GetTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class Kf extends Va{constructor(t){super(),this.available=!1,this.tokensAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kf).fromBinary(t,r)}static fromJson(t,r){return(new Kf).fromJson(t,r)}static fromJsonString(t,r){return(new Kf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kf,t,r)}static $(){return["GetTeamGrokBotScimDirectoryResponse|1 available 8|2 directory #0?|3 tokens_available 8",Lf]}}class zf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zf).fromBinary(t,r)}static fromJson(t,r){return(new zf).fromJson(t,r)}static fromJsonString(t,r){return(new zf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zf,t,r)}static $(){return["EnableTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class jf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jf).fromBinary(t,r)}static fromJson(t,r){return(new jf).fromJson(t,r)}static fromJsonString(t,r){return(new jf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jf,t,r)}static $(){return["EnableTeamGrokBotScimDirectoryResponse|1 directory #0",Lf]}}class Hf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hf).fromBinary(t,r)}static fromJson(t,r){return(new Hf).fromJson(t,r)}static fromJsonString(t,r){return(new Hf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hf,t,r)}static $(){return["DisableTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class Wf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wf).fromBinary(t,r)}static fromJson(t,r){return(new Wf).fromJson(t,r)}static fromJsonString(t,r){return(new Wf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wf,t,r)}static $(){return["DisableTeamGrokBotScimDirectoryResponse|1 directory #0",Lf]}}class Qf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qf).fromBinary(t,r)}static fromJson(t,r){return(new Qf).fromJson(t,r)}static fromJsonString(t,r){return(new Qf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qf,t,r)}static $(){return["CreateTeamGrokBotScimTokenRequest|1 team_id 5|2 expires_in_days 5?"]}}class Vf extends Va{constructor(t){super(),this.plaintextToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vf).fromBinary(t,r)}static fromJson(t,r){return(new Vf).fromJson(t,r)}static fromJsonString(t,r){return(new Vf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vf,t,r)}static $(){return["CreateTeamGrokBotScimTokenResponse|1 directory #0|2 token #1|3 plaintext_token 9",Lf,Gf]}}class Xf extends Va{constructor(t){super(),this.teamId=0,this.tokenId="",this.rotation=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xf).fromBinary(t,r)}static fromJson(t,r){return(new Xf).fromJson(t,r)}static fromJsonString(t,r){return(new Xf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xf,t,r)}static $(){return["RevokeTeamGrokBotScimTokenRequest|1 team_id 5|2 token_id 9|3 rotation 8"]}}class Yf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yf).fromBinary(t,r)}static fromJson(t,r){return(new Yf).fromJson(t,r)}static fromJsonString(t,r){return(new Yf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yf,t,r)}static $(){return["RevokeTeamGrokBotScimTokenResponse|1 directory #0",Lf]}}class Zf extends Va{constructor(t){super(),this.teamId=0,this.ipAllowlist=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zf).fromBinary(t,r)}static fromJson(t,r){return(new Zf).fromJson(t,r)}static fromJsonString(t,r){return(new Zf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zf,t,r)}static $(){return["UpdateTeamGrokBotScimIpAllowlistRequest|1 team_id 5|2 ip_allowlist 9*"]}}class td extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new td).fromBinary(t,r)}static fromJson(t,r){return(new td).fromJson(t,r)}static fromJsonString(t,r){return(new td).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(td,t,r)}static $(){return["UpdateTeamGrokBotScimIpAllowlistResponse|1 directory #0",Lf]}}class rd extends Va{constructor(t){super(),this.agentId="",this.name="",this.userName="",this.hidden=!1,this.createdAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rd).fromBinary(t,r)}static fromJson(t,r){return(new rd).fromJson(t,r)}static fromJsonString(t,r){return(new rd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rd,t,r)}static $(){return["TeamGrokBotScimBot|1 agent_id 9|2 name 9|3 user_name 9|4 manager 9?|5 hidden 8|6 created_at_epoch_millis 3|7 hidden_at_epoch_millis 3?"]}}class ed extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ed).fromBinary(t,r)}static fromJson(t,r){return(new ed).fromJson(t,r)}static fromJsonString(t,r){return(new ed).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ed,t,r)}static $(){return["ListTeamGrokBotScimBotsRequest|1 team_id 5"]}}class nd extends Va{constructor(t){super(),this.bots=[],this.activeCount=0,this.hiddenCount=0,this.truncated=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nd).fromBinary(t,r)}static fromJson(t,r){return(new nd).fromJson(t,r)}static fromJsonString(t,r){return(new nd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nd,t,r)}static $(){return["ListTeamGrokBotScimBotsResponse|1 bots #0*|2 active_count 5|3 hidden_count 5|4 truncated 8",rd]}}class sd extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sd).fromBinary(t,r)}static fromJson(t,r){return(new sd).fromJson(t,r)}static fromJsonString(t,r){return(new sd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sd,t,r)}static $(){return["DeleteTeamGrokBotScimBotRequest|1 team_id 5|2 agent_id 9"]}}class id extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new id).fromBinary(t,r)}static fromJson(t,r){return(new id).fromJson(t,r)}static fromJsonString(t,r){return(new id).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(id,t,r)}static $(){return["DeleteTeamGrokBotScimBotResponse"]}}class od extends Va{constructor(t){super(),this.pem="",this.sha256Fingerprint="",this.notBeforeEpochMillis=s.protoInt64.zero,this.notAfterEpochMillis=s.protoInt64.zero,this.subject="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new od).fromBinary(t,r)}static fromJson(t,r){return(new od).fromJson(t,r)}static fromJsonString(t,r){return(new od).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(od,t,r)}static $(){return["TeamGrokBotScimSigningCertificate|1 pem 9|2 sha256_fingerprint 9|3 not_before_epoch_millis 3|4 not_after_epoch_millis 3|5 subject 9"]}}class ad extends Va{constructor(t){super(),this.identityId="",this.oktaOrgUrl="",this.oidcClientId="",this.oidcClientSecretSet=!1,this.samlIdpId="",this.samlAudience="",this.samlIssuer="",this.signingKeySet=!1,this.configVersion=0,this.updatedAtEpochMillis=s.protoInt64.zero,this.oktaSignInMethod=cu.UNSPECIFIED,this.oktaClientAuthMethod=lu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ad).fromBinary(t,r)}static fromJson(t,r){return(new ad).fromJson(t,r)}static fromJsonString(t,r){return(new ad).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ad,t,r)}static $(){return["TeamGrokBotScimIdpIdentity|1 identity_id 9|2 okta_org_url 9|3 oidc_client_id 9|4 oidc_client_secret_set 8|5 saml_idp_id 9|6 saml_audience 9|7 saml_issuer 9|8 signing_key_set 8|9 signing_certificate #0?|10 config_version 5|11 updated_at_epoch_millis 3|12 okta_sign_in_method #1|13 okta_client_auth_method #2",od,cu,lu]}}class ud extends Va{constructor(t){super(),this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ud).fromBinary(t,r)}static fromJson(t,r){return(new ud).fromJson(t,r)}static fromJsonString(t,r){return(new ud).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ud,t,r)}static $(){return["TeamGrokBotScimIdJagServer|1 server_url 9|2 client_id 9?"]}}class cd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cd).fromBinary(t,r)}static fromJson(t,r){return(new cd).fromJson(t,r)}static fromJsonString(t,r){return(new cd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cd,t,r)}static $(){return["GetTeamGrokBotScimIdpIdentityRequest|1 team_id 5"]}}class ld extends Va{constructor(t){super(),this.available=!1,this.oktaRedirectUri="",this.idJagServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ld).fromBinary(t,r)}static fromJson(t,r){return(new ld).fromJson(t,r)}static fromJsonString(t,r){return(new ld).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ld,t,r)}static $(){return["GetTeamGrokBotScimIdpIdentityResponse|1 available 8|2 identity #0?|3 okta_redirect_uri 9|4 id_jag_servers #1*",ad,ud]}}class md extends Va{constructor(t){super(),this.teamId=0,this.oktaOrgUrl="",this.oidcClientId="",this.samlIdpId="",this.samlAudience="",this.samlIssuer="",this.expectedConfigVersion=0,this.expectedIdentityId="",this.oktaSignInMethod=cu.UNSPECIFIED,this.oktaClientAuthMethod=lu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new md).fromBinary(t,r)}static fromJson(t,r){return(new md).fromJson(t,r)}static fromJsonString(t,r){return(new md).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(md,t,r)}static $(){return["UpdateTeamGrokBotScimIdpIdentityRequest|1 team_id 5|2 okta_org_url 9|3 oidc_client_id 9|4 oidc_client_secret 9?|5 saml_idp_id 9|6 saml_audience 9|7 saml_issuer 9|8 signing_certificate_pem 9?|9 signing_private_key_pem 9?|10 expected_config_version 5|11 expected_identity_id 9|12 okta_sign_in_method #0|13 okta_client_auth_method #1",cu,lu]}}class fd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fd).fromBinary(t,r)}static fromJson(t,r){return(new fd).fromJson(t,r)}static fromJsonString(t,r){return(new fd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fd,t,r)}static $(){return["UpdateTeamGrokBotScimIdpIdentityResponse|1 identity #0",ad]}}class dd extends Va{constructor(t){super(),this.teamId=0,this.expectedConfigVersion=0,this.expectedIdentityId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dd).fromBinary(t,r)}static fromJson(t,r){return(new dd).fromJson(t,r)}static fromJsonString(t,r){return(new dd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dd,t,r)}static $(){return["GenerateTeamGrokBotScimIdpSigningKeyRequest|1 team_id 5|2 expected_config_version 5|3 expected_identity_id 9"]}}class pd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pd).fromBinary(t,r)}static fromJson(t,r){return(new pd).fromJson(t,r)}static fromJsonString(t,r){return(new pd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pd,t,r)}static $(){return["GenerateTeamGrokBotScimIdpSigningKeyResponse|1 identity #0",ad]}}class hd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hd).fromBinary(t,r)}static fromJson(t,r){return(new hd).fromJson(t,r)}static fromJsonString(t,r){return(new hd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hd,t,r)}static $(){return["DeleteTeamGrokBotScimIdpIdentityRequest|1 team_id 5"]}}class gd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gd).fromBinary(t,r)}static fromJson(t,r){return(new gd).fromJson(t,r)}static fromJsonString(t,r){return(new gd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gd,t,r)}static $(){return["DeleteTeamGrokBotScimIdpIdentityResponse"]}}class _d extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _d).fromBinary(t,r)}static fromJson(t,r){return(new _d).fromJson(t,r)}static fromJsonString(t,r){return(new _d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_d,t,r)}static $(){return["GetTeamGrokBotPublishedWorkerImageRequest|1 team_id 5"]}}class Jd extends Va{constructor(t){super(),this.workerImageVersion=s.protoInt64.zero,this.imageTag="",this.gitCommit="",this.fromLastKnown=!1,this.failure=fu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jd).fromBinary(t,r)}static fromJson(t,r){return(new Jd).fromJson(t,r)}static fromJsonString(t,r){return(new Jd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jd,t,r)}static $(){return["GrokBotPublishedWorkerImage|1 worker_image_version 3|2 image_tag 9|3 git_commit 9|4 from_last_known 8|5 read_at_ms 3?|6 failure #0",fu]}}class wd extends Va{constructor(t){super(),this.state=mu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wd).fromBinary(t,r)}static fromJson(t,r){return(new wd).fromJson(t,r)}static fromJsonString(t,r){return(new wd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wd,t,r)}static $(){return["GetTeamGrokBotPublishedWorkerImageResponse|1 state #0|2 image #1",mu,Jd]}}class yd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yd).fromBinary(t,r)}static fromJson(t,r){return(new yd).fromJson(t,r)}static fromJsonString(t,r){return(new yd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yd,t,r)}static $(){return["ListTeamGrokBotCustomerHostedWorkersRequest|1 team_id 5"]}}class Sd extends Va{constructor(t){super(),this.poolName="",this.workers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sd).fromBinary(t,r)}static fromJson(t,r){return(new Sd).fromJson(t,r)}static fromJsonString(t,r){return(new Sd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sd,t,r)}static $(){return["ListTeamGrokBotCustomerHostedWorkersResponse|1 pool_name 9|2 workers #0*",Id]}}class qd extends Va{constructor(t){super(),this.manifestId="",this.revision="",this.ok=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qd).fromBinary(t,r)}static fromJson(t,r){return(new qd).fromJson(t,r)}static fromJsonString(t,r){return(new qd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qd,t,r)}static $(){return["GrokBotCustomerHostedWorkerSetupManifest|1 manifest_id 9|2 revision 9|3 ok 8"]}}class Bd extends Va{constructor(t){super(),this.state=du.UNSPECIFIED,this.manifests=[],this.truncatedCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bd).fromBinary(t,r)}static fromJson(t,r){return(new Bd).fromJson(t,r)}static fromJsonString(t,r){return(new Bd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bd,t,r)}static $(){return["GrokBotCustomerHostedWorkerSetup|1 state #0|2 unavailable_reason #1?|3 manifests #2*|4 truncated_count 5|5 reported_at_ms 1?",du,pu,qd]}}class Id extends Va{constructor(t){super(),this.workerId="",this.name="",this.connectedAtMs=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Id).fromBinary(t,r)}static fromJson(t,r){return(new Id).fromJson(t,r)}static fromJsonString(t,r){return(new Id).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Id,t,r)}static $(){return["GrokBotCustomerHostedWorker|1 worker_id 9|2 name 9|3 connected_at_ms 1|4 image_digest 9?|5 customer_version 9?|6 worker_image_tag 9?|7 worker_image_version 9?|8 setup #0?",Bd]}}class Pd extends Va{constructor(t){super(),this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pd).fromBinary(t,r)}static fromJson(t,r){return(new Pd).fromJson(t,r)}static fromJsonString(t,r){return(new Pd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pd,t,r)}static $(){return["RemoveSandMachineRequest|1 machine_id 9"]}}class bd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bd).fromBinary(t,r)}static fromJson(t,r){return(new bd).fromJson(t,r)}static fromJsonString(t,r){return(new bd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bd,t,r)}static $(){return["RemoveSandMachineResponse"]}}class Rd extends Va{constructor(t){super(),this.userId=0,this.email="",this.name="",this.role=hu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rd).fromBinary(t,r)}static fromJson(t,r){return(new Rd).fromJson(t,r)}static fromJsonString(t,r){return(new Rd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rd,t,r)}static $(){return["TeamGrokBotDashboardAccessEntry|1 user_id 5|2 email 9|3 name 9|4 role #0",hu]}}class vd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vd).fromBinary(t,r)}static fromJson(t,r){return(new vd).fromJson(t,r)}static fromJsonString(t,r){return(new vd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vd,t,r)}static $(){return["ListTeamGrokBotDashboardAccessRequest|1 team_id 5"]}}class xd extends Va{constructor(t){super(),this.enabled=!1,this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xd).fromBinary(t,r)}static fromJson(t,r){return(new xd).fromJson(t,r)}static fromJsonString(t,r){return(new xd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xd,t,r)}static $(){return["ListTeamGrokBotDashboardAccessResponse|1 enabled 8|2 entries #0*",Rd]}}class kd extends Va{constructor(t){super(),this.teamId=0,this.userId=0,this.role=hu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kd).fromBinary(t,r)}static fromJson(t,r){return(new kd).fromJson(t,r)}static fromJsonString(t,r){return(new kd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kd,t,r)}static $(){return["SetTeamGrokBotDashboardAccessRequest|1 team_id 5|2 user_id 5|3 role #0",hu]}}class Ed extends Va{constructor(t){super(),this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ed).fromBinary(t,r)}static fromJson(t,r){return(new Ed).fromJson(t,r)}static fromJsonString(t,r){return(new Ed).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ed,t,r)}static $(){return["SetTeamGrokBotDashboardAccessResponse|1 entries #0*",Rd]}}class Cd extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class Td extends Cd{constructor(t){super(),this.teamId=0,this.allTeams=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Td).fromBinary(t,r)}static fromJson(t,r){return(new Td).fromJson(t,r)}static fromJsonString(t,r){return(new Td).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Td,t,r)}static $(){return["GetTeamTailnetRequest|1 team_id 5|2 all_teams 8"]}}class Ud extends Cd{constructor(t){super(),this.enabled=!1,this.magicDnsSuffix="",this.enabledAtMs=s.protoInt64.zero,this.available=!1,this.canManage=!1,this.teams=[],this.companyCaAvailable=!1,this.companyCas=[],this.magicDnsSuffixes=[],this.multipleAvailable=!1,this.tailnetNames={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ud).fromBinary(t,r)}static fromJson(t,r){return(new Ud).fromJson(t,r)}static fromJsonString(t,r){return(new Ud).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ud,t,r)}static $(){return["GetTeamTailnetResponse|1 enabled 8|2 magic_dns_suffix 9|3 enabled_at_ms 3|4 available 8|5 can_manage 8|8 member_device_count 5?|10 teams #0*|11 company_ca_available 8|12 company_cas #1*|13 magic_dns_suffixes 9*|14 multiple_available 8|15 active #2|16 tailnet_names 9,9|17 box_access #3|18 allow_unlabeled 8?|19 exit_nodes #4",Gd,Ld,Od,Md,Ad]}}class Ad extends Cd{constructor(t){super(),this.exitNodes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ad).fromBinary(t,r)}static fromJson(t,r){return(new Ad).fromJson(t,r)}static fromJsonString(t,r){return(new Ad).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ad,t,r)}static $(){return["TeamTailnetExitNodes|1 exit_nodes #0*",$d]}}class $d extends Cd{constructor(t){super(),this.magicDnsSuffix="",this.nodeId="",this.nodeName="",this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $d).fromBinary(t,r)}static fromJson(t,r){return(new $d).fromJson(t,r)}static fromJsonString(t,r){return(new $d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($d,t,r)}static $(){return["TeamTailnetExitNode|1 magic_dns_suffix 9|2 node_id 9|3 node_name 9|4 cidrs 9*"]}}class Md extends Cd{constructor(t){super(),this.magicDnsSuffixes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Md).fromBinary(t,r)}static fromJson(t,r){return(new Md).fromJson(t,r)}static fromJsonString(t,r){return(new Md).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Md,t,r)}static $(){return["TeamTailnetBoxAccess|1 magic_dns_suffixes 9*"]}}class Od extends Cd{constructor(t){super(),this.choice={case:void 0},this.chosen=!1,this.personalAccountKey="",this.magicDnsSuffix="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Od).fromBinary(t,r)}static fromJson(t,r){return(new Od).fromJson(t,r)}static fromJsonString(t,r){return(new Od).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Od,t,r)}static $(){return["ActiveTailnet|1 personal 8 choice|2 team_id 5 choice|3 chosen 8|4 personal_account_key 9|5 magic_dns_suffix 9"]}}class Dd extends Cd{constructor(t){super(),this.choice={case:void 0},this.personalAccountKey="",this.magicDnsSuffix="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dd).fromBinary(t,r)}static fromJson(t,r){return(new Dd).fromJson(t,r)}static fromJsonString(t,r){return(new Dd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dd,t,r)}static $(){return["SetActiveTailnetRequest|1 personal 8 choice|2 team_id 5 choice|3 personal_account_key 9|4 magic_dns_suffix 9"]}}class Nd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nd).fromBinary(t,r)}static fromJson(t,r){return(new Nd).fromJson(t,r)}static fromJsonString(t,r){return(new Nd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nd,t,r)}static $(){return["SetActiveTailnetResponse"]}}class Gd extends Cd{constructor(t){super(),this.teamId=0,this.teamName="",this.enabled=!1,this.magicDnsSuffix="",this.enabledAtMs=s.protoInt64.zero,this.available=!1,this.canManage=!1,this.companyCaAvailable=!1,this.companyCas=[],this.magicDnsSuffixes=[],this.multipleAvailable=!1,this.tailnetNames={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gd).fromBinary(t,r)}static fromJson(t,r){return(new Gd).fromJson(t,r)}static fromJsonString(t,r){return(new Gd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gd,t,r)}static $(){return["TeamTailnetTeamView|1 team_id 5|2 team_name 9|3 enabled 8|4 magic_dns_suffix 9|5 enabled_at_ms 3|6 available 8|7 can_manage 8|10 member_device_count 5?|12 company_ca_available 8|13 company_cas #0*|14 magic_dns_suffixes 9*|15 multiple_available 8|16 tailnet_names 9,9|17 box_access #1|18 allow_unlabeled 8?|19 exit_nodes #2",Ld,Md,Ad]}}class Ld extends Cd{constructor(t){super(),this.subject="",this.sha256Fingerprint="",this.notAfterMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ld).fromBinary(t,r)}static fromJson(t,r){return(new Ld).fromJson(t,r)}static fromJsonString(t,r){return(new Ld).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ld,t,r)}static $(){return["TeamTailnetCompanyCa|1 subject 9|2 sha256_fingerprint 9|3 not_after_ms 3"]}}class Fd extends Cd{constructor(t){super(),this.teamId=0,this.enabled=!1,this.magicDnsSuffix="",this.consent=!1,this.magicDnsSuffixes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fd).fromBinary(t,r)}static fromJson(t,r){return(new Fd).fromJson(t,r)}static fromJsonString(t,r){return(new Fd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fd,t,r)}static $(){return["UpdateTeamTailnetRequest|1 team_id 5|2 enabled 8|3 magic_dns_suffix 9|4 consent 8|5 magic_dns_suffixes 9*|6 allow_unlabeled 8?"]}}class Kd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kd).fromBinary(t,r)}static fromJson(t,r){return(new Kd).fromJson(t,r)}static fromJsonString(t,r){return(new Kd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kd,t,r)}static $(){return["UpdateTeamTailnetResponse"]}}class zd extends Cd{constructor(t){super(),this.teamId=0,this.companyCaBundle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zd).fromBinary(t,r)}static fromJson(t,r){return(new zd).fromJson(t,r)}static fromJsonString(t,r){return(new zd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zd,t,r)}static $(){return["UpdateTeamTailnetCompanyCaRequest|1 team_id 5|2 company_ca_bundle 9"]}}class jd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jd).fromBinary(t,r)}static fromJson(t,r){return(new jd).fromJson(t,r)}static fromJsonString(t,r){return(new jd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jd,t,r)}static $(){return["UpdateTeamTailnetCompanyCaResponse"]}}class Hd extends Cd{constructor(t){super(),this.teamId=0,this.magicDnsSuffix="",this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hd).fromBinary(t,r)}static fromJson(t,r){return(new Hd).fromJson(t,r)}static fromJsonString(t,r){return(new Hd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hd,t,r)}static $(){return["UpdateTeamTailnetBoxAccessRequest|1 team_id 5|2 magic_dns_suffix 9|3 enabled 8"]}}class Wd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wd).fromBinary(t,r)}static fromJson(t,r){return(new Wd).fromJson(t,r)}static fromJsonString(t,r){return(new Wd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wd,t,r)}static $(){return["UpdateTeamTailnetBoxAccessResponse"]}}class Qd extends Cd{constructor(t){super(),this.teamId=0,this.magicDnsSuffix="",this.nodeId="",this.nodeName="",this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qd).fromBinary(t,r)}static fromJson(t,r){return(new Qd).fromJson(t,r)}static fromJsonString(t,r){return(new Qd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qd,t,r)}static $(){return["UpdateTeamTailnetExitNodeRequest|1 team_id 5|2 magic_dns_suffix 9|3 node_id 9|4 node_name 9|5 cidrs 9*"]}}class Vd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vd).fromBinary(t,r)}static fromJson(t,r){return(new Vd).fromJson(t,r)}static fromJsonString(t,r){return(new Vd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vd,t,r)}static $(){return["UpdateTeamTailnetExitNodeResponse"]}}class Xd extends Cd{constructor(t){super(),this.teamId=0,this.start=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xd).fromBinary(t,r)}static fromJson(t,r){return(new Xd).fromJson(t,r)}static fromJsonString(t,r){return(new Xd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xd,t,r)}static $(){return["DiscoverTeamTailnetSuffixRequest|1 team_id 5|2 start 8"]}}class Yd extends Cd{constructor(t){super(),this.signInUrl="",this.magicDnsSuffix="",this.failureReason="",this.tailnetName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yd).fromBinary(t,r)}static fromJson(t,r){return(new Yd).fromJson(t,r)}static fromJsonString(t,r){return(new Yd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yd,t,r)}static $(){return["DiscoverTeamTailnetSuffixResponse|1 sign_in_url 9|2 magic_dns_suffix 9|3 failure_reason 9|4 tailnet_name 9"]}}class Zd extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class tp extends Zd{constructor(t){super(),this.subjectKey="",this.score=0,this.sampleCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tp).fromBinary(t,r)}static fromJson(t,r){return(new tp).fromJson(t,r)}static fromJsonString(t,r){return(new tp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tp,t,r)}static $(){return["SubjectScore|1 subject_key 9|2 score 1|3 sample_count 1"]}}class rp extends Zd{constructor(t){super(),this.sourceWatermarkMs=s.protoInt64.zero,this.generatedAtMs=s.protoInt64.zero,this.expiresAtMs=s.protoInt64.zero,this.scores=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rp).fromBinary(t,r)}static fromJson(t,r){return(new rp).fromJson(t,r)}static fromJsonString(t,r){return(new rp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rp,t,r)}static $(){return["ProjectionScoreSet|1 source_watermark_ms 3|2 generated_at_ms 3|3 expires_at_ms 3|4 scores #0*",tp]}}class ep extends Zd{constructor(t){super(),this.policyId="",this.knownSnapshotVersion=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ep).fromBinary(t,r)}static fromJson(t,r){return(new ep).fromJson(t,r)}static fromJsonString(t,r){return(new ep).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ep,t,r)}static $(){return["GetProjectionSnapshotRequest|1 policy_id 9|2 known_snapshot_version 4"]}}class np extends Zd{constructor(t){super(),this.policyId="",this.policyVersion=0,this.snapshotVersion=s.protoInt64.zero,this.notModified=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new np).fromBinary(t,r)}static fromJson(t,r){return(new np).fromJson(t,r)}static fromJsonString(t,r){return(new np).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(np,t,r)}static $(){return["GetProjectionSnapshotResponse|1 policy_id 9|2 policy_version 13|3 snapshot_version 4|4 team #0|5 not_modified 8",rp]}}class sp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class ip extends sp{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ip).fromBinary(t,r)}static fromJson(t,r){return(new ip).fromJson(t,r)}static fromJsonString(t,r){return(new ip).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ip,t,r)}static $(){return["ListRepoLearnedRulesRequest|1 team_id 5"]}}class op extends sp{constructor(t){super(),this.enabled=!1,this.items=[],this.truncated=!1,this.hiddenCount=0,this.live=!1,this.canEdit=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new op).fromBinary(t,r)}static fromJson(t,r){return(new op).fromJson(t,r)}static fromJsonString(t,r){return(new op).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(op,t,r)}static $(){return["ListRepoLearnedRulesResponse|1 enabled 8|2 items #0*|3 truncated 8|4 hidden_count 5|5 live 8|6 can_edit 8",ap]}}class ap extends sp{constructor(t){super(),this.id="",this.repoId="",this.gitRemoteOrigin="",this.title="",this.appliesWhen="",this.content="",this.kind="",this.scopedPaths=[],this.status="",this.importance=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ap).fromBinary(t,r)}static fromJson(t,r){return(new ap).fromJson(t,r)}static fromJsonString(t,r){return(new ap).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ap,t,r)}static $(){return["RepoLearnedRule|1 id 9|2 repo_id 9|3 git_remote_origin 9|4 title 9|5 applies_when 9|6 content 9|7 kind 9|8 item_class 9?|9 scoped_paths 9*|10 status 9|11 importance 5|12 would_promote_at #0|13 archived_at #0|14 archived_reason 9?|15 created_at #0|16 updated_at #0|17 source 9?",s.Timestamp]}}class up extends sp{constructor(t){super(),this.teamId=0,this.id="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new up).fromBinary(t,r)}static fromJson(t,r){return(new up).fromJson(t,r)}static fromJsonString(t,r){return(new up).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(up,t,r)}static $(){return["RemoveRepoLearnedRuleRequest|1 team_id 5|2 id 9"]}}class cp extends sp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cp).fromBinary(t,r)}static fromJson(t,r){return(new cp).fromJson(t,r)}static fromJsonString(t,r){return(new cp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cp,t,r)}static $(){return["RemoveRepoLearnedRuleResponse"]}}const lp="aiserver.v1.";class mp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return lp}}var fp=(0,i.QT)(s.proto3,lp,"RsiRecordKind",[[0,"UNSPECIFIED"],[1,"CONTROL"],[2,"BREAKER"],[3,"TICK"],[4,"META_RUN"],[5,"HARNESS"],[6,"JUDGEMENT"],[7,"SNAPSHOT"],[8,"DAY"],[9,"REPLY"]],1),dp=(s.proto3,(0,i.QT)(s.proto3,lp,"RsiLoop",[[0,"UNSPECIFIED"],[1,"TICK"],[2,"META"],[3,"FOLLOWUP"]],1));class pp extends mp{constructor(t){super(),this.org="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pp).fromBinary(t,r)}static fromJson(t,r){return(new pp).fromJson(t,r)}static fromJsonString(t,r){return(new pp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pp,t,r)}static $(){return["RsiRepo|1 org 9|2 name 9"]}}class hp extends mp{constructor(t){super(),this.id="",this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.writerBcId="",this.createdAt="",this.updatedAt="",this.bodyJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hp).fromBinary(t,r)}static fromJson(t,r){return(new hp).fromJson(t,r)}static fromJsonString(t,r){return(new hp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hp,t,r)}static $(){return["RsiRecord|1 id 9|2 kind #0|3 record_key 9|4 day 9|5 writer_bc_id 9|6 created_at 9|7 updated_at 9|8 body_json 9",fp]}}class gp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.bodyJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gp).fromBinary(t,r)}static fromJson(t,r){return(new gp).fromJson(t,r)}static fromJsonString(t,r){return(new gp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gp,t,r)}static $(){return["AppendRsiRecordRequest|1 team_id 5|2 repo #0|3 kind #1|4 record_key 9|5 day 9|6 body_json 9",pp,fp]}}class _p extends mp{constructor(t){super(),this.id="",this.created=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _p).fromBinary(t,r)}static fromJson(t,r){return(new _p).fromJson(t,r)}static fromJsonString(t,r){return(new _p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_p,t,r)}static $(){return["AppendRsiRecordResponse|1 id 9|2 created 8"]}}class Jp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.recordKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jp).fromBinary(t,r)}static fromJson(t,r){return(new Jp).fromJson(t,r)}static fromJsonString(t,r){return(new Jp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jp,t,r)}static $(){return["GetRsiRecordRequest|1 team_id 5|2 repo #0|3 kind #1|4 record_key 9",pp,fp]}}class wp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wp).fromBinary(t,r)}static fromJson(t,r){return(new wp).fromJson(t,r)}static fromJsonString(t,r){return(new wp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wp,t,r)}static $(){return["GetRsiRecordResponse|1 record #0",hp]}}class yp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.dayFrom="",this.dayTo="",this.pageSize=0,this.pageToken="",this.includeBody=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yp).fromBinary(t,r)}static fromJson(t,r){return(new yp).fromJson(t,r)}static fromJsonString(t,r){return(new yp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yp,t,r)}static $(){return["ListRsiRecordsRequest|1 team_id 5|2 repo #0|3 kind #1|4 day_from 9|5 day_to 9|6 page_size 5|7 page_token 9|8 include_body 8",pp,fp]}}class Sp extends mp{constructor(t){super(),this.records=[],this.nextPageToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sp).fromBinary(t,r)}static fromJson(t,r){return(new Sp).fromJson(t,r)}static fromJsonString(t,r){return(new Sp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sp,t,r)}static $(){return["ListRsiRecordsResponse|1 records #0*|2 next_page_token 9",hp]}}class qp extends mp{constructor(t){super(),this.teamId=0,this.day="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qp).fromBinary(t,r)}static fromJson(t,r){return(new qp).fromJson(t,r)}static fromJsonString(t,r){return(new qp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qp,t,r)}static $(){return["GetRsiSnapshotRequest|1 team_id 5|2 repo #0|3 day 9",pp]}}class Bp extends mp{constructor(t){super(),this.snapshotJson="",this.dayJson="",this.snapshotUpdatedAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bp).fromBinary(t,r)}static fromJson(t,r){return(new Bp).fromJson(t,r)}static fromJsonString(t,r){return(new Bp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bp,t,r)}static $(){return["GetRsiSnapshotResponse|1 snapshot_json 9|2 day_json 9|3 snapshot_updated_at 9"]}}class Ip extends mp{constructor(t){super(),this.workflowId="",this.scheduledAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ip).fromBinary(t,r)}static fromJson(t,r){return(new Ip).fromJson(t,r)}static fromJsonString(t,r){return(new Ip).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ip,t,r)}static $(){return["RsiAdminScheduleRun|1 workflow_id 9|2 scheduled_at 9"]}}class Pp extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,this.scheduleId="",this.launchEnabled=!1,this.scheduleFound=!1,this.paused=!1,this.note="",this.nextFireTimes=[],this.recentRuns=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pp).fromBinary(t,r)}static fromJson(t,r){return(new Pp).fromJson(t,r)}static fromJsonString(t,r){return(new Pp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pp,t,r)}static $(){return["RsiAdminLoop|1 loop #0|2 schedule_id 9|3 launch_enabled 8|4 schedule_found 8|5 paused 8|6 note 9|7 next_fire_times 9*|8 recent_runs #1*",dp,Ip]}}class bp extends mp{constructor(t){super(),this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.writerBcId="",this.updatedAt="",this.summaryJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bp).fromBinary(t,r)}static fromJson(t,r){return(new bp).fromJson(t,r)}static fromJsonString(t,r){return(new bp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bp,t,r)}static $(){return["RsiAdminRecord|1 kind #0|2 record_key 9|3 day 9|4 writer_bc_id 9|5 updated_at 9|6 summary_json 9",fp]}}class Rp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rp).fromBinary(t,r)}static fromJson(t,r){return(new Rp).fromJson(t,r)}static fromJsonString(t,r){return(new Rp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rp,t,r)}static $(){return["GetRsiAdminStatusInternalRequest"]}}class vp extends mp{constructor(t){super(),this.controlConfigJson="",this.controlRefusal="",this.controlError="",this.loops=[],this.records=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vp).fromBinary(t,r)}static fromJson(t,r){return(new vp).fromJson(t,r)}static fromJsonString(t,r){return(new vp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vp,t,r)}static $(){return["GetRsiAdminStatusInternalResponse|1 repo #0|2 control_config_json 9|3 control_refusal 9|4 control_error 9|5 loops #1*|6 records #2*",pp,Pp,bp]}}class xp extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xp).fromBinary(t,r)}static fromJson(t,r){return(new xp).fromJson(t,r)}static fromJsonString(t,r){return(new xp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xp,t,r)}static $(){return["RunRsiLoopNowInternalRequest|1 loop #0",dp]}}class kp extends mp{constructor(t){super(),this.workflowId="",this.outcome="",this.slot="",this.bcId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kp).fromBinary(t,r)}static fromJson(t,r){return(new kp).fromJson(t,r)}static fromJsonString(t,r){return(new kp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kp,t,r)}static $(){return["RunRsiLoopNowInternalResponse|1 workflow_id 9|2 outcome 9|3 slot 9|4 bc_id 9"]}}class Ep extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,this.paused=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ep).fromBinary(t,r)}static fromJson(t,r){return(new Ep).fromJson(t,r)}static fromJsonString(t,r){return(new Ep).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ep,t,r)}static $(){return["SetRsiLoopPausedInternalRequest|1 loop #0|2 paused 8",dp]}}class Cp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cp).fromBinary(t,r)}static fromJson(t,r){return(new Cp).fromJson(t,r)}static fromJsonString(t,r){return(new Cp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cp,t,r)}static $(){return["SetRsiLoopPausedInternalResponse|1 loop #0",Pp]}}class Tp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class Up extends Tp{constructor(t){super(),this.teamId=0,this.serviceAccountId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Up).fromBinary(t,r)}static fromJson(t,r){return(new Up).fromJson(t,r)}static fromJsonString(t,r){return(new Up).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Up,t,r)}static $(){return["SuspendTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Ap extends Tp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ap).fromBinary(t,r)}static fromJson(t,r){return(new Ap).fromJson(t,r)}static fromJsonString(t,r){return(new Ap).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ap,t,r)}static $(){return["SuspendTeamServiceAccountResponse"]}}class $p extends Tp{constructor(t){super(),this.teamId=0,this.serviceAccountId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $p).fromBinary(t,r)}static fromJson(t,r){return(new $p).fromJson(t,r)}static fromJsonString(t,r){return(new $p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($p,t,r)}static $(){return["ResumeTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Mp extends Tp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mp).fromBinary(t,r)}static fromJson(t,r){return(new Mp).fromJson(t,r)}static fromJsonString(t,r){return(new Mp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mp,t,r)}static $(){return["ResumeTeamServiceAccountResponse"]}}const Op="aiserver.v1.";class Dp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Op}}var Np=(0,i.QT)(s.proto3,Op,"XaiSubscriptionPlan",[[0,"UNSPECIFIED"],[1,"XPASS_PLUS"],[2,"XPASS_PREMIUM"],[3,"XPASS_SUPER"],[4,"XPASS_ULTRA"]],1);class Gp extends Dp{constructor(t){super(),this.cursorUserId=0,this.plan=Np.UNSPECIFIED,this.endsAt="",this.idempotencyKey="",this.grantedBy="",this.reason="",this.cursorTeamId=0,this.seats=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gp).fromBinary(t,r)}static fromJson(t,r){return(new Gp).fromJson(t,r)}static fromJsonString(t,r){return(new Gp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gp,t,r)}static $(){return["GrantSubscriptionRequest|1 cursor_user_id 5|2 plan #0|3 ends_at 9|4 idempotency_key 9|5 granted_by 9|6 reason 9|7 cursor_team_id 5|8 seats 5",Np]}}class Lp extends Dp{constructor(t){super(),this.outcome={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lp).fromBinary(t,r)}static fromJson(t,r){return(new Lp).fromJson(t,r)}static fromJsonString(t,r){return(new Lp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lp,t,r)}static $(){return["GrantSubscriptionResponse|1 result #0 outcome|2 error #1 outcome",Fp,Kp]}}class Fp extends Dp{constructor(t){super(),this.xaiUserId="",this.subscriptionId="",this.alreadyGranted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fp).fromBinary(t,r)}static fromJson(t,r){return(new Fp).fromJson(t,r)}static fromJsonString(t,r){return(new Fp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fp,t,r)}static $(){return["GrantSubscriptionResult|1 xai_user_id 9|2 subscription_id 9|3 already_granted 8"]}}class Kp extends Dp{constructor(t){super(),this.code="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kp).fromBinary(t,r)}static fromJson(t,r){return(new Kp).fromJson(t,r)}static fromJsonString(t,r){return(new Kp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kp,t,r)}static $(){return["GrantSubscriptionError|1 code 9|2 message 9"]}}const zp={typeName:"aiserver.v1.DashboardService",methods:{getTeams:{name:"GetTeams",I:n.EZo,O:n.m0q,kind:s.MethodKind.Unary},getMe:{name:"GetMe",I:n.Ewt,O:n.S7I,kind:s.MethodKind.Unary},getUnificationLegacySuperGrokPlan:{name:"GetUnificationLegacySuperGrokPlan",I:vt,O:xt,kind:s.MethodKind.Unary},getUnifyEligibility:{name:"GetUnifyEligibility",I:m,O:f,kind:s.MethodKind.Unary},getUnifyPendingMerge:{name:"GetUnifyPendingMerge",I:h,O:g,kind:s.MethodKind.Unary},getPostPurchaseMergeOffer:{name:"GetPostPurchaseMergeOffer",I:Zn,O:ts,kind:s.MethodKind.Unary},getUnifyMergeNowBanner:{name:"GetUnifyMergeNowBanner",I:rs,O:es,kind:s.MethodKind.Unary},getUnifyWaitlistStatus:{name:"GetUnifyWaitlistStatus",I:Qn,O:Vn,kind:s.MethodKind.Unary},joinUnifyWaitlist:{name:"JoinUnifyWaitlist",I:Xn,O:Yn,kind:s.MethodKind.Unary},listCollapseCandidates:{name:"ListCollapseCandidates",I:kt,O:At,kind:s.MethodKind.Unary},getUnificationIntent:{name:"GetUnificationIntent",I:Ot,O:Ft,kind:s.MethodKind.Unary},getStoreSubscriptionsToCancel:{name:"GetStoreSubscriptionsToCancel",I:Dt,O:Lt,kind:s.MethodKind.Unary},getIndividualUnificationPrepaidPreview:{name:"GetIndividualUnificationPrepaidPreview",I:zt,O:jt,kind:s.MethodKind.Unary},upsertUnificationIntent:{name:"UpsertUnificationIntent",I:Ht,O:Wt,kind:s.MethodKind.Unary},startUnifyGrokOAuth:{name:"StartUnifyGrokOAuth",I:Qt,O:Vt,kind:s.MethodKind.Unary},completeUnifyGrokOAuth:{name:"CompleteUnifyGrokOAuth",I:Xt,O:er,kind:s.MethodKind.Unary},confirmUnifyGrokUnlinkAtConflict:{name:"ConfirmUnifyGrokUnlinkAtConflict",I:Xt,O:er,kind:s.MethodKind.Unary},startTeamInviteGrokBind:{name:"StartTeamInviteGrokBind",I:Yt,O:Zt,kind:s.MethodKind.Unary},getTeamInviteGrokBindStatus:{name:"GetTeamInviteGrokBindStatus",I:tr,O:rr,kind:s.MethodKind.Unary},parkUnifyGrokOAuthForAppSheet:{name:"ParkUnifyGrokOAuthForAppSheet",I:Rn,O:vn,kind:s.MethodKind.Unary},completeUnifyGrokOAuthFromAppSheet:{name:"CompleteUnifyGrokOAuthFromAppSheet",I:xn,O:er,kind:s.MethodKind.Unary},getUnifyAlreadyUnifiedMergeOffer:{name:"GetUnifyAlreadyUnifiedMergeOffer",I:kn,O:En,kind:s.MethodKind.Unary},startUnifyAlreadyUnifiedMerge:{name:"StartUnifyAlreadyUnifiedMerge",I:Cn,O:Tn,kind:s.MethodKind.Unary},cancelUnifyAlreadyUnifiedMerge:{name:"CancelUnifyAlreadyUnifiedMerge",I:Un,O:An,kind:s.MethodKind.Unary},startUnifyXLogin:{name:"StartUnifyXLogin",I:ar,O:ur,kind:s.MethodKind.Unary},completeUnifyXLogin:{name:"CompleteUnifyXLogin",I:cr,O:lr,kind:s.MethodKind.Unary},verifyUnifyXLoginEmail:{name:"VerifyUnifyXLoginEmail",I:mr,O:lr,kind:s.MethodKind.Unary},parkUnifyXLoginForAppSheet:{name:"ParkUnifyXLoginForAppSheet",I:Kn,O:zn,kind:s.MethodKind.Unary},completeUnifyXLoginFromAppSheet:{name:"CompleteUnifyXLoginFromAppSheet",I:jn,O:lr,kind:s.MethodKind.Unary},startCollapseSourceProof:{name:"StartCollapseSourceProof",I:fr,O:dr,kind:s.MethodKind.Unary},completeCollapseSourceProof:{name:"CompleteCollapseSourceProof",I:pr,O:hr,kind:s.MethodKind.Unary},revokeCollapseSourceProof:{name:"RevokeCollapseSourceProof",I:gr,O:_r,kind:s.MethodKind.Unary},provisionUnifyGrokAccount:{name:"ProvisionUnifyGrokAccount",I:Jr,O:wr,kind:s.MethodKind.Unary},finalizeIndividualUnification:{name:"FinalizeIndividualUnification",I:qr,O:Ir,kind:s.MethodKind.Unary},getUnifyCta:{name:"GetUnifyCta",I:yr,O:Sr,kind:s.MethodKind.Unary},startUnifiedCheckout:{name:"StartUnifiedCheckout",I:In,O:Pn,kind:s.MethodKind.Unary},resolveUnifiedTeamStart:{name:"ResolveUnifiedTeamStart",I:Mn,O:On,kind:s.MethodKind.Unary},startUnifiedTeamCheckout:{name:"StartUnifiedTeamCheckout",I:Nn,O:Gn,kind:s.MethodKind.Unary},createGrokSignInLink:{name:"CreateGrokSignInLink",I:Ln,O:Fn,kind:s.MethodKind.Unary},getOrCreateXaiUnificationIntent:{name:"GetOrCreateXaiUnificationIntent",I:Pr,O:br,kind:s.MethodKind.Unary},getXaiUnificationIntent:{name:"GetXaiUnificationIntent",I:Rr,O:xr,kind:s.MethodKind.Unary},selectXaiUnificationCursorAccount:{name:"SelectXaiUnificationCursorAccount",I:kr,O:Er,kind:s.MethodKind.Unary},deselectXaiUnificationCursorAccount:{name:"DeselectXaiUnificationCursorAccount",I:Ur,O:Ar,kind:s.MethodKind.Unary},unlinkXaiUnificationCursorAccount:{name:"UnlinkXaiUnificationCursorAccount",I:Cr,O:Tr,kind:s.MethodKind.Unary},listXaiUnificationCollapseCandidates:{name:"ListXaiUnificationCollapseCandidates",I:$r,O:At,kind:s.MethodKind.Unary},startXaiUnificationCursorAccountProof:{name:"StartXaiUnificationCursorAccountProof",I:Mr,O:Or,kind:s.MethodKind.Unary},completeXaiUnificationCursorAccountProof:{name:"CompleteXaiUnificationCursorAccountProof",I:Dr,O:Nr,kind:s.MethodKind.Unary},advanceXaiUnificationIntent:{name:"AdvanceXaiUnificationIntent",I:Gr,O:Lr,kind:s.MethodKind.Unary},startXaiCursorAccountLink:{name:"StartXaiCursorAccountLink",I:Fr,O:Kr,kind:s.MethodKind.Unary},completeXaiCursorAccountLink:{name:"CompleteXaiCursorAccountLink",I:zr,O:jr,kind:s.MethodKind.Unary},peekXaiCursorAccountLinkContinuation:{name:"PeekXaiCursorAccountLinkContinuation",I:Hr,O:Wr,kind:s.MethodKind.Unary},getAgenticOnboardingConfig:{name:"GetAgenticOnboardingConfig",I:n.CQB,O:n.WQf,kind:s.MethodKind.Unary},getUserOrganizations:{name:"GetUserOrganizations",I:n.V2d,O:n.NjL,kind:s.MethodKind.Unary},getTeamLinkedOrganization:{name:"GetTeamLinkedOrganization",I:n.Pxo,O:n.RR2,kind:s.MethodKind.Unary},setUserDefaultTeam:{name:"SetUserDefaultTeam",I:n.tol,O:n.b0C,kind:s.MethodKind.Unary},getOrganizationMembers:{name:"GetOrganizationMembers",I:n.cF_,O:n.SY0,kind:s.MethodKind.Unary},getOrganizationMember:{name:"GetOrganizationMember",I:n.lN3,O:n.vBH,kind:s.MethodKind.Unary},listOrganizationIdentityProviders:{name:"ListOrganizationIdentityProviders",I:n.rq6,O:n.dSe,kind:s.MethodKind.Unary},updateOrganizationIdentityProviderSsoSettings:{name:"UpdateOrganizationIdentityProviderSsoSettings",I:n.XwO,O:n.BDH,kind:s.MethodKind.Unary},setOrganizationIdentityProviderAllowDomainJoin:{name:"SetOrganizationIdentityProviderAllowDomainJoin",I:n.bpP,O:n.BDH,kind:s.MethodKind.Unary},addOrganizationIdentityProviderDomainJoin:{name:"AddOrganizationIdentityProviderDomainJoin",I:n.$n5,O:n.BDH,kind:s.MethodKind.Unary},removeOrganizationIdentityProviderDomainJoin:{name:"RemoveOrganizationIdentityProviderDomainJoin",I:n.SFI,O:n.BDH,kind:s.MethodKind.Unary},mergeOrganizationIdentityProvider:{name:"MergeOrganizationIdentityProvider",I:n.SAH,O:n.mOD,kind:s.MethodKind.Unary},preflightMergeOrganizationIdentityProvider:{name:"PreflightMergeOrganizationIdentityProvider",I:n.FMO,O:n.PUH,kind:s.MethodKind.Unary},getOrganizationMergeIdpRequest:{name:"GetOrganizationMergeIdpRequest",I:n.bXT,O:n.TQ7,kind:s.MethodKind.Unary},listOrganizationMergeIdpRequests:{name:"ListOrganizationMergeIdpRequests",I:n.Y1Y,O:n.G2s,kind:s.MethodKind.Unary},moveOrganizationMemberToTeam:{name:"MoveOrganizationMemberToTeam",I:n.kiI,O:n.gqE,kind:s.MethodKind.Unary},setOrganizationMemberTeams:{name:"SetOrganizationMemberTeams",I:n.NW8,O:n.tP0,kind:s.MethodKind.Unary},removeOrganizationMember:{name:"RemoveOrganizationMember",I:n.rLu,O:n.Puo,kind:s.MethodKind.Unary},bulkMoveOrganizationMembers:{name:"BulkMoveOrganizationMembers",I:n.VN4,O:n.nPy,kind:s.MethodKind.Unary},startBulkMoveOrganizationMembers:{name:"StartBulkMoveOrganizationMembers",I:n.piC,O:n.T_o,kind:s.MethodKind.Unary},getBackgroundJob:{name:"GetBackgroundJob",I:n.Nbg,O:n.xel,kind:s.MethodKind.Unary},setOrganizationMemberRole:{name:"SetOrganizationMemberRole",I:n.xBJ,O:n.jFq,kind:s.MethodKind.Unary},updateOrganization:{name:"UpdateOrganization",I:n.SC0,O:n.kz1,kind:s.MethodKind.Unary},uploadOrganizationIcon:{name:"UploadOrganizationIcon",I:n.Jt2,O:n.Fmo,kind:s.MethodKind.Unary},updateOrganizationIcon:{name:"UpdateOrganizationIcon",I:n.DqU,O:n.X99,kind:s.MethodKind.Unary},updateOrganizationTeam:{name:"UpdateOrganizationTeam",I:n.Dmk,O:n.RAD,kind:s.MethodKind.Unary},createOrganizationTeam:{name:"CreateOrganizationTeam",I:n.iQx,O:n.uYE,kind:s.MethodKind.Unary},startEnterpriseGrokMigration:{name:"StartEnterpriseGrokMigration",I:ee,O:ne,kind:s.MethodKind.Unary},getEnterpriseGrokMigrationStatus:{name:"GetEnterpriseGrokMigrationStatus",I:se,O:ie,kind:s.MethodKind.Unary},getOrganizationScimSource:{name:"GetOrganizationScimSource",I:n._J0,O:n.OBE,kind:s.MethodKind.Unary},checkEnterpriseGrokMigrationEligibility:{name:"CheckEnterpriseGrokMigrationEligibility",I:te,O:re,kind:s.MethodKind.Unary},previewOrganizationTeamSettingsCopy:{name:"PreviewOrganizationTeamSettingsCopy",I:n.CrG,O:n.YQr,kind:s.MethodKind.Unary},copyOrganizationTeamSettingsToTeam:{name:"CopyOrganizationTeamSettingsToTeam",I:n.ign,O:n.WSJ,kind:s.MethodKind.Unary},listOrganizationTeamSettingsCopySources:{name:"ListOrganizationTeamSettingsCopySources",I:n.YNI,O:n.yaP,kind:s.MethodKind.Unary},getOrganizationTeamAdminCandidates:{name:"GetOrganizationTeamAdminCandidates",I:n.rgp,O:n.xa_,kind:s.MethodKind.Unary},getDirectoryGroups:{name:"GetDirectoryGroups",I:n.LYo,O:n.PJy,kind:s.MethodKind.Unary},updateDirectoryGroupSettings:{name:"UpdateDirectoryGroupSettings",I:n.kFu,O:n.Mpk,kind:s.MethodKind.Unary},getOrganizationGroups:{name:"GetOrganizationGroups",I:n.f5k,O:n.ZJV,kind:s.MethodKind.Unary},getOrganizationGroup:{name:"GetOrganizationGroup",I:n.wH4,O:n.uwp,kind:s.MethodKind.Unary},getOrganizationGroupMembers:{name:"GetOrganizationGroupMembers",I:n.nQH,O:n.rd8,kind:s.MethodKind.Unary},createOrganizationGroup:{name:"CreateOrganizationGroup",I:n.ed4,O:n.urU,kind:s.MethodKind.Unary},updateOrganizationGroup:{name:"UpdateOrganizationGroup",I:n.Bhj,O:n.LBR,kind:s.MethodKind.Unary},deleteOrganizationGroup:{name:"DeleteOrganizationGroup",I:n.pe4,O:n.Huq,kind:s.MethodKind.Unary},addOrganizationGroupMembers:{name:"AddOrganizationGroupMembers",I:n.U8V,O:n.mf3,kind:s.MethodKind.Unary},removeOrganizationGroupMembers:{name:"RemoveOrganizationGroupMembers",I:n.xQP,O:n.TGX,kind:s.MethodKind.Unary},updateOrganizationGroupMember:{name:"UpdateOrganizationGroupMember",I:n.rj1,O:n.jWT,kind:s.MethodKind.Unary},getOrganizationGroupServiceAccountMembers:{name:"GetOrganizationGroupServiceAccountMembers",I:n.bPz,O:n.H0j,kind:s.MethodKind.Unary},getOrganizationServiceAccounts:{name:"GetOrganizationServiceAccounts",I:n.Exr,O:n.aYg,kind:s.MethodKind.Unary},addOrganizationGroupServiceAccounts:{name:"AddOrganizationGroupServiceAccounts",I:n.ggo,O:n.aHm,kind:s.MethodKind.Unary},removeOrganizationGroupServiceAccounts:{name:"RemoveOrganizationGroupServiceAccounts",I:n.dSX,O:n.nS1,kind:s.MethodKind.Unary},getOrganizationGroupAutorunSettings:{name:"GetOrganizationGroupAutorunSettings",I:n.ZKL,O:n.f43,kind:s.MethodKind.Unary},updateOrganizationGroupAutorunSettings:{name:"UpdateOrganizationGroupAutorunSettings",I:n.Cwp,O:n._i8,kind:s.MethodKind.Unary},getOrganizationGroupMcpSettings:{name:"GetOrganizationGroupMcpSettings",I:Us,O:$s,kind:s.MethodKind.Unary},updateOrganizationGroupMcpSettings:{name:"UpdateOrganizationGroupMcpSettings",I:Ms,O:Os,kind:s.MethodKind.Unary},exportOrganizationGroupMcpAllowlist:{name:"ExportOrganizationGroupMcpAllowlist",I:Ds,O:Ns,kind:s.MethodKind.Unary},importOrganizationGroupMcpAllowlist:{name:"ImportOrganizationGroupMcpAllowlist",I:Hs,O:Ws,kind:s.MethodKind.Unary},exportTeamMcpAllowlist:{name:"ExportTeamMcpAllowlist",I:Gs,O:Ls,kind:s.MethodKind.Unary},importTeamMcpAllowlist:{name:"ImportTeamMcpAllowlist",I:Qs,O:Vs,kind:s.MethodKind.Unary},getTeamCloudAgentMcpAllowlist:{name:"GetTeamCloudAgentMcpAllowlist",I:Xs,O:Ys,kind:s.MethodKind.Unary},updateTeamCloudAgentMcpAllowlist:{name:"UpdateTeamCloudAgentMcpAllowlist",I:Zs,O:ti,kind:s.MethodKind.Unary},listMcpAllowlistRuleMatches:{name:"ListMcpAllowlistRuleMatches",I:ei,O:ai,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},resetOrganizationGroupAgentRunModeToAutoReview:{name:"ResetOrganizationGroupAgentRunModeToAutoReview",I:n.ePV,O:n.EuD,kind:s.MethodKind.Unary},getOrganizationGroupModelAllowlist:{name:"GetOrganizationGroupModelAllowlist",I:n.M89,O:n.qlA,kind:s.MethodKind.Unary},updateOrganizationGroupModelAllowlist:{name:"UpdateOrganizationGroupModelAllowlist",I:n.$bH,O:n.nCl,kind:s.MethodKind.Unary},getOrganizationGroupAutoReviewSettings:{name:"GetOrganizationGroupAutoReviewSettings",I:n.QOh,O:n.qbQ,kind:s.MethodKind.Unary},updateOrganizationGroupAutoReviewSettings:{name:"UpdateOrganizationGroupAutoReviewSettings",I:n.DtR,O:n.dDc,kind:s.MethodKind.Unary},getOrganizationGroupSmartAutoSettings:{name:"GetOrganizationGroupSmartAutoSettings",I:n.H8G,O:n.rt0,kind:s.MethodKind.Unary},updateOrganizationGroupSmartAutoSettings:{name:"UpdateOrganizationGroupSmartAutoSettings",I:n.Yir,O:n.GDG,kind:s.MethodKind.Unary},createOrganizationGroupAnthropicCyberEnrollmentUrl:{name:"CreateOrganizationGroupAnthropicCyberEnrollmentUrl",I:n.C1F,O:n.wqi,kind:s.MethodKind.Unary},requestOrganizationGroupAnthropicEfs:{name:"RequestOrganizationGroupAnthropicEfs",I:n.rF_,O:n.DmQ,kind:s.MethodKind.Unary},requestOrganizationAnthropicEfs:{name:"RequestOrganizationAnthropicEfs",I:n.Y6P,O:n.QeE,kind:s.MethodKind.Unary},getOrganizationAnthropicEfsStatus:{name:"GetOrganizationAnthropicEfsStatus",I:n.BHf,O:n.lqZ,kind:s.MethodKind.Unary},reviewAnthropicEfsRequestInternal:{name:"ReviewAnthropicEfsRequestInternal",I:n.ovZ,O:n.gdR,kind:s.MethodKind.Unary},getTeamGroups:{name:"GetTeamGroups",I:n.JbB,O:n.nrv,kind:s.MethodKind.Unary},getTeamGroup:{name:"GetTeamGroup",I:n.UQh,O:n.cUB,kind:s.MethodKind.Unary},getTeamGroupMembers:{name:"GetTeamGroupMembers",I:n.J67,O:n.VBR,kind:s.MethodKind.Unary},getTeamGroupServiceAccountMembers:{name:"GetTeamGroupServiceAccountMembers",I:n.DWT,O:n.hSD,kind:s.MethodKind.Unary},createTeamGroup:{name:"CreateTeamGroup",I:n.cbD,O:n.CiW,kind:s.MethodKind.Unary},updateTeamGroup:{name:"UpdateTeamGroup",I:n.NS0,O:n.JL8,kind:s.MethodKind.Unary},deleteTeamGroup:{name:"DeleteTeamGroup",I:n.p9b,O:n.VyS,kind:s.MethodKind.Unary},addTeamGroupMembers:{name:"AddTeamGroupMembers",I:n.yqO,O:n.Gc8,kind:s.MethodKind.Unary},removeTeamGroupMembers:{name:"RemoveTeamGroupMembers",I:n.rA4,O:n.lER,kind:s.MethodKind.Unary},addTeamGroupServiceAccounts:{name:"AddTeamGroupServiceAccounts",I:n.Ipj,O:n.a0c,kind:s.MethodKind.Unary},removeTeamGroupServiceAccounts:{name:"RemoveTeamGroupServiceAccounts",I:n.X6C,O:n.$Fl,kind:s.MethodKind.Unary},updateTeamGroupMember:{name:"UpdateTeamGroupMember",I:n.jG,O:n.jFj,kind:s.MethodKind.Unary},getTeamGroupAutorunSettings:{name:"GetTeamGroupAutorunSettings",I:n.bK1,O:n.bJ,kind:s.MethodKind.Unary},updateTeamGroupAutorunSettings:{name:"UpdateTeamGroupAutorunSettings",I:n.KTu,O:n._$O,kind:s.MethodKind.Unary},getTeamGroupMcpSettings:{name:"GetTeamGroupMcpSettings",I:ui,O:_i,kind:s.MethodKind.Unary},updateTeamGroupMcpSettings:{name:"UpdateTeamGroupMcpSettings",I:Ji,O:wi,kind:s.MethodKind.Unary},getTeamMemberEffectiveMcpPolicy:{name:"GetTeamMemberEffectiveMcpPolicy",I:pi,O:hi,kind:s.MethodKind.Unary},listBuiltinMcpServerTools:{name:"ListBuiltinMcpServerTools",I:yi,O:Si,kind:s.MethodKind.Unary},exportTeamGroupMcpAllowlist:{name:"ExportTeamGroupMcpAllowlist",I:qi,O:Bi,kind:s.MethodKind.Unary},importTeamGroupMcpAllowlist:{name:"ImportTeamGroupMcpAllowlist",I:Ii,O:Pi,kind:s.MethodKind.Unary},resetTeamGroupAgentRunModeToAutoReview:{name:"ResetTeamGroupAgentRunModeToAutoReview",I:n.I3c,O:n.Qnc,kind:s.MethodKind.Unary},getTeamGroupModelAllowlist:{name:"GetTeamGroupModelAllowlist",I:n.s$M,O:n.MJ,kind:s.MethodKind.Unary},updateTeamGroupModelAllowlist:{name:"UpdateTeamGroupModelAllowlist",I:n.pbs,O:n.PD$,kind:s.MethodKind.Unary},getTeamGroupAutoReviewSettings:{name:"GetTeamGroupAutoReviewSettings",I:n.Mx4,O:n.gDX,kind:s.MethodKind.Unary},updateTeamGroupAutoReviewSettings:{name:"UpdateTeamGroupAutoReviewSettings",I:n.dXc,O:n.zF8,kind:s.MethodKind.Unary},getTeamSandNetworkSettings:{name:"GetTeamSandNetworkSettings",I:gu,O:_u,kind:s.MethodKind.Unary},getTeamGrokBotTrial:{name:"GetTeamGrokBotTrial",I:Pu,O:bu,kind:s.MethodKind.Unary},listTeamGrokBotAgentsAdmin:{name:"ListTeamGrokBotAgentsAdmin",I:Eu,O:Uu,kind:s.MethodKind.Unary},getTeamGrokBotRoiPreview:{name:"GetTeamGrokBotRoiPreview",I:Au,O:Ou,kind:s.MethodKind.Unary},getTeamGrokBotRoiBot:{name:"GetTeamGrokBotRoiBot",I:Du,O:zu,kind:s.MethodKind.Unary},updateTeamSandNetworkSettings:{name:"UpdateTeamSandNetworkSettings",I:ju,O:Hu,kind:s.MethodKind.Unary},getTeamSandTrustedCaCertificates:{name:"GetTeamSandTrustedCaCertificates",I:Wu,O:Qu,kind:s.MethodKind.Unary},updateTeamSandTrustedCaCertificates:{name:"UpdateTeamSandTrustedCaCertificates",I:Vu,O:Xu,kind:s.MethodKind.Unary},getTeamSandLocalEgressPrivateDestinations:{name:"GetTeamSandLocalEgressPrivateDestinations",I:Zu,O:tc,kind:s.MethodKind.Unary},updateTeamSandLocalEgressPrivateDestinations:{name:"UpdateTeamSandLocalEgressPrivateDestinations",I:rc,O:ec,kind:s.MethodKind.Unary},getTeamIngressIpAllowlist:{name:"GetTeamIngressIpAllowlist",I:n.Y44,O:n.kE_,kind:s.MethodKind.Unary},updateTeamIngressIpAllowlist:{name:"UpdateTeamIngressIpAllowlist",I:n.vq0,O:n.npe,kind:s.MethodKind.Unary},getOrganizationIngressIpAllowlist:{name:"GetOrganizationIngressIpAllowlist",I:n.UvC,O:n.SkP,kind:s.MethodKind.Unary},updateOrganizationIngressIpAllowlist:{name:"UpdateOrganizationIngressIpAllowlist",I:n.vvr,O:n.J3N,kind:s.MethodKind.Unary},getOrganizationNetworkBlocklist:{name:"GetOrganizationNetworkBlocklist",I:n.YtZ,O:n.UZr,kind:s.MethodKind.Unary},createOrganizationNetworkBlocklistUpload:{name:"CreateOrganizationNetworkBlocklistUpload",I:n.JoU,O:n.vU,kind:s.MethodKind.Unary},commitOrganizationNetworkBlocklistUpload:{name:"CommitOrganizationNetworkBlocklistUpload",I:n.KBr,O:n.EAu,kind:s.MethodKind.Unary},createOrganizationNetworkBlocklistExport:{name:"CreateOrganizationNetworkBlocklistExport",I:n.Cqw,O:n.mk5,kind:s.MethodKind.Unary},setOrganizationNetworkBlocklistEnabled:{name:"SetOrganizationNetworkBlocklistEnabled",I:n.$VK,O:n.tfN,kind:s.MethodKind.Unary},getTeamSandEgressHttpRules:{name:"GetTeamSandEgressHttpRules",I:Su,O:qu,kind:s.MethodKind.Unary},updateTeamSandEgressHttpRules:{name:"UpdateTeamSandEgressHttpRules",I:Bu,O:Iu,kind:s.MethodKind.Unary},getTeamTailnet:{name:"GetTeamTailnet",I:Td,O:Ud,kind:s.MethodKind.Unary},updateTeamTailnet:{name:"UpdateTeamTailnet",I:Fd,O:Kd,kind:s.MethodKind.Unary},updateTeamTailnetCompanyCa:{name:"UpdateTeamTailnetCompanyCa",I:zd,O:jd,kind:s.MethodKind.Unary},updateTeamTailnetBoxAccess:{name:"UpdateTeamTailnetBoxAccess",I:Hd,O:Wd,kind:s.MethodKind.Unary},updateTeamTailnetExitNode:{name:"UpdateTeamTailnetExitNode",I:Qd,O:Vd,kind:s.MethodKind.Unary},discoverTeamTailnetSuffix:{name:"DiscoverTeamTailnetSuffix",I:Xd,O:Yd,kind:s.MethodKind.Unary},setActiveTailnet:{name:"SetActiveTailnet",I:Dd,O:Nd,kind:s.MethodKind.Unary},getTeamGroupSandNetworkSettings:{name:"GetTeamGroupSandNetworkSettings",I:nc,O:sc,kind:s.MethodKind.Unary},updateTeamGroupSandNetworkSettings:{name:"UpdateTeamGroupSandNetworkSettings",I:ic,O:oc,kind:s.MethodKind.Unary},getTeamGroupGrokBotCapabilities:{name:"GetTeamGroupGrokBotCapabilities",I:cc,O:lc,kind:s.MethodKind.Unary},updateTeamGroupGrokBotCapabilities:{name:"UpdateTeamGroupGrokBotCapabilities",I:mc,O:fc,kind:s.MethodKind.Unary},getTeamGroupSmartAutoSettings:{name:"GetTeamGroupSmartAutoSettings",I:n.hu7,O:n.BPt,kind:s.MethodKind.Unary},updateTeamGroupSmartAutoSettings:{name:"UpdateTeamGroupSmartAutoSettings",I:n.Gor,O:n.WWO,kind:s.MethodKind.Unary},createTeamGroupAnthropicCyberEnrollmentUrl:{name:"CreateTeamGroupAnthropicCyberEnrollmentUrl",I:n.oJv,O:n.UPX,kind:s.MethodKind.Unary},requestTeamGroupAnthropicEfs:{name:"RequestTeamGroupAnthropicEfs",I:n.be7,O:n.THz,kind:s.MethodKind.Unary},getTeamAnthropicEfsStatus:{name:"GetTeamAnthropicEfsStatus",I:n.TdK,O:n.v6H,kind:s.MethodKind.Unary},listTeamGroupScimDirectories:{name:"ListTeamGroupScimDirectories",I:n.DEE,O:n.xUt,kind:s.MethodKind.Unary},listTeamGroupScimGroupsFromUpstream:{name:"ListTeamGroupScimGroupsFromUpstream",I:n.nsd,O:n.xYI,kind:s.MethodKind.Unary},listTeamGroupScimTargetMappings:{name:"ListTeamGroupScimTargetMappings",I:n.QE,O:n.gsU,kind:s.MethodKind.Unary},createTeamGroupScimTargetMapping:{name:"CreateTeamGroupScimTargetMapping",I:n.lW,O:n.$a1,kind:s.MethodKind.Unary},deleteTeamGroupScimTargetMapping:{name:"DeleteTeamGroupScimTargetMapping",I:n.mA,O:n.U1k,kind:s.MethodKind.Unary},getGroups:{name:"GetGroups",I:n.CY$,O:n.WsC,kind:s.MethodKind.Unary},getGroupMembers:{name:"GetGroupMembers",I:n.i$e,O:n.StO,kind:s.MethodKind.Unary},createGroup:{name:"CreateGroup",I:n.p8r,O:n.Dsz,kind:s.MethodKind.Unary},updateGroup:{name:"UpdateGroup",I:n.Eh9,O:n.wrT,kind:s.MethodKind.Unary},deleteGroup:{name:"DeleteGroup",I:n.SBx,O:n.uDb,kind:s.MethodKind.Unary},addGroupMembers:{name:"AddGroupMembers",I:n.Hcr,O:n.he9,kind:s.MethodKind.Unary},removeGroupMembers:{name:"RemoveGroupMembers",I:n.im6,O:n.SSe,kind:s.MethodKind.Unary},bulkAssignGroupMembers:{name:"BulkAssignGroupMembers",I:n.t3S,O:n.PXK,kind:s.MethodKind.Unary},previewAttachGroupToDirectory:{name:"PreviewAttachGroupToDirectory",I:n.OeX,O:n.Wow,kind:s.MethodKind.Unary},detachGroupFromDirectory:{name:"DetachGroupFromDirectory",I:n.tm2,O:n.prK,kind:s.MethodKind.Unary},getScimConflicts:{name:"GetScimConflicts",I:n.l9M,O:n.nPZ,kind:s.MethodKind.Unary},listScimDirectories:{name:"ListScimDirectories",I:n.Dxu,O:n.LM8,kind:s.MethodKind.Unary},getOrganizationScimConfigurationLinks:{name:"GetOrganizationScimConfigurationLinks",I:n.Dxu,O:n.C61,kind:s.MethodKind.Unary},createScimDirectory:{name:"CreateScimDirectory",I:n.BwS,O:n.dnd,kind:s.MethodKind.Unary},updateScimDirectorySyncSettings:{name:"UpdateScimDirectorySyncSettings",I:n.Spq,O:n.YCH,kind:s.MethodKind.Unary},deleteScimDirectory:{name:"DeleteScimDirectory",I:n.gwk,O:n.CN_,kind:s.MethodKind.Unary},listScimGroupsFromUpstream:{name:"ListScimGroupsFromUpstream",I:n.lmw,O:n.na4,kind:s.MethodKind.Unary},listScimTargetMappings:{name:"ListScimTargetMappings",I:n.OWn,O:n.c3u,kind:s.MethodKind.Unary},listOrganizationGroupTargetMappings:{name:"ListOrganizationGroupTargetMappings",I:n.UTl,O:n.i4X,kind:s.MethodKind.Unary},createScimTargetMapping:{name:"CreateScimTargetMapping",I:n.PwZ,O:n.vFW,kind:s.MethodKind.Unary},deleteScimTargetMapping:{name:"DeleteScimTargetMapping",I:n.gFI,O:n.c7s,kind:s.MethodKind.Unary},getActivationCheckoutUrl:{name:"GetActivationCheckoutUrl",I:n.hWx,O:n.dr7,kind:s.MethodKind.Unary},checkPromotionEligibility:{name:"CheckPromotionEligibility",I:n.yD0,O:n.MEI,kind:s.MethodKind.Unary},activatePromotion:{name:"ActivatePromotion",I:n.uHx,O:n.yDS,kind:s.MethodKind.Unary},getTeamCustomerPortalUrl:{name:"GetTeamCustomerPortalUrl",I:n.qjo,O:n.M_,kind:s.MethodKind.Unary},cancelPendingTeamSubscriptionNow:{name:"CancelPendingTeamSubscriptionNow",I:n.v_r,O:n.$n,kind:s.MethodKind.Unary},createPendingTeamProCheckout:{name:"CreatePendingTeamProCheckout",I:n.PTe,O:n.pF3,kind:s.MethodKind.Unary},getTeamPrepaidBilling:{name:"GetTeamPrepaidBilling",I:n.FcH,O:n.$qn,kind:s.MethodKind.Unary},setTeamPrepaidAutoTopUp:{name:"SetTeamPrepaidAutoTopUp",I:n.$ty,O:n.VN6,kind:s.MethodKind.Unary},createPrepaidTopUp:{name:"CreatePrepaidTopUp",I:n.XAW,O:n.bTQ,kind:s.MethodKind.Unary},getUserPrepaidBilling:{name:"GetUserPrepaidBilling",I:n.b4u,O:n.$H_,kind:s.MethodKind.Unary},setUserPrepaidAutoTopUp:{name:"SetUserPrepaidAutoTopUp",I:n.h3x,O:n.D9s,kind:s.MethodKind.Unary},createUserPrepaidTopUp:{name:"CreateUserPrepaidTopUp",I:n.uDD,O:n.EO4,kind:s.MethodKind.Unary},getTeamMembers:{name:"GetTeamMembers",I:n.Imd,O:n.QI7,kind:s.MethodKind.Unary},sendTeamInvite:{name:"SendTeamInvite",I:n.cn,O:n.YBJ,kind:s.MethodKind.Unary},sendTeamInvites:{name:"SendTeamInvites",I:n.Naf,O:n.pF$,kind:s.MethodKind.Unary},getTeamInviteLink:{name:"GetTeamInviteLink",I:n.C4p,O:n.gRj,kind:s.MethodKind.Unary},acceptInvite:{name:"AcceptInvite",I:n.LRJ,O:n.bCe,kind:s.MethodKind.Unary},getTeamInviteMetadata:{name:"GetTeamInviteMetadata",I:n.h1G,O:n.doQ,kind:s.MethodKind.Unary},listContactImportConnections:{name:"ListContactImportConnections",I:n.Ezc,O:n.cDB,kind:s.MethodKind.Unary},getGoogleContactImportAuthUrl:{name:"GetGoogleContactImportAuthUrl",I:n.$7Y,O:n.LoC,kind:s.MethodKind.Unary},connectGoogleContactImportCallback:{name:"ConnectGoogleContactImportCallback",I:n.X38,O:n.tZA,kind:s.MethodKind.Unary},listContactImportContacts:{name:"ListContactImportContacts",I:n.gNW,O:n.SuV,kind:s.MethodKind.Unary},getContactImportAvatar:{name:"GetContactImportAvatar",I:n.mPq,O:n.i5j,kind:s.MethodKind.Unary},disconnectContactImportConnection:{name:"DisconnectContactImportConnection",I:n.jzf,O:n.zu1,kind:s.MethodKind.Unary},createTeam:{name:"CreateTeam",I:n.nxO,O:n.vgA,kind:s.MethodKind.Unary},getJoinableTeamsByDomain:{name:"GetJoinableTeamsByDomain",I:n.ND4,O:n.Rkv,kind:s.MethodKind.Unary},joinTeamByDomain:{name:"JoinTeamByDomain",I:n.E2N,O:n.iX6,kind:s.MethodKind.Unary},updateTeamDomainJoinSetting:{name:"UpdateTeamDomainJoinSetting",I:n.yog,O:n.K_o,kind:s.MethodKind.Unary},getTeamMemberDomains:{name:"GetTeamMemberDomains",I:n.Obu,O:n.S5H,kind:s.MethodKind.Unary},getTeamIdForReactivation:{name:"GetTeamIdForReactivation",I:n._CN,O:n.Kww,kind:s.MethodKind.Unary},changeSeat:{name:"ChangeSeat",I:n.HZm,O:n.lRG,kind:s.MethodKind.Unary},changeTeamSubscription:{name:"ChangeTeamSubscription",I:n.oOo,O:n.MIx,kind:s.MethodKind.Unary},connectGithubCallback:{name:"ConnectGithubCallback",I:n.SH9,O:n._$M,kind:s.MethodKind.Unary},registerGithubCursorCode:{name:"RegisterGithubCursorCode",I:n.H1p,O:n.DUo,kind:s.MethodKind.Unary},prepareGithubConnectFlow:{name:"PrepareGithubConnectFlow",I:n.uif,O:n.EJq,kind:s.MethodKind.Unary},completeGithubConnectFlow:{name:"CompleteGithubConnectFlow",I:n.OjU,O:n.Ohd,kind:s.MethodKind.Unary},disconnectGithub:{name:"DisconnectGithub",I:n.D57,O:n.llV,kind:s.MethodKind.Unary},prepareSetupGithubEnterpriseApp:{name:"PrepareSetupGithubEnterpriseApp",I:n.jPV,O:n.lP,kind:s.MethodKind.Unary},finishSetupGithubEnterpriseApp:{name:"FinishSetupGithubEnterpriseApp",I:n.jiB,O:n.Z48,kind:s.MethodKind.Unary},listGithubEnterpriseApps:{name:"ListGithubEnterpriseApps",I:n.k6E,O:n.a$2,kind:s.MethodKind.Unary},deleteGithubEnterpriseApp:{name:"DeleteGithubEnterpriseApp",I:n.mZ$,O:n.WBx,kind:s.MethodKind.Unary},setupGitlabEnterpriseInstance:{name:"SetupGitlabEnterpriseInstance",I:n.MS0,O:n.k09,kind:s.MethodKind.Unary},listGitlabEnterpriseInstances:{name:"ListGitlabEnterpriseInstances",I:n.gvC,O:n.WaG,kind:s.MethodKind.Unary},setGitlabEnterpriseHostControlledServiceAccountToken:{name:"SetGitlabEnterpriseHostControlledServiceAccountToken",I:n.Rns,O:n.PFp,kind:s.MethodKind.Unary},rotateGitlabEnterpriseWebhookSecret:{name:"RotateGitlabEnterpriseWebhookSecret",I:n.eor,O:n.oTi,kind:s.MethodKind.Unary},deleteGitlabEnterpriseInstance:{name:"DeleteGitlabEnterpriseInstance",I:n.iVu,O:n.wuD,kind:s.MethodKind.Unary},setupBitbucketServerInstance:{name:"SetupBitbucketServerInstance",I:n.w9j,O:n.c1o,kind:s.MethodKind.Unary},listBitbucketServerInstances:{name:"ListBitbucketServerInstances",I:n.Q3t,O:n.Oef,kind:s.MethodKind.Unary},updateBitbucketServerInstanceToken:{name:"UpdateBitbucketServerInstanceToken",I:n.fKS,O:n.tkR,kind:s.MethodKind.Unary},deleteBitbucketServerInstance:{name:"DeleteBitbucketServerInstance",I:n.opt,O:n.ABq,kind:s.MethodKind.Unary},syncGitlabRepos:{name:"SyncGitlabRepos",I:n.ZrD,O:n.ffl,kind:s.MethodKind.Unary},getGitlabReposSyncStatus:{name:"GetGitlabReposSyncStatus",I:n.jp5,O:n.dpH,kind:s.MethodKind.Unary},updateRole:{name:"UpdateRole",I:n.$ht,O:n.BrS,kind:s.MethodKind.Unary},removeMember:{name:"RemoveMember",I:n.mig,O:n.sX9,kind:s.MethodKind.Unary},retryTeamXaiMembershipHold:{name:"RetryTeamXaiMembershipHold",I:oe,O:ae,kind:s.MethodKind.Unary},getMemberRemovalInsights:{name:"GetMemberRemovalInsights",I:n.BF8,O:n.t__,kind:s.MethodKind.Unary},getSignUpType:{name:"GetSignUpType",I:n.u_Q,O:n.WsA,kind:s.MethodKind.Unary},getHardLimit:{name:"GetHardLimit",I:n.g6R,O:n.oyU,kind:s.MethodKind.Unary},setHardLimit:{name:"SetHardLimit",I:n.yL5,O:n.se9,kind:s.MethodKind.Unary},getSpendLimitPolicy:{name:"GetSpendLimitPolicy",I:n.zEV,O:n.pig,kind:s.MethodKind.Unary},setSpendLimitPolicy:{name:"SetSpendLimitPolicy",I:n.LMY,O:n.LLB,kind:s.MethodKind.Unary},getOrgTeamBudgets:{name:"GetOrgTeamBudgets",I:n.DXb,O:n.D42,kind:s.MethodKind.Unary},setOrgTeamBudget:{name:"SetOrgTeamBudget",I:n.yWy,O:n.as5,kind:s.MethodKind.Unary},getOrgDailySpendByCategory:{name:"GetOrgDailySpendByCategory",I:n.ubJ,O:n.GlZ,kind:s.MethodKind.Unary},enableOnDemandSpend:{name:"EnableOnDemandSpend",I:n.toG,O:n.V$m,kind:s.MethodKind.Unary},deleteAccount:{name:"DeleteAccount",I:n.gqj,O:n.wER,kind:s.MethodKind.Unary},getAccountSettings:{name:"GetAccountSettings",I:n.oNu,O:n.Hdf,kind:s.MethodKind.Unary},getAccountDeletionSummary:{name:"GetAccountDeletionSummary",I:n.RwL,O:n.MSh,kind:s.MethodKind.Unary},createAccountHandoff:{name:"CreateAccountHandoff",I:n.vaB,O:n.rzz,kind:s.MethodKind.Unary},startAccountCollapseRun:{name:"StartAccountCollapseRun",I:ht,O:gt,kind:s.MethodKind.Unary},getAccountCollapseRun:{name:"GetAccountCollapseRun",I:_t,O:Jt,kind:s.MethodKind.Unary},startAccountCollapseRunInternal:{name:"StartAccountCollapseRunInternal",I:ht,O:gt,kind:s.MethodKind.Unary},getAccountCollapseRunInternal:{name:"GetAccountCollapseRunInternal",I:_t,O:Jt,kind:s.MethodKind.Unary},startCursorAccountCollapse:{name:"StartCursorAccountCollapse",I:wt,O:yt,kind:s.MethodKind.Unary},getCursorAccountCollapseByTarget:{name:"GetCursorAccountCollapseByTarget",I:St,O:qt,kind:s.MethodKind.Unary},startCursorSessionAccountCollapse:{name:"StartCursorSessionAccountCollapse",I:Bt,O:yt,kind:s.MethodKind.Unary},getCursorSessionAccountCollapse:{name:"GetCursorSessionAccountCollapse",I:It,O:qt,kind:s.MethodKind.Unary},listCursorSessionAccountCollapseCandidates:{name:"ListCursorSessionAccountCollapseCandidates",I:Pt,O:At,kind:s.MethodKind.Unary},startCursorSessionAccountCollapseProof:{name:"StartCursorSessionAccountCollapseProof",I:bt,O:dr,kind:s.MethodKind.Unary},completeCursorSessionAccountCollapseProof:{name:"CompleteCursorSessionAccountCollapseProof",I:Rt,O:hr,kind:s.MethodKind.Unary},sendDownloadEmail:{name:"SendDownloadEmail",I:n.e5r,O:n.C3d,kind:s.MethodKind.Unary},getMonthlyInvoice:{name:"GetMonthlyInvoice",I:n.yO3,O:n.Si_,kind:s.MethodKind.Unary},listInvoiceCycles:{name:"ListInvoiceCycles",I:n.yMo,O:n.G8V,kind:s.MethodKind.Unary},getDailySpendByCategory:{name:"GetDailySpendByCategory",I:n.irI,O:n.GlZ,kind:s.MethodKind.Unary},getPricingHistory:{name:"GetPricingHistory",I:n.Akd,O:n.i7t,kind:s.MethodKind.Unary},listBackgroundComposerSecrets:{name:"ListBackgroundComposerSecrets",I:n.$F$,O:n.dnq,kind:s.MethodKind.Unary},createBackgroundComposerSecret:{name:"CreateBackgroundComposerSecret",I:n.sJl,O:n.ukh,kind:s.MethodKind.Unary},createBackgroundComposerSecretBatch:{name:"CreateBackgroundComposerSecretBatch",I:n.S3E,O:n.o6Z,kind:s.MethodKind.Unary},revokeBackgroundComposerSecret:{name:"RevokeBackgroundComposerSecret",I:n.AU3,O:n.keR,kind:s.MethodKind.Unary},updateBackgroundComposerSecret:{name:"UpdateBackgroundComposerSecret",I:n.zYv,O:n.FmW,kind:s.MethodKind.Unary},getMcpConfig:{name:"GetMcpConfig",I:bi,O:vi,kind:s.MethodKind.Unary},getEffectiveMcpConfigForUser:{name:"GetEffectiveMcpConfigForUser",I:xi,O:ki,kind:s.MethodKind.Unary},getAvailableMcpServers:{name:"GetAvailableMcpServers",I:Ei,O:Ci,kind:s.MethodKind.Unary},getMcpServerUsageSummary:{name:"GetMcpServerUsageSummary",I:Di,O:Gi,kind:s.MethodKind.Unary},setMcpConfig:{name:"SetMcpConfig",I:Li,O:Fi,kind:s.MethodKind.Unary},updateUserDefaultMcpSettings:{name:"UpdateUserDefaultMcpSettings",I:Yi,O:Zi,kind:s.MethodKind.Unary},setGrokConnectorEnabled:{name:"SetGrokConnectorEnabled",I:n.$ZN,O:n.NtP,kind:s.MethodKind.Unary},setUserMcpToolChoices:{name:"SetUserMcpToolChoices",I:eo,O:no,kind:s.MethodKind.Unary},markMcpServersSeen:{name:"MarkMcpServersSeen",I:io,O:oo,kind:s.MethodKind.Unary},storeMcpOAuthToken:{name:"StoreMcpOAuthToken",I:ao,O:uo,kind:s.MethodKind.Unary},getMcpOAuthTokens:{name:"GetMcpOAuthTokens",I:co,O:lo,kind:s.MethodKind.Unary},listSandMcpTools:{name:"ListSandMcpTools",I:dc,O:pc,kind:s.MethodKind.Unary},previewTeamMcpTools:{name:"PreviewTeamMcpTools",I:fo,O:po,kind:s.MethodKind.Unary},executeSandMcpTool:{name:"ExecuteSandMcpTool",I:gc,O:wc,kind:s.MethodKind.Unary},readSandMcpResource:{name:"ReadSandMcpResource",I:yc,O:Sc,kind:s.MethodKind.Unary},classifySandAutoReview:{name:"ClassifySandAutoReview",I:_c,O:Jc,kind:s.MethodKind.Unary},recordSandAuditEvents:{name:"RecordSandAuditEvents",I:$c,O:Mc,kind:s.MethodKind.Unary},mcpOAuthRefreshLockBegin:{name:"McpOAuthRefreshLockBegin",I:ho,O:go,kind:s.MethodKind.Unary},mcpOAuthRefreshLockRelease:{name:"McpOAuthRefreshLockRelease",I:_o,O:Jo,kind:s.MethodKind.Unary},deleteMcpOAuthToken:{name:"DeleteMcpOAuthToken",I:wo,O:yo,kind:s.MethodKind.Unary},validateMcpOAuthTokens:{name:"ValidateMcpOAuthTokens",I:qo,O:Io,kind:s.MethodKind.Unary},checkHttpMcpStatus:{name:"CheckHttpMcpStatus",I:xo,O:ko,kind:s.MethodKind.Unary},storeMcpOAuthPendingState:{name:"StoreMcpOAuthPendingState",I:To,O:Uo,kind:s.MethodKind.Unary},getMcpOAuthPendingState:{name:"GetMcpOAuthPendingState",I:Ao,O:$o,kind:s.MethodKind.Unary},renameMcpOAuthAccount:{name:"RenameMcpOAuthAccount",I:Go,O:Lo,kind:s.MethodKind.Unary},deleteMcpOAuthAccount:{name:"DeleteMcpOAuthAccount",I:Fo,O:Ko,kind:s.MethodKind.Unary},completeMcpOAuth:{name:"CompleteMcpOAuth",I:Mo,O:Oo,kind:s.MethodKind.Unary},handOffMcpOAuthCode:{name:"HandOffMcpOAuthCode",I:Do,O:No,kind:s.MethodKind.Unary},getPluginMcpConfig:{name:"GetPluginMcpConfig",I:zo,O:jo,kind:s.MethodKind.Unary},batchGetPluginMcpConfig:{name:"BatchGetPluginMcpConfig",I:Ho,O:Qo,kind:s.MethodKind.Unary},addMcpServersFromPlugin:{name:"AddMcpServersFromPlugin",I:Vo,O:Xo,kind:s.MethodKind.Unary},moveUserMcpServerToTeam:{name:"MoveUserMcpServerToTeam",I:Ki,O:zi,kind:s.MethodKind.Unary},getTeamMcpPlacementDefault:{name:"GetTeamMcpPlacementDefault",I:ji,O:Hi,kind:s.MethodKind.Unary},updateTeamMcpPlacementDefault:{name:"UpdateTeamMcpPlacementDefault",I:Wi,O:Qi,kind:s.MethodKind.Unary},migrateTeamMcpServersToDefaultMarketplace:{name:"MigrateTeamMcpServersToDefaultMarketplace",I:Vi,O:Xi,kind:s.MethodKind.Unary},probeMcpUrl:{name:"ProbeMcpUrl",I:Yo,O:Zo,kind:s.MethodKind.Unary},getMcpBackendAccessToken:{name:"GetMcpBackendAccessToken",I:ta,O:ra,kind:s.MethodKind.Unary},createTeamWithFreeTrial:{name:"CreateTeamWithFreeTrial",I:n.LAq,O:n.x2A,kind:s.MethodKind.Unary},createTeamWithOrg:{name:"CreateTeamWithOrg",I:n.BlC,O:n.Dd7,kind:s.MethodKind.Unary},getTeamHasValidPaymentMethod:{name:"GetTeamHasValidPaymentMethod",I:n.MrA,O:n.gJp,kind:s.MethodKind.Unary},getTeamPrivacyModeForced:{name:"GetTeamPrivacyModeForced",I:n.lKh,O:n.rsP,kind:s.MethodKind.Unary},getTeamXaiDataRetention:{name:"GetTeamXaiDataRetention",I:n.rcf,O:n.Jcx,kind:s.MethodKind.Unary},switchTeamPrivacyMode:{name:"SwitchTeamPrivacyMode",I:n.SmK,O:n.kjp,kind:s.MethodKind.Unary},updateFastRequests:{name:"UpdateFastRequests",I:n.rjZ,O:n.FFm,kind:s.MethodKind.Unary},getFastRequests:{name:"GetFastRequests",I:n.iSm,O:n.aUJ,kind:s.MethodKind.Unary},getDownloadLink:{name:"GetDownloadLink",I:n.Upy,O:n.AlS,kind:s.MethodKind.Unary},getCliDownloadUrl:{name:"GetCliDownloadUrl",I:n.Xhp,O:n.JRd,kind:s.MethodKind.Unary},getSsoConfigurationLinks:{name:"GetSsoConfigurationLinks",I:n._$o,O:n.Opj,kind:s.MethodKind.Unary},getScimConfigurationLinks:{name:"GetScimConfigurationLinks",I:n.n$I,O:n.fMg,kind:s.MethodKind.Unary},setAdminOnlyUsagePricing:{name:"SetAdminOnlyUsagePricing",I:n.SAF,O:n.Ix8,kind:s.MethodKind.Unary},getYearlyUpgradeEligibility:{name:"GetYearlyUpgradeEligibility",I:n.DLp,O:n.R$$,kind:s.MethodKind.Unary},upgradeToYearly:{name:"UpgradeToYearly",I:n.bBp,O:n.rk2,kind:s.MethodKind.Unary},getEnterpriseCTAEligibility:{name:"GetEnterpriseCTAEligibility",I:n.i6G,O:n.i0P,kind:s.MethodKind.Unary},getUsageBasedPremiumRequests:{name:"GetUsageBasedPremiumRequests",I:n.nDb,O:n.n8L,kind:s.MethodKind.Unary},setUsageBasedPremiumRequests:{name:"SetUsageBasedPremiumRequests",I:n.ZU_,O:n.X8H,kind:s.MethodKind.Unary},getReferrals:{name:"GetReferrals",I:n.Gch,O:n.gBX,kind:s.MethodKind.Unary},getReferralCodes:{name:"GetReferralCodes",I:n.bT6,O:n.D2n,kind:s.MethodKind.Unary},createP2PReferralLink:{name:"CreateP2PReferralLink",I:n.bhY,O:n.XEQ,kind:s.MethodKind.Unary},getP2PReferralStatus:{name:"GetP2PReferralStatus",I:n.pGh,O:n.XWY,kind:s.MethodKind.Unary},sendP2PReferralInvites:{name:"SendP2PReferralInvites",I:n.ZKX,O:n.tZb,kind:s.MethodKind.Unary},getP2PReferralHistory:{name:"GetP2PReferralHistory",I:n.EcQ,O:n.nd7,kind:s.MethodKind.Unary},checkReferralAllowlist:{name:"CheckReferralAllowlist",I:n.ukN,O:n.cRU,kind:s.MethodKind.Unary},checkReferralCode:{name:"CheckReferralCode",I:n.MRM,O:n.wb2,kind:s.MethodKind.Unary},redeemGiftCode:{name:"RedeemGiftCode",I:n.ziV,O:n.lme,kind:s.MethodKind.Unary},getGiftCodeInfo:{name:"GetGiftCodeInfo",I:n.Nmm,O:n.Xa_,kind:s.MethodKind.Unary},getEventCodeInfo:{name:"GetEventCodeInfo",I:n.RiQ,O:n.XUY,kind:s.MethodKind.Unary},redeemEventCode:{name:"RedeemEventCode",I:n.VF8,O:n.Djf,kind:s.MethodKind.Unary},getTeamRepos:{name:"GetTeamRepos",I:n.aYW,O:n.k1F,kind:s.MethodKind.Unary},getTeamReposOrEmptyIfNotInTeam:{name:"GetTeamReposOrEmptyIfNotInTeam",I:n.aYW,O:n.k1F,kind:s.MethodKind.Unary},getTeamRules:{name:"GetTeamRules",I:n.yds,O:n.KZ$,kind:s.MethodKind.Unary},createTeamRule:{name:"CreateTeamRule",I:n.J7F,O:n.vZv,kind:s.MethodKind.Unary},updateTeamRule:{name:"UpdateTeamRule",I:n.qEG,O:n.CMB,kind:s.MethodKind.Unary},deleteTeamRule:{name:"DeleteTeamRule",I:n.Ch8,O:n.uzD,kind:s.MethodKind.Unary},getTeamGroupRules:{name:"GetTeamGroupRules",I:n.vdM,O:n.Xu9,kind:s.MethodKind.Unary},createTeamGroupRule:{name:"CreateTeamGroupRule",I:n.WxI,O:n.AkX,kind:s.MethodKind.Unary},updateTeamGroupRule:{name:"UpdateTeamGroupRule",I:n.dpZ,O:n.Lxb,kind:s.MethodKind.Unary},deleteTeamGroupRule:{name:"DeleteTeamGroupRule",I:n.lIO,O:n.jqE,kind:s.MethodKind.Unary},getTeamHooks:{name:"GetTeamHooks",I:n.$kg,O:n.PtB,kind:s.MethodKind.Unary},createTeamHook:{name:"CreateTeamHook",I:n.wT7,O:n.a4I,kind:s.MethodKind.Unary},updateTeamHook:{name:"UpdateTeamHook",I:n.TeW,O:n.$lk,kind:s.MethodKind.Unary},deleteTeamHook:{name:"DeleteTeamHook",I:n.x4u,O:n.FNs,kind:s.MethodKind.Unary},getTeamCommands:{name:"GetTeamCommands",I:n.XDt,O:n.lzR,kind:s.MethodKind.Unary},createTeamCommand:{name:"CreateTeamCommand",I:n.Ctq,O:n.CXw,kind:s.MethodKind.Unary},updateTeamCommand:{name:"UpdateTeamCommand",I:n.XQ_,O:n.DZr,kind:s.MethodKind.Unary},deleteTeamCommand:{name:"DeleteTeamCommand",I:n.xo6,O:n.atP,kind:s.MethodKind.Unary},getGlobalCommands:{name:"GetGlobalCommands",I:n.YSR,O:n.rL_,kind:s.MethodKind.Unary},getRepoSlashCommands:{name:"GetRepoSlashCommands",I:n.LM4,O:n.hcQ,kind:s.MethodKind.Unary},getBackgroundComposerSlashCommands:{name:"GetBackgroundComposerSlashCommands",I:n.T1q,O:n.RNi,kind:s.MethodKind.Unary},getCloudAgentPluginsSnapshot:{name:"GetCloudAgentPluginsSnapshot",I:n.G24,O:n.gNl,kind:s.MethodKind.Unary},getBugbotTeamRules:{name:"GetBugbotTeamRules",I:n.N8K,O:n.RP_,kind:s.MethodKind.Unary},createBugbotTeamRule:{name:"CreateBugbotTeamRule",I:n.CHh,O:n.GL9,kind:s.MethodKind.Unary},updateBugbotTeamRule:{name:"UpdateBugbotTeamRule",I:n.rtb,O:n.v0c,kind:s.MethodKind.Unary},deleteBugbotTeamRule:{name:"DeleteBugbotTeamRule",I:n.pj7,O:n.rP9,kind:s.MethodKind.Unary},getBugbotLearnedRules:{name:"GetBugbotLearnedRules",I:n.hp9,O:n.z7W,kind:s.MethodKind.Unary},updateBugbotLearnedRule:{name:"UpdateBugbotLearnedRule",I:n.BIT,O:n.Xmf,kind:s.MethodKind.Unary},deleteBugbotLearnedRule:{name:"DeleteBugbotLearnedRule",I:n.hnR,O:n.Ld4,kind:s.MethodKind.Unary},createBugbotManualRepositoryRule:{name:"CreateBugbotManualRepositoryRule",I:n.Bdx,O:n.Zk6,kind:s.MethodKind.Unary},getBugbotManualRepositoryRules:{name:"GetBugbotManualRepositoryRules",I:n.qF$,O:n.azW,kind:s.MethodKind.Unary},updateBugbotManualRepositoryRule:{name:"UpdateBugbotManualRepositoryRule",I:n.UBx,O:n.ead,kind:s.MethodKind.Unary},deleteBugbotManualRepositoryRule:{name:"DeleteBugbotManualRepositoryRule",I:n.ONG,O:n.YYN,kind:s.MethodKind.Unary},runDiamondToBugbotMigration:{name:"RunDiamondToBugbotMigration",I:n.rb7,O:n.DkK,kind:s.MethodKind.Unary},getBugbotRuleAnalytics:{name:"GetBugbotRuleAnalytics",I:n.lvI,O:n.RK5,kind:s.MethodKind.Unary},getBugbotRuleById:{name:"GetBugbotRuleById",I:n.TOm,O:n.tkD,kind:s.MethodKind.Unary},createTeamRepo:{name:"CreateTeamRepo",I:n.J4c,O:n.fCO,kind:s.MethodKind.Unary},deleteTeamRepo:{name:"DeleteTeamRepo",I:n.m0x,O:n.Cw0,kind:s.MethodKind.Unary},addRepoPattern:{name:"AddRepoPattern",I:n.pji,O:n.D3c,kind:s.MethodKind.Unary},removeRepoPattern:{name:"RemoveRepoPattern",I:n.MEU,O:n.U0s,kind:s.MethodKind.Unary},setTeamRepoType:{name:"SetTeamRepoType",I:n.HeY,O:n.V_5,kind:s.MethodKind.Unary},getTeamAdminSettings:{name:"GetTeamAdminSettings",I:n.Byz,O:n.V5U,kind:s.MethodKind.Unary},getTeamAdminSettingsOrEmptyIfNotInTeam:{name:"GetTeamAdminSettingsOrEmptyIfNotInTeam",I:n.Byz,O:n.V5U,kind:s.MethodKind.Unary},getBaseTeamAdminSettings:{name:"GetBaseTeamAdminSettings",I:n.Qrr,O:n.V5U,kind:s.MethodKind.Unary},getTeamOriginDisabled:{name:"GetTeamOriginDisabled",I:n.NES,O:n.Fj9,kind:s.MethodKind.Unary},listUnlistedMemberServers:{name:"ListUnlistedMemberServers",I:n.esR,O:n.eiD,kind:s.MethodKind.Unary},updateTeamAdminSettings:{name:"UpdateTeamAdminSettings",I:n.sCz,O:n.aP5,kind:s.MethodKind.Unary},getCloudAgentStartupScript:{name:"GetCloudAgentStartupScript",I:n.ISZ,O:n.yTE,kind:s.MethodKind.Unary},updateCloudAgentStartupScript:{name:"UpdateCloudAgentStartupScript",I:n.PvX,O:n.JPA,kind:s.MethodKind.Unary},getTeamCustomerTelemetryDestinations:{name:"GetTeamCustomerTelemetryDestinations",I:n.n$w,O:n.R9K,kind:s.MethodKind.Unary},createTeamCustomerTelemetryDestination:{name:"CreateTeamCustomerTelemetryDestination",I:n.qxp,O:n.uts,kind:s.MethodKind.Unary},updateTeamCustomerTelemetryDestination:{name:"UpdateTeamCustomerTelemetryDestination",I:n.LJ3,O:n.Hen,kind:s.MethodKind.Unary},deleteTeamCustomerTelemetryDestination:{name:"DeleteTeamCustomerTelemetryDestination",I:n.t1u,O:n.rFi,kind:s.MethodKind.Unary},testTeamCustomerTelemetryDestinationConnection:{name:"TestTeamCustomerTelemetryDestinationConnection",I:n.ybE,O:n.YiF,kind:s.MethodKind.Unary},getTeamCustomerTelemetryDestinationHealth:{name:"GetTeamCustomerTelemetryDestinationHealth",I:n.mD_,O:n.wGo,kind:s.MethodKind.Unary},getTeamCustomerTelemetryContentExportOptIn:{name:"GetTeamCustomerTelemetryContentExportOptIn",I:n.LWe,O:n.F8Y,kind:s.MethodKind.Unary},updateTeamCustomerTelemetryContentExportOptIn:{name:"UpdateTeamCustomerTelemetryContentExportOptIn",I:n.UvX,O:n.G8P,kind:s.MethodKind.Unary},getTeamInferenceHookConfig:{name:"GetTeamInferenceHookConfig",I:n.TB_,O:n.nE8,kind:s.MethodKind.Unary},updateTeamInferenceHookConfig:{name:"UpdateTeamInferenceHookConfig",I:n.qJd,O:n.IIB,kind:s.MethodKind.Unary},rotateTeamInferenceHookSigningSecret:{name:"RotateTeamInferenceHookSigningSecret",I:n.B8P,O:n.HQR,kind:s.MethodKind.Unary},getTeamInferenceHookHealth:{name:"GetTeamInferenceHookHealth",I:n.lax,O:n.rM7,kind:s.MethodKind.Unary},resetTeamInferenceHookBreaker:{name:"ResetTeamInferenceHookBreaker",I:n._dj,O:n.Mob,kind:s.MethodKind.Unary},getTeamGrokBotIdpConnection:{name:"GetTeamGrokBotIdpConnection",I:Af,O:$f,kind:s.MethodKind.Unary},updateTeamGrokBotIdpConnection:{name:"UpdateTeamGrokBotIdpConnection",I:Mf,O:Of,kind:s.MethodKind.Unary},deleteTeamGrokBotIdpConnection:{name:"DeleteTeamGrokBotIdpConnection",I:Df,O:Nf,kind:s.MethodKind.Unary},getTeamGrokBotScimDirectory:{name:"GetTeamGrokBotScimDirectory",I:Ff,O:Kf,kind:s.MethodKind.Unary},enableTeamGrokBotScimDirectory:{name:"EnableTeamGrokBotScimDirectory",I:zf,O:jf,kind:s.MethodKind.Unary},disableTeamGrokBotScimDirectory:{name:"DisableTeamGrokBotScimDirectory",I:Hf,O:Wf,kind:s.MethodKind.Unary},createTeamGrokBotScimToken:{name:"CreateTeamGrokBotScimToken",I:Qf,O:Vf,kind:s.MethodKind.Unary},revokeTeamGrokBotScimToken:{name:"RevokeTeamGrokBotScimToken",I:Xf,O:Yf,kind:s.MethodKind.Unary},updateTeamGrokBotScimIpAllowlist:{name:"UpdateTeamGrokBotScimIpAllowlist",I:Zf,O:td,kind:s.MethodKind.Unary},listTeamGrokBotScimBots:{name:"ListTeamGrokBotScimBots",I:ed,O:nd,kind:s.MethodKind.Unary},deleteTeamGrokBotScimBot:{name:"DeleteTeamGrokBotScimBot",I:sd,O:id,kind:s.MethodKind.Unary},getTeamGrokBotScimIdpIdentity:{name:"GetTeamGrokBotScimIdpIdentity",I:cd,O:ld,kind:s.MethodKind.Unary},updateTeamGrokBotScimIdpIdentity:{name:"UpdateTeamGrokBotScimIdpIdentity",I:md,O:fd,kind:s.MethodKind.Unary},generateTeamGrokBotScimIdpSigningKey:{name:"GenerateTeamGrokBotScimIdpSigningKey",I:dd,O:pd,kind:s.MethodKind.Unary},deleteTeamGrokBotScimIdpIdentity:{name:"DeleteTeamGrokBotScimIdpIdentity",I:hd,O:gd,kind:s.MethodKind.Unary},getTeamLlmGatewayCredentialStatus:{name:"GetTeamLlmGatewayCredentialStatus",I:n.v8R,O:n.dsv,kind:s.MethodKind.Unary},setTeamLlmGatewayCredential:{name:"SetTeamLlmGatewayCredential",I:n.JQv,O:n.LQe,kind:s.MethodKind.Unary},replaceTeamLlmGatewayCredential:{name:"ReplaceTeamLlmGatewayCredential",I:n.Bwq,O:n.nUL,kind:s.MethodKind.Unary},clearTeamLlmGatewayCredential:{name:"ClearTeamLlmGatewayCredential",I:n.uBx,O:n._rf,kind:s.MethodKind.Unary},updateTeamLlmGatewayModelDiscovery:{name:"UpdateTeamLlmGatewayModelDiscovery",I:n.i_X,O:n.wBS,kind:s.MethodKind.Unary},updateTeamLlmGatewayProviderEndpoints:{name:"UpdateTeamLlmGatewayProviderEndpoints",I:n.moj,O:n.k3$,kind:s.MethodKind.Unary},setTeamNoZdrModelConsent:{name:"SetTeamNoZdrModelConsent",I:n.HOq,O:n.xEn,kind:s.MethodKind.Unary},setOrganizationNoZdrModelConsent:{name:"SetOrganizationNoZdrModelConsent",I:n.xO$,O:n.b07,kind:s.MethodKind.Unary},getOrganizationPrivateInferencePolicy:{name:"GetOrganizationPrivateInferencePolicy",I:n.Vie,O:n.vsf,kind:s.MethodKind.Unary},updateOrganizationPrivateInferencePolicy:{name:"UpdateOrganizationPrivateInferencePolicy",I:n.Tjf,O:n.eWF,kind:s.MethodKind.Unary},getOrganizationPrivateInferenceTeamGroups:{name:"GetOrganizationPrivateInferenceTeamGroups",I:n.Ok7,O:n.Ajm,kind:s.MethodKind.Unary},getTeamPrivateInferencePolicy:{name:"GetTeamPrivateInferencePolicy",I:n.VNQ,O:n.NYc,kind:s.MethodKind.Unary},updateTeamPrivateInferencePolicy:{name:"UpdateTeamPrivateInferencePolicy",I:n.Ozh,O:n.wcT,kind:s.MethodKind.Unary},getOrganizationOnDemandSpendDisabled:{name:"GetOrganizationOnDemandSpendDisabled",I:n.Twg,O:n.$H2,kind:s.MethodKind.Unary},setOrganizationOnDemandSpendDisabled:{name:"SetOrganizationOnDemandSpendDisabled",I:n.zYy,O:n.dwD,kind:s.MethodKind.Unary},getOrganizationCreditRequestButtonHidden:{name:"GetOrganizationCreditRequestButtonHidden",I:n.jIe,O:n.JEj,kind:s.MethodKind.Unary},setOrganizationCreditRequestButtonHidden:{name:"SetOrganizationCreditRequestButtonHidden",I:n.v_8,O:n.VgQ,kind:s.MethodKind.Unary},getOrganizationSsoJitAutoEnrollment:{name:"GetOrganizationSsoJitAutoEnrollment",I:n._v$,O:n.yj0,kind:s.MethodKind.Unary},setOrganizationSsoJitAutoEnrollment:{name:"SetOrganizationSsoJitAutoEnrollment",I:n.yjV,O:n.c4k,kind:s.MethodKind.Unary},getTeamSsoJitAutoEnrollment:{name:"GetTeamSsoJitAutoEnrollment",I:n.WsN,O:n.Afl,kind:s.MethodKind.Unary},setTeamSsoJitAutoEnrollment:{name:"SetTeamSsoJitAutoEnrollment",I:n.O8H,O:n.wDw,kind:s.MethodKind.Unary},getTeamXAccountLinking:{name:"GetTeamXAccountLinking",I:n.ScF,O:n.bZb,kind:s.MethodKind.Unary},setTeamXAccountLinking:{name:"SetTeamXAccountLinking",I:n.WUm,O:n.bZb,kind:s.MethodKind.Unary},getOrganizationRemoteControlSettings:{name:"GetOrganizationRemoteControlSettings",I:n.ZPB,O:n.vfT,kind:s.MethodKind.Unary},updateOrganizationRemoteControlSettings:{name:"UpdateOrganizationRemoteControlSettings",I:n.AL,O:n.EDv,kind:s.MethodKind.Unary},getOrganizationSlackManagedWorkspaces:{name:"GetOrganizationSlackManagedWorkspaces",I:n.kxz,O:n.wFu,kind:s.MethodKind.Unary},updateOrganizationSlackManagedWorkspaces:{name:"UpdateOrganizationSlackManagedWorkspaces",I:n.pmc,O:n.PW,kind:s.MethodKind.Unary},getOrganizationSlackInboundInstallPolicy:{name:"GetOrganizationSlackInboundInstallPolicy",I:n.pPB,O:n.DxY,kind:s.MethodKind.Unary},updateOrganizationSlackInboundInstallPolicy:{name:"UpdateOrganizationSlackInboundInstallPolicy",I:n.aam,O:n.AF,kind:s.MethodKind.Unary},getOrganizationGrokBotWallSnapshotControls:{name:"GetOrganizationGrokBotWallSnapshotControls",I:Rf,O:vf,kind:s.MethodKind.Unary},updateOrganizationGrokBotWallSnapshotControls:{name:"UpdateOrganizationGrokBotWallSnapshotControls",I:xf,O:kf,kind:s.MethodKind.Unary},getOrganizationGoogleDriveBlockedSharedDrives:{name:"GetOrganizationGoogleDriveBlockedSharedDrives",I:n.iS1,O:n._ax,kind:s.MethodKind.Unary},updateOrganizationGoogleDriveBlockedSharedDrives:{name:"UpdateOrganizationGoogleDriveBlockedSharedDrives",I:n.b3B,O:n.vym,kind:s.MethodKind.Unary},getOrganizationConnectorAccountOwnership:{name:"GetOrganizationConnectorAccountOwnership",I:n.GoS,O:n.O8k,kind:s.MethodKind.Unary},updateOrganizationConnectorAccountOwnership:{name:"UpdateOrganizationConnectorAccountOwnership",I:n.fS9,O:n.EvY,kind:s.MethodKind.Unary},getTeamRemoteControlSettings:{name:"GetTeamRemoteControlSettings",I:n.DVl,O:n.V$7,kind:s.MethodKind.Unary},updateTeamRemoteControlSettings:{name:"UpdateTeamRemoteControlSettings",I:n.ORt,O:n.yL9,kind:s.MethodKind.Unary},listOrganizationRemoteControlDevices:{name:"ListOrganizationRemoteControlDevices",I:n.jrM,O:n.ERl,kind:s.MethodKind.Unary},revokeOrganizationRemoteControlDevice:{name:"RevokeOrganizationRemoteControlDevice",I:n.CdP,O:n.lvC,kind:s.MethodKind.Unary},listTeamRemoteControlDevices:{name:"ListTeamRemoteControlDevices",I:n.P0D,O:n.ERl,kind:s.MethodKind.Unary},revokeTeamRemoteControlDevice:{name:"RevokeTeamRemoteControlDevice",I:n.Apo,O:n.lvC,kind:s.MethodKind.Unary},setUserNoZdrModelConsent:{name:"SetUserNoZdrModelConsent",I:n.hk4,O:n.ZpC,kind:s.MethodKind.Unary},setTeamMemberNoZdrModelConsent:{name:"SetTeamMemberNoZdrModelConsent",I:n.npU,O:n.PGd,kind:s.MethodKind.Unary},getNoZdrModelConsentStatus:{name:"GetNoZdrModelConsentStatus",I:n.Udp,O:n._am,kind:s.MethodKind.Unary},updateTeamInviteLinkTTLSetting:{name:"UpdateTeamInviteLinkTTLSetting",I:n.Lr1,O:n.Bpu,kind:s.MethodKind.Unary},updateTeamMemberInviteSetting:{name:"UpdateTeamMemberInviteSetting",I:n.tdz,O:n.N4Y,kind:s.MethodKind.Unary},updateTeamInviteLinkJoinApprovalSetting:{name:"UpdateTeamInviteLinkJoinApprovalSetting",I:n.cCB,O:n.mFP,kind:s.MethodKind.Unary},updateTeamPersonalApiKeyCreationSetting:{name:"UpdateTeamPersonalApiKeyCreationSetting",I:n.izj,O:n.Qul,kind:s.MethodKind.Unary},updateTeamVoiceChatSetting:{name:"UpdateTeamVoiceChatSetting",I:n.WL_,O:n.SPf,kind:s.MethodKind.Unary},updateTeamDefaultMemberBillingTier:{name:"UpdateTeamDefaultMemberBillingTier",I:n.gPk,O:n.wZY,kind:s.MethodKind.Unary},updateTeamSandOnboardingCompleted:{name:"UpdateTeamSandOnboardingCompleted",I:Cl,O:Tl,kind:s.MethodKind.Unary},updateTeamSandSetupChecklistItem:{name:"UpdateTeamSandSetupChecklistItem",I:Ul,O:Al,kind:s.MethodKind.Unary},markTeamSandOnboardingSeen:{name:"MarkTeamSandOnboardingSeen",I:$l,O:Ml,kind:s.MethodKind.Unary},getTeamGrokBotEligibleUserIds:{name:"GetTeamGrokBotEligibleUserIds",I:Ol,O:Dl,kind:s.MethodKind.Unary},sendTeamSandOnboardingInvites:{name:"SendTeamSandOnboardingInvites",I:Nl,O:Gl,kind:s.MethodKind.Unary},getProtectedGitScopes:{name:"GetProtectedGitScopes",I:n.TXH,O:n.P_k,kind:s.MethodKind.Unary},createProtectedGitScope:{name:"CreateProtectedGitScope",I:n.IW3,O:n.wmn,kind:s.MethodKind.Unary},deleteProtectedGitScope:{name:"DeleteProtectedGitScope",I:n.tE7,O:n.R1c,kind:s.MethodKind.Unary},createTeamFreeTrialCode:{name:"CreateTeamFreeTrialCode",I:n.Qx5,O:n.M3e,kind:s.MethodKind.Unary},createTeamFreeTrialCodeInternal:{name:"CreateTeamFreeTrialCodeInternal",I:n.Qx5,O:n.M3e,kind:s.MethodKind.Unary},setTrialSpendLimitOverrideInternal:{name:"SetTrialSpendLimitOverrideInternal",I:n.IHq,O:n.qks,kind:s.MethodKind.Unary},getTrialSpendLimitInternal:{name:"GetTrialSpendLimitInternal",I:n.yIy,O:n.C2K,kind:s.MethodKind.Unary},getOrganizationEnterpriseTrialExtendContextInternal:{name:"GetOrganizationEnterpriseTrialExtendContextInternal",I:n.Yeg,O:n.eBq,kind:s.MethodKind.Unary},applyOrganizationEnterpriseTrialEndInternal:{name:"ApplyOrganizationEnterpriseTrialEndInternal",I:n.mi9,O:n.Izq,kind:s.MethodKind.Unary},getTeamUnifiedStatusInternal:{name:"GetTeamUnifiedStatusInternal",I:ue,O:ce,kind:s.MethodKind.Unary},startUnifiedTeamTrialInternal:{name:"StartUnifiedTeamTrialInternal",I:fe,O:me,kind:s.MethodKind.Unary},extendUnifiedTeamTrialInternal:{name:"ExtendUnifiedTeamTrialInternal",I:de,O:me,kind:s.MethodKind.Unary},endUnifiedTeamTrialInternal:{name:"EndUnifiedTeamTrialInternal",I:pe,O:me,kind:s.MethodKind.Unary},convertUnifiedTeamTrialInternal:{name:"ConvertUnifiedTeamTrialInternal",I:he,O:me,kind:s.MethodKind.Unary},getUnifiedTeamTrialInternal:{name:"GetUnifiedTeamTrialInternal",I:ge,O:_e,kind:s.MethodKind.Unary},getEnterpriseGrokBotTeamTrialInternal:{name:"GetEnterpriseGrokBotTeamTrialInternal",I:Ll,O:Fl,kind:s.MethodKind.Unary},setEnterpriseGrokBotTeamTrialExpirationInternal:{name:"SetEnterpriseGrokBotTeamTrialExpirationInternal",I:Kl,O:zl,kind:s.MethodKind.Unary},getXaiUserUsageSnapshot:{name:"GetXaiUserUsageSnapshot",I:n.WAE,O:n.qSX,kind:s.MethodKind.Unary},getXaiUserPrepaidBilling:{name:"GetXaiUserPrepaidBilling",I:n.b4u,O:n.$H_,kind:s.MethodKind.Unary},setXaiUserPrepaidAutoTopUp:{name:"SetXaiUserPrepaidAutoTopUp",I:n.h3x,O:n.D9s,kind:s.MethodKind.Unary},getXaiCommerceBearerToken:{name:"GetXaiCommerceBearerToken",I:n.hD2,O:n.ZoF,kind:s.MethodKind.Unary},getTeamOffboardingConfigInternal:{name:"GetTeamOffboardingConfigInternal",I:n.XRZ,O:n.pv1,kind:s.MethodKind.Unary},updateTeamOffboardingConfigInternal:{name:"UpdateTeamOffboardingConfigInternal",I:n.AKO,O:n.C7S,kind:s.MethodKind.Unary},createTeamCreditGrantInternal:{name:"CreateTeamCreditGrantInternal",I:n.BEg,O:n.Rz7,kind:s.MethodKind.Unary},listTeamCreditGrantsInternal:{name:"ListTeamCreditGrantsInternal",I:n.CAc,O:n.GYk,kind:s.MethodKind.Unary},createTeamsTrialV2ReferralCode:{name:"CreateTeamsTrialV2ReferralCode",I:n.cj_,O:n.SyP,kind:s.MethodKind.Unary},getTeamAnalytics:{name:"GetTeamAnalytics",I:n.FFq,O:n.LLA,kind:s.MethodKind.Unary},getUserAnalytics:{name:"GetUserAnalytics",I:n.dcL,O:n.n24,kind:s.MethodKind.Unary},getTeamRawData:{name:"GetTeamRawData",I:n.hUh,O:n.dZ5,kind:s.MethodKind.Unary},getClientUsageData:{name:"GetClientUsageData",I:n.u_0,O:n.gHM,kind:s.MethodKind.Unary},getCurrentPeriodUsage:{name:"GetCurrentPeriodUsage",I:n.Dl4,O:n.bO3,kind:s.MethodKind.Unary},useSandBankedReset:{name:"UseSandBankedReset",I:jl,O:Hl,kind:s.MethodKind.Unary},listSandBankedResets:{name:"ListSandBankedResets",I:Wl,O:Vl,kind:s.MethodKind.Unary},getSandUsageStatus:{name:"GetSandUsageStatus",I:Gm,O:zm,kind:s.MethodKind.Unary},getSandUpgradeOffer:{name:"GetSandUpgradeOffer",I:om,O:am,kind:s.MethodKind.Unary},getGrokBotUsageBreakdown:{name:"GetGrokBotUsageBreakdown",I:Qm,O:ef,kind:s.MethodKind.Unary},getSandEnterpriseSpendLimit:{name:"GetSandEnterpriseSpendLimit",I:nf,O:sf,kind:s.MethodKind.Unary},requestSandSeatTierUpgrade:{name:"RequestSandSeatTierUpgrade",I:Lm,O:Fm,kind:s.MethodKind.Unary},listBankedUsageResets:{name:"ListBankedUsageResets",I:n.kCx,O:n.izO,kind:s.MethodKind.Unary},redeemTeamBankedUsageReset:{name:"RedeemTeamBankedUsageReset",I:n.J_n,O:n.BLE,kind:s.MethodKind.Unary},redeemUserBankedUsageReset:{name:"RedeemUserBankedUsageReset",I:n.J_n,O:n.BLE,kind:s.MethodKind.Unary},startSandTrial:{name:"StartSandTrial",I:uf,O:_f,kind:s.MethodKind.Unary},claimSandTrialWithDeviceAttestation:{name:"ClaimSandTrialWithDeviceAttestation",I:cf,O:ff,kind:s.MethodKind.Unary},resetSandTrialDeviceAttestation:{name:"ResetSandTrialDeviceAttestation",I:pf,O:hf,kind:s.MethodKind.Unary},isEligibleForSandTrial:{name:"IsEligibleForSandTrial",I:yf,O:Sf,kind:s.MethodKind.Unary},getSandTrialClaimStatus:{name:"GetSandTrialClaimStatus",I:If,O:Pf,kind:s.MethodKind.Unary},cancelSandTrial:{name:"CancelSandTrial",I:qf,O:Bf,kind:s.MethodKind.Unary},getSandAccessStatus:{name:"GetSandAccessStatus",I:Xl,O:mm,kind:s.MethodKind.Unary},shouldShowGrokBotTrainingOptInPopup:{name:"ShouldShowGrokBotTrainingOptInPopup",I:Yl,O:Zl,kind:s.MethodKind.Unary},markGrokBotTrainingOptInPromptSeen:{name:"MarkGrokBotTrainingOptInPromptSeen",I:um,O:cm,kind:s.MethodKind.Unary},getSandMarketingIdentity:{name:"GetSandMarketingIdentity",I:Om,O:Dm,kind:s.MethodKind.Unary},getBonfireStatus:{name:"GetBonfireStatus",I:n.DrQ,O:n.ZhM,kind:s.MethodKind.Unary},createBonfireInvite:{name:"CreateBonfireInvite",I:n._do,O:n.EAb,kind:s.MethodKind.Unary},sendBonfireInvite:{name:"SendBonfireInvite",I:n.EiN,O:n.e0Y,kind:s.MethodKind.Unary},registerSandMachine:{name:"RegisterSandMachine",I:Sm,O:qm,kind:s.MethodKind.Unary},listSandMachines:{name:"ListSandMachines",I:Bm,O:Pm,kind:s.MethodKind.Unary},updateSandMachineLabel:{name:"UpdateSandMachineLabel",I:bm,O:Rm,kind:s.MethodKind.Unary},updateSandMachineLocalToolPermission:{name:"UpdateSandMachineLocalToolPermission",I:vm,O:xm,kind:s.MethodKind.Unary},getSandMachineMessagesEnabled:{name:"GetSandMachineMessagesEnabled",I:km,O:Em,kind:s.MethodKind.Unary},updateSandMachineMessagesEnabled:{name:"UpdateSandMachineMessagesEnabled",I:Cm,O:Tm,kind:s.MethodKind.Unary},retrySandMessagesPermission:{name:"RetrySandMessagesPermission",I:Um,O:Am,kind:s.MethodKind.Unary},removeSandMachine:{name:"RemoveSandMachine",I:Pd,O:bd,kind:s.MethodKind.Unary},requestSandTeamAccess:{name:"RequestSandTeamAccess",I:$m,O:Mm,kind:s.MethodKind.Unary},listPendingUserAccessRequests:{name:"ListPendingUserAccessRequests",I:n._YH,O:n._i_,kind:s.MethodKind.Unary},getUsageSignalsProjectionSnapshot:{name:"GetUsageSignalsProjectionSnapshot",I:ep,O:np,kind:s.MethodKind.Unary},getPlanInfo:{name:"GetPlanInfo",I:n.V4G,O:n.noV,kind:s.MethodKind.Unary},verifyAppleTransaction:{name:"VerifyAppleTransaction",I:n.Ll_,O:n.rKG,kind:s.MethodKind.Unary},verifyGooglePlayPurchase:{name:"VerifyGooglePlayPurchase",I:n.rG0,O:n.lWs,kind:s.MethodKind.Unary},getGooglePlayBillingAccountId:{name:"GetGooglePlayBillingAccountId",I:n.wcH,O:n.cQ7,kind:s.MethodKind.Unary},inventoryGooglePlayPurchaseTokens:{name:"InventoryGooglePlayPurchaseTokens",I:n.WCl,O:n.GYE,kind:s.MethodKind.Unary},restoreCommerceStorePurchases:{name:"RestoreCommerceStorePurchases",I:n.Eg0,O:n.c6S,kind:s.MethodKind.Unary},getGrokCreditPackPurchaseAccount:{name:"GetGrokCreditPackPurchaseAccount",I:Je,O:we,kind:s.MethodKind.Unary},reportGrokCreditPackPurchase:{name:"ReportGrokCreditPackPurchase",I:ye,O:Be,kind:s.MethodKind.Unary},inspectGooglePlaySubscriptionInternal:{name:"InspectGooglePlaySubscriptionInternal",I:n.NNb,O:n.Zm8,kind:s.MethodKind.Unary},inspectGooglePlayTransactionsInternal:{name:"InspectGooglePlayTransactionsInternal",I:n.B5B,O:n.bh8,kind:s.MethodKind.Unary},sendTestPushNotificationInternal:{name:"SendTestPushNotificationInternal",I:n.wQX,O:n.izm,kind:s.MethodKind.Unary},listTeamInviteLinksInternal:{name:"ListTeamInviteLinksInternal",I:n.sbK,O:n.ofK,kind:s.MethodKind.Unary},revokeTeamInviteLinksInternal:{name:"RevokeTeamInviteLinksInternal",I:n.kwX,O:n.WRC,kind:s.MethodKind.Unary},getCursorReviewEntitlement:{name:"GetCursorReviewEntitlement",I:n.pmk,O:n.LwP,kind:s.MethodKind.Unary},searchOriginReviewPeople:{name:"SearchOriginReviewPeople",I:n.PBS,O:n.JZ6,kind:s.MethodKind.Unary},getOriginReviewPreferences:{name:"GetOriginReviewPreferences",I:n.q9G,O:n.MQS,kind:s.MethodKind.Unary},setOriginReviewPreferences:{name:"SetOriginReviewPreferences",I:n.CLT,O:n.q5s,kind:s.MethodKind.Unary},getMergeBotSettings:{name:"GetMergeBotSettings",I:n._GX,O:n.Q50,kind:s.MethodKind.Unary},setMergeBotConsent:{name:"SetMergeBotConsent",I:n.Ldy,O:n.BDC,kind:s.MethodKind.Unary},syncClientSettings:{name:"SyncClientSettings",I:n.L7H,O:n.jGg,kind:s.MethodKind.Unary},listRepoLearnedRules:{name:"ListRepoLearnedRules",I:ip,O:op,kind:s.MethodKind.Unary},removeRepoLearnedRule:{name:"RemoveRepoLearnedRule",I:up,O:cp,kind:s.MethodKind.Unary},appendRsiRecord:{name:"AppendRsiRecord",I:gp,O:_p,kind:s.MethodKind.Unary},getRsiRecord:{name:"GetRsiRecord",I:Jp,O:wp,kind:s.MethodKind.Unary},listRsiRecords:{name:"ListRsiRecords",I:yp,O:Sp,kind:s.MethodKind.Unary},getRsiSnapshot:{name:"GetRsiSnapshot",I:qp,O:Bp,kind:s.MethodKind.Unary},getRsiAdminStatusInternal:{name:"GetRsiAdminStatusInternal",I:Rp,O:vp,kind:s.MethodKind.Unary},runRsiLoopNowInternal:{name:"RunRsiLoopNowInternal",I:xp,O:kp,kind:s.MethodKind.Unary},setRsiLoopPausedInternal:{name:"SetRsiLoopPausedInternal",I:Ep,O:Cp,kind:s.MethodKind.Unary},getUsageLimitPolicyStatus:{name:"GetUsageLimitPolicyStatus",I:n.qhH,O:n.I_D,kind:s.MethodKind.Unary},getUsageLimitStatusAndActiveGrants:{name:"GetUsageLimitStatusAndActiveGrants",I:n.S9t,O:n._ty,kind:s.MethodKind.Unary},getCreditGrantsBalance:{name:"GetCreditGrantsBalance",I:n.MjR,O:n.CkD,kind:s.MethodKind.Unary},getClientVisibleCreditGrants:{name:"GetClientVisibleCreditGrants",I:n.V8e,O:n.Pqo,kind:s.MethodKind.Unary},getAdvancedAnalyticsEnabled:{name:"GetAdvancedAnalyticsEnabled",I:n.P1T,O:n.VxL,kind:s.MethodKind.Unary},getTokenUsage:{name:"GetTokenUsage",I:n.SK5,O:n.I9h,kind:s.MethodKind.Unary},validateBedrockIamRole:{name:"ValidateBedrockIamRole",I:n.Z8m,O:n.VbN,kind:s.MethodKind.Unary},getTeamSpend:{name:"GetTeamSpend",I:n.$Sc,O:n.R2E,kind:s.MethodKind.Unary},getTeamSeatUpgradeRecommendations:{name:"GetTeamSeatUpgradeRecommendations",I:n.Y$T,O:n.o35,kind:s.MethodKind.Unary},getPendingSeatTierUpgradeRequests:{name:"GetPendingSeatTierUpgradeRequests",I:n.qWG,O:n.YJY,kind:s.MethodKind.Unary},getTeamSeatCapacity:{name:"GetTeamSeatCapacity",I:n.e6P,O:n.SuY,kind:s.MethodKind.Unary},startMergedTeamSeatChange:{name:"StartMergedTeamSeatChange",I:Ie,O:be,kind:s.MethodKind.Unary},changeMergedTeamSeat:{name:"ChangeMergedTeamSeat",I:Re,O:xe,kind:s.MethodKind.Unary},getMergedTeamSeatChanges:{name:"GetMergedTeamSeatChanges",I:ke,O:Ce,kind:s.MethodKind.Unary},getXaiTeamPlanManagement:{name:"GetXaiTeamPlanManagement",I:n.jq0,O:n.f1t,kind:s.MethodKind.Unary},changeXaiTeamPlan:{name:"ChangeXaiTeamPlan",I:n.IV$,O:n.yW5,kind:s.MethodKind.Unary},getCurrentBillingCycle:{name:"GetCurrentBillingCycle",I:n.yI7,O:n.cTj,kind:s.MethodKind.Unary},getMonthlyBillingCycle:{name:"GetMonthlyBillingCycle",I:n.iaP,O:n.KuC,kind:s.MethodKind.Unary},getBugbotSettings:{name:"GetBugbotSettings",I:n.Ioc,O:n.GNy,kind:s.MethodKind.Unary},getBugbotAnalyticsV2:{name:"GetBugbotAnalyticsV2",I:n.JWI,O:n.NXG,kind:s.MethodKind.Unary},getBugBotPRAnalytics:{name:"GetBugBotPRAnalytics",I:n.Jns,O:n.Fkp,kind:s.MethodKind.Unary},getGithubInstallations:{name:"GetGithubInstallations",I:n.kcC,O:n.UYU,kind:s.MethodKind.Unary},getGithubInstallationTenantGrants:{name:"GetGithubInstallationTenantGrants",I:n.Owv,O:n.yq_,kind:s.MethodKind.Unary},grantGithubInstallationTenant:{name:"GrantGithubInstallationTenant",I:n.hvD,O:n.p84,kind:s.MethodKind.Unary},revokeGithubInstallationTenant:{name:"RevokeGithubInstallationTenant",I:n.Rig,O:n.neC,kind:s.MethodKind.Unary},getBugbotSuggestedRepos:{name:"GetBugbotSuggestedRepos",I:n.nTs,O:n.ZJ6,kind:s.MethodKind.Unary},getSecurityAgentSuggestedRepos:{name:"GetSecurityAgentSuggestedRepos",I:n.ZPw,O:n.ZOX,kind:s.MethodKind.Unary},getScmConnectionStatus:{name:"GetScmConnectionStatus",I:n.Lys,O:n.VS9,kind:s.MethodKind.Unary},getGithubRepoAccessStatus:{name:"GetGithubRepoAccessStatus",I:n.XT3,O:n.HyV,kind:s.MethodKind.Unary},getScmConnectionStatuses:{name:"GetScmConnectionStatuses",I:n.tJ9,O:n.lIF,kind:s.MethodKind.Unary},getInstallationRepos:{name:"GetInstallationRepos",I:n.L$Y,O:n.ljc,kind:s.MethodKind.Unary},fetchAllInstallationRepos:{name:"FetchAllInstallationRepos",I:n.UfC,O:n.gJO,kind:s.MethodKind.Unary},getInstallationGithubUsers:{name:"GetInstallationGithubUsers",I:n.toQ,O:n.P4d,kind:s.MethodKind.Unary},getUserAdminOrganizations:{name:"GetUserAdminOrganizations",I:n._V,O:n.KLX,kind:s.MethodKind.Unary},getTeamGithubUsers:{name:"GetTeamGithubUsers",I:n.yk8,O:n.ecN,kind:s.MethodKind.Unary},addGithubUsersToTeam:{name:"AddGithubUsersToTeam",I:n.gMg,O:n.yD7,kind:s.MethodKind.Unary},resolveGithubIdentities:{name:"ResolveGithubIdentities",I:n.lpG,O:n.LlT,kind:s.MethodKind.Unary},getUserPullRequests:{name:"GetUserPullRequests",I:n.Mq,O:n.M2w,kind:s.MethodKind.Unary},getUserReviewRequests:{name:"GetUserReviewRequests",I:n.Jjk,O:n.$DS,kind:s.MethodKind.Unary},getPullRequestForBranch:{name:"GetPullRequestForBranch",I:n.xGV,O:n.$EH,kind:s.MethodKind.Unary},updateGithubRepoSettings:{name:"UpdateGithubRepoSettings",I:n.NZ_,O:n.l8$,kind:s.MethodKind.Unary},updateGithubInstallationSettings:{name:"UpdateGithubInstallationSettings",I:n.J9i,O:n.T1W,kind:s.MethodKind.Unary},updateAllGithubRepoSettings:{name:"UpdateAllGithubRepoSettings",I:n.CNn,O:n.QOJ,kind:s.MethodKind.Unary},updateGithubInstallationTeamScope:{name:"UpdateGithubInstallationTeamScope",I:n.hxG,O:n.Lre,kind:s.MethodKind.Unary},updateSelfGithubAllowlist:{name:"UpdateSelfGithubAllowlist",I:n.pNh,O:n.vTx,kind:s.MethodKind.Unary},getTeamBugbotSettings:{name:"GetTeamBugbotSettings",I:n.LRN,O:n.Lg7,kind:s.MethodKind.Unary},updateTeamBugbotSettings:{name:"UpdateTeamBugbotSettings",I:n.sNl,O:n.Mlf,kind:s.MethodKind.Unary},migrateTeamBugbotToUsageBasedBilling:{name:"MigrateTeamBugbotToUsageBasedBilling",I:n.LIs,O:n.lW1,kind:s.MethodKind.Unary},getBugbotMergedPrScanSummary:{name:"GetBugbotMergedPrScanSummary",I:n.wS2,O:n.sWv,kind:s.MethodKind.Unary},getBugbotMode:{name:"GetBugbotMode",I:n.sVJ,O:n.YHh,kind:s.MethodKind.Unary},updateBugbotMode:{name:"UpdateBugbotMode",I:n.NQP,O:n.LK4,kind:s.MethodKind.Unary},getBugBotProUserMode:{name:"GetBugBotProUserMode",I:n.meH,O:n.ym8,kind:s.MethodKind.Unary},updateBugBotProUserMode:{name:"UpdateBugBotProUserMode",I:n.dj5,O:n.PFI,kind:s.MethodKind.Unary},getBugbotUserSettings:{name:"GetBugbotUserSettings",I:n.BHX,O:n.DLm,kind:s.MethodKind.Unary},updateBugbotUserSettings:{name:"UpdateBugbotUserSettings",I:n.QWx,O:n.Qsl,kind:s.MethodKind.Unary},getFullSelfDrivingUserSettings:{name:"GetFullSelfDrivingUserSettings",I:n.y$W,O:n.Ik0,kind:s.MethodKind.Unary},updateFullSelfDrivingUserSettings:{name:"UpdateFullSelfDrivingUserSettings",I:n.DrI,O:n.BRX,kind:s.MethodKind.Unary},listFullSelfDrivingRepoSettings:{name:"ListFullSelfDrivingRepoSettings",I:n.LdP,O:n.l1H,kind:s.MethodKind.Unary},setFullSelfDrivingRepoEnabled:{name:"SetFullSelfDrivingRepoEnabled",I:n.V6X,O:n.tJA,kind:s.MethodKind.Unary},getFullSelfDrivingTeamSettings:{name:"GetFullSelfDrivingTeamSettings",I:n.i20,O:n.M7A,kind:s.MethodKind.Unary},updateFullSelfDrivingTeamSettings:{name:"UpdateFullSelfDrivingTeamSettings",I:n.zuZ,O:n.Dfi,kind:s.MethodKind.Unary},listFullSelfDrivingTeamRepoSettings:{name:"ListFullSelfDrivingTeamRepoSettings",I:n.CXL,O:n.ybH,kind:s.MethodKind.Unary},setFullSelfDrivingTeamRepoEnabled:{name:"SetFullSelfDrivingTeamRepoEnabled",I:n.YBO,O:n.Soi,kind:s.MethodKind.Unary},listFullSelfDrivingActiveAgents:{name:"ListFullSelfDrivingActiveAgents",I:n.KHx,O:n.GPC,kind:s.MethodKind.Unary},listFullSelfDrivingTeamActiveAgents:{name:"ListFullSelfDrivingTeamActiveAgents",I:n.Hrn,O:n.pxf,kind:s.MethodKind.Unary},updateFullSelfDrivingPrConfig:{name:"UpdateFullSelfDrivingPrConfig",I:n.DWR,O:n.pGw,kind:s.MethodKind.Unary},getBugBotProUserSettings:{name:"GetBugBotProUserSettings",I:n.I6A,O:n.aBI,kind:s.MethodKind.Unary},updateBugBotProUserSettings:{name:"UpdateBugBotProUserSettings",I:n.hSh,O:n.P8G,kind:s.MethodKind.Unary},migrateBugBotProUserToUsageBasedBilling:{name:"MigrateBugBotProUserToUsageBasedBilling",I:n.E3$,O:n.MPB,kind:s.MethodKind.Unary},getGlassEarlyPreviewEnrollment:{name:"GetGlassEarlyPreviewEnrollment",I:n.Ryr,O:n.FPs,kind:s.MethodKind.Unary},enrollInGlassEarlyPreview:{name:"EnrollInGlassEarlyPreview",I:n.Cul,O:n.Y9v,kind:s.MethodKind.Unary},unenrollFromGlassEarlyPreview:{name:"UnenrollFromGlassEarlyPreview",I:n.UHP,O:n.UBK,kind:s.MethodKind.Unary},recordBugbotDeeplinkEvent:{name:"RecordBugbotDeeplinkEvent",I:n.sDp,O:n.Uj4,kind:s.MethodKind.Unary},recordBugbotDeeplinkEventUnauthenticated:{name:"RecordBugbotDeeplinkEventUnauthenticated",I:n.sDp,O:n.Uj4,kind:s.MethodKind.Unary},revokeBugBotLicenses:{name:"RevokeBugBotLicenses",I:n.H5R,O:n.Tcn,kind:s.MethodKind.Unary},revokeUserBugbotLicense:{name:"RevokeUserBugbotLicense",I:n.Z$K,O:n.FOE,kind:s.MethodKind.Unary},startBugbotBackfillLearning:{name:"StartBugbotBackfillLearning",I:n.NS4,O:n.xx6,kind:s.MethodKind.Unary},getBugbotBackfillStatus:{name:"GetBugbotBackfillStatus",I:n.Nux,O:n.hxv,kind:s.MethodKind.Unary},setSlackAuth:{name:"SetSlackAuth",I:n.WKP,O:n.mys,kind:s.MethodKind.Unary},getSlackTeamSettings:{name:"GetSlackTeamSettings",I:n.YAE,O:n.YyD,kind:s.MethodKind.Unary},updateSlackTeamSettings:{name:"UpdateSlackTeamSettings",I:n.HFD,O:n.Fr4,kind:s.MethodKind.Unary},getSlackSettings:{name:"GetSlackSettings",I:n.tcG,O:n.no,kind:s.MethodKind.Unary},getDeploymentIntegrationAvailability:{name:"GetDeploymentIntegrationAvailability",I:n.aPV,O:n.w_Q,kind:s.MethodKind.Unary},getSlackModelOptions:{name:"GetSlackModelOptions",I:n.lym,O:n.ddf,kind:s.MethodKind.Unary},getSlackInstallUrl:{name:"GetSlackInstallUrl",I:n.St,O:n.QKj,kind:s.MethodKind.Unary},getSlackInstallUrlPublic:{name:"GetSlackInstallUrlPublic",I:n.Xoe,O:n.ZoZ,kind:s.MethodKind.Unary},getSlackInstallUrlPublicWithUserScopes:{name:"GetSlackInstallUrlPublicWithUserScopes",I:n.Vqj,O:n.pty,kind:s.MethodKind.Unary},getFilteredUsageEvents:{name:"GetFilteredUsageEvents",I:n.FHO,O:n.TpA,kind:s.MethodKind.Unary},getAggregatedUsageEvents:{name:"GetAggregatedUsageEvents",I:n.l4W,O:n.JZY,kind:s.MethodKind.Unary},getAuditLogs:{name:"GetAuditLogs",I:n.Mq$,O:n.mTp,kind:s.MethodKind.Unary},getOrganizationAuditLogs:{name:"GetOrganizationAuditLogs",I:n.dIX,O:n.fIK,kind:s.MethodKind.Unary},listTeamDataExports:{name:"ListTeamDataExports",I:n.qC3,O:n.wHV,kind:s.MethodKind.Unary},createTeamDataExportDownloadUrl:{name:"CreateTeamDataExportDownloadUrl",I:n.eW$,O:n.eQk,kind:s.MethodKind.Unary},getUserPrivacyMode:{name:"GetUserPrivacyMode",I:n.KoG,O:n.mWk,kind:s.MethodKind.Unary},setUserPrivacyMode:{name:"SetUserPrivacyMode",I:n.eWf,O:n.Wig,kind:s.MethodKind.Unary},webAcknowledgeGracePeriodDisclaimer:{name:"WebAcknowledgeGracePeriodDisclaimer",I:n.sRz,O:n.mEf,kind:s.MethodKind.Unary},skipPrivacyModeGracePeriod:{name:"SkipPrivacyModeGracePeriod",I:n.jOB,O:n.dGI,kind:s.MethodKind.Unary},needsPrivacyModeMigration:{name:"NeedsPrivacyModeMigration",I:n.WWi,O:n.U5k,kind:s.MethodKind.Unary},updateTeamPrivacyModeMigrationOptOut:{name:"UpdateTeamPrivacyModeMigrationOptOut",I:n.es2,O:n.CKk,kind:s.MethodKind.Unary},shareConversation:{name:"ShareConversation",I:n.kHo,O:n.QhI,kind:s.MethodKind.Unary},getSharedConversation:{name:"GetSharedConversation",I:n.MyJ,O:n.mvz,kind:s.MethodKind.Unary},getPublicSharedConversation:{name:"GetPublicSharedConversation",I:n.ROu,O:n.xfP,kind:s.MethodKind.Unary},listSharedConversations:{name:"ListSharedConversations",I:n.R28,O:n.nMz,kind:s.MethodKind.Unary},deleteSharedConversation:{name:"DeleteSharedConversation",I:n.FUz,O:n.Z36,kind:s.MethodKind.Unary},updateSharedConversationVisibility:{name:"UpdateSharedConversationVisibility",I:n.NPW,O:n.JAL,kind:s.MethodKind.Unary},shareCanvas:{name:"ShareCanvas",I:n.tE3,O:n.lL7,kind:s.MethodKind.Unary},getSharedCanvas:{name:"GetSharedCanvas",I:n.JF,O:n.B2G,kind:s.MethodKind.Unary},getPublicSharedCanvas:{name:"GetPublicSharedCanvas",I:n.aE$,O:n.OCF,kind:s.MethodKind.Unary},listSharedCanvases:{name:"ListSharedCanvases",I:n.xos,O:n.xTz,kind:s.MethodKind.Unary},deleteSharedCanvas:{name:"DeleteSharedCanvas",I:n.shm,O:n._Md,kind:s.MethodKind.Unary},lookupSharedCanvasByKey:{name:"LookupSharedCanvasByKey",I:n.ptC,O:n.$bK,kind:s.MethodKind.Unary},listUserCanvases:{name:"ListUserCanvases",I:n.P_7,O:n.H1r,kind:s.MethodKind.Unary},getCanvasMetadata:{name:"GetCanvasMetadata",I:n.zyT,O:n.hcJ,kind:s.MethodKind.Unary},getCanvasPayload:{name:"GetCanvasPayload",I:n.gDx,O:n.K6f,kind:s.MethodKind.Unary},refreshCanvasSources:{name:"RefreshCanvasSources",I:n.TGZ,O:n.d6S,kind:s.MethodKind.Unary},runCanvasConnectorAction:{name:"RunCanvasConnectorAction",I:n.Ebu,O:n.E7l,kind:s.MethodKind.Unary},getCanvasPageBrand:{name:"GetCanvasPageBrand",I:n.SNZ,O:n.wEJ,kind:s.MethodKind.Unary},getDocumentPayload:{name:"GetDocumentPayload",I:n.r$m,O:n.ZB$,kind:s.MethodKind.Unary},setCanvasVisibility:{name:"SetCanvasVisibility",I:n.uKx,O:n._w7,kind:s.MethodKind.Unary},getCanvasShareAccess:{name:"GetCanvasShareAccess",I:n.dAQ,O:n.$sY,kind:s.MethodKind.Unary},updateCanvasShareAccess:{name:"UpdateCanvasShareAccess",I:n.YG,O:n.uNt,kind:s.MethodKind.Unary},setPageAddress:{name:"SetPageAddress",I:n.rhB,O:n.p5Q,kind:s.MethodKind.Unary},deleteCanvas:{name:"DeleteCanvas",I:n.J5_,O:n.xQH,kind:s.MethodKind.Unary},renameCanvas:{name:"RenameCanvas",I:n.k5b,O:n.icQ,kind:s.MethodKind.Unary},getTeamSharedConversationSettings:{name:"GetTeamSharedConversationSettings",I:n._b6,O:n.yTb,kind:s.MethodKind.Unary},updateTeamSharedConversationSettings:{name:"UpdateTeamSharedConversationSettings",I:n.TIw,O:n.rRJ,kind:s.MethodKind.Unary},getTeamSharedCanvasSettings:{name:"GetTeamSharedCanvasSettings",I:n.LWu,O:n.fZU,kind:s.MethodKind.Unary},updateTeamSharedCanvasSettings:{name:"UpdateTeamSharedCanvasSettings",I:n.iXm,O:n.k8Q,kind:s.MethodKind.Unary},getTeamProjectsSettings:{name:"GetTeamProjectsSettings",I:n.aJE,O:n.SRO,kind:s.MethodKind.Unary},updateTeamProjectsSettings:{name:"UpdateTeamProjectsSettings",I:n.xvP,O:n.nhk,kind:s.MethodKind.Unary},getTeamAppsSettings:{name:"GetTeamAppsSettings",I:n.OmT,O:n.GoT,kind:s.MethodKind.Unary},updateTeamAppsSettings:{name:"UpdateTeamAppsSettings",I:n.da6,O:n.zwl,kind:s.MethodKind.Unary},getTeamAppsReviewRules:{name:"GetTeamAppsReviewRules",I:n.CNw,O:n.iR7,kind:s.MethodKind.Unary},listTeamAppsReviewRulesVersions:{name:"ListTeamAppsReviewRulesVersions",I:n.pbO,O:n.xim,kind:s.MethodKind.Unary},getTeamAppsReviewRulesVersion:{name:"GetTeamAppsReviewRulesVersion",I:n.kfB,O:n.iwy,kind:s.MethodKind.Unary},saveTeamAppsReviewRules:{name:"SaveTeamAppsReviewRules",I:n.XRd,O:n.joE,kind:s.MethodKind.Unary},activateTeamAppsReviewRulesVersion:{name:"ActivateTeamAppsReviewRulesVersion",I:n.fdV,O:n.VVb,kind:s.MethodKind.Unary},getTeamPublicProfileSettings:{name:"GetTeamPublicProfileSettings",I:n.K$9,O:n.yVw,kind:s.MethodKind.Unary},updateTeamPublicProfileSettings:{name:"UpdateTeamPublicProfileSettings",I:n.VIg,O:n.lxh,kind:s.MethodKind.Unary},getTeamSandShareBotExportSettings:{name:"GetTeamSandShareBotExportSettings",I:Dc,O:Nc,kind:s.MethodKind.Unary},updateTeamSandShareBotExportSettings:{name:"UpdateTeamSandShareBotExportSettings",I:Gc,O:Lc,kind:s.MethodKind.Unary},updateTeamGrokBotCapabilities:{name:"UpdateTeamGrokBotCapabilities",I:Kc,O:Hc,kind:s.MethodKind.Unary},getTeamGrokBotConnectorAudiences:{name:"GetTeamGrokBotConnectorAudiences",I:Yc,O:Zc,kind:s.MethodKind.Unary},updateTeamGrokBotConnectorAudience:{name:"UpdateTeamGrokBotConnectorAudience",I:tl,O:rl,kind:s.MethodKind.Unary},getTeamDataRetentionPolicy:{name:"GetTeamDataRetentionPolicy",I:n.ZvO,O:n.bhm,kind:s.MethodKind.Unary},updateTeamDataRetentionPolicy:{name:"UpdateTeamDataRetentionPolicy",I:n.bLK,O:n.YbK,kind:s.MethodKind.Unary},getTeamGrokBotSlackWorkspaceAccess:{name:"GetTeamGrokBotSlackWorkspaceAccess",I:sl,O:il,kind:s.MethodKind.Unary},setTeamGrokBotSlackWorkspaceAccess:{name:"SetTeamGrokBotSlackWorkspaceAccess",I:ol,O:al,kind:s.MethodKind.Unary},listTeamGrokBotDefaultAgents:{name:"ListTeamGrokBotDefaultAgents",I:ul,O:cl,kind:s.MethodKind.Unary},setTeamGrokBotDefaultAudience:{name:"SetTeamGrokBotDefaultAudience",I:ll,O:ml,kind:s.MethodKind.Unary},setTeamGrokBotAgentTeamApproved:{name:"SetTeamGrokBotAgentTeamApproved",I:fl,O:dl,kind:s.MethodKind.Unary},listTeamGrokBotAgentAccess:{name:"ListTeamGrokBotAgentAccess",I:hl,O:gl,kind:s.MethodKind.Unary},setTeamGrokBotAgentAccess:{name:"SetTeamGrokBotAgentAccess",I:_l,O:Jl,kind:s.MethodKind.Unary},listTeamGrokBotDashboardAccess:{name:"ListTeamGrokBotDashboardAccess",I:vd,O:xd,kind:s.MethodKind.Unary},setTeamGrokBotDashboardAccess:{name:"SetTeamGrokBotDashboardAccess",I:kd,O:Ed,kind:s.MethodKind.Unary},listTeamGrokBotAccessTeams:{name:"ListTeamGrokBotAccessTeams",I:yl,O:Sl,kind:s.MethodKind.Unary},previewTeamGrokBotAgentTransfer:{name:"PreviewTeamGrokBotAgentTransfer",I:ql,O:Bl,kind:s.MethodKind.Unary},transferTeamGrokBotAgents:{name:"TransferTeamGrokBotAgents",I:Il,O:Pl,kind:s.MethodKind.Unary},getTeamGrokBotAgentTransfers:{name:"GetTeamGrokBotAgentTransfers",I:bl,O:Rl,kind:s.MethodKind.Unary},listTeamGrokBotTransferDestinations:{name:"ListTeamGrokBotTransferDestinations",I:vl,O:xl,kind:s.MethodKind.Unary},startTeamGrokBotOwnershipTransfer:{name:"StartTeamGrokBotOwnershipTransfer",I:kl,O:El,kind:s.MethodKind.Unary},getTeamSmartAutoSettings:{name:"GetTeamSmartAutoSettings",I:n.WjG,O:n.OBF,kind:s.MethodKind.Unary},updateTeamSmartAutoSettings:{name:"UpdateTeamSmartAutoSettings",I:n.Xtc,O:n.bIg,kind:s.MethodKind.Unary},getTeamPromptCachingSettings:{name:"GetTeamPromptCachingSettings",I:n.H1L,O:n.P8_,kind:s.MethodKind.Unary},updateTeamPromptCachingSettings:{name:"UpdateTeamPromptCachingSettings",I:n.omy,O:n.wgB,kind:s.MethodKind.Unary},resetTeamAgentRunModeToAutoReview:{name:"ResetTeamAgentRunModeToAutoReview",I:n.L2q,O:n.Jiu,kind:s.MethodKind.Unary},getUserSmartAutoSettings:{name:"GetUserSmartAutoSettings",I:n.c$y,O:n.cHR,kind:s.MethodKind.Unary},updateUserSmartAutoSettings:{name:"UpdateUserSmartAutoSettings",I:n.ZVF,O:n.zri,kind:s.MethodKind.Unary},getTeamBackgroundAgentSettings:{name:"GetTeamBackgroundAgentSettings",I:n.fQ,O:n.bNb,kind:s.MethodKind.Unary},getTeamGrokBotPublishedWorkerImage:{name:"GetTeamGrokBotPublishedWorkerImage",I:_d,O:wd,kind:s.MethodKind.Unary},updateTeamBackgroundAgentSettings:{name:"UpdateTeamBackgroundAgentSettings",I:n.QRZ,O:n.Iz5,kind:s.MethodKind.Unary},listTeamGrokBotCustomerHostedWorkers:{name:"ListTeamGrokBotCustomerHostedWorkers",I:yd,O:Sd,kind:s.MethodKind.Unary},getRepoSourcePreference:{name:"GetRepoSourcePreference",I:n.qc8,O:n.Mtj,kind:s.MethodKind.Unary},updateUserRepoSourcePreference:{name:"UpdateUserRepoSourcePreference",I:n.G6u,O:n._E_,kind:s.MethodKind.Unary},updateTeamRepoSourcePreference:{name:"UpdateTeamRepoSourcePreference",I:n.gez,O:n.MYI,kind:s.MethodKind.Unary},resolvePrCreationForge:{name:"ResolvePrCreationForge",I:n.OaX,O:n.MX_,kind:s.MethodKind.Unary},revokeTeamInviteLink:{name:"RevokeTeamInviteLink",I:n.yKm,O:n.mmN,kind:s.MethodKind.Unary},listTeamInviteLinks:{name:"ListTeamInviteLinks",I:n.$WS,O:n.Rc0,kind:s.MethodKind.Unary},listTeamPendingInvites:{name:"ListTeamPendingInvites",I:n.E7o,O:n.MLT,kind:s.MethodKind.Unary},revokeTeamPendingInvite:{name:"RevokeTeamPendingInvite",I:n.BaU,O:n.tRU,kind:s.MethodKind.Unary},resendTeamPendingInvite:{name:"ResendTeamPendingInvite",I:n.Y53,O:n.Ip9,kind:s.MethodKind.Unary},listTeamJoinRequests:{name:"ListTeamJoinRequests",I:n.ryS,O:n.rV_,kind:s.MethodKind.Unary},approveTeamJoinRequest:{name:"ApproveTeamJoinRequest",I:n.flK,O:n.Pqr,kind:s.MethodKind.Unary},denyTeamJoinRequest:{name:"DenyTeamJoinRequest",I:n.c9k,O:n.gTH,kind:s.MethodKind.Unary},updateUserName:{name:"UpdateUserName",I:n.bjc,O:n.lLB,kind:s.MethodKind.Unary},uploadUserProfilePicture:{name:"UploadUserProfilePicture",I:n.J3_,O:n.jzZ,kind:s.MethodKind.Unary},updateUserProfilePicture:{name:"UpdateUserProfilePicture",I:n.hLX,O:n.lYk,kind:s.MethodKind.Unary},listInvoices:{name:"ListInvoices",I:n.WXZ,O:n.YeS,kind:s.MethodKind.Unary},listUnifiedInvoices:{name:"ListUnifiedInvoices",I:Te,O:Ae,kind:s.MethodKind.Unary},getComplatCreditBalance:{name:"GetComplatCreditBalance",I:n.Hdt,O:n.F9z,kind:s.MethodKind.Unary},listBlockingCheckoutInvoices:{name:"ListBlockingCheckoutInvoices",I:n.hHX,O:n.D7O,kind:s.MethodKind.Unary},listPayableTeamInvoices:{name:"ListPayableTeamInvoices",I:n.Z_i,O:n.jiy,kind:s.MethodKind.Unary},listUnpaidUsageInvoices:{name:"ListUnpaidUsageInvoices",I:n.QBt,O:n.SQ3,kind:s.MethodKind.Unary},getRemainingRefunds:{name:"GetRemainingRefunds",I:n.Xdv,O:n.hzd,kind:s.MethodKind.Unary},getServiceAccountSpendLimit:{name:"GetServiceAccountSpendLimit",I:n.f_r,O:n.bJx,kind:s.MethodKind.Unary},setServiceAccountSpendLimit:{name:"SetServiceAccountSpendLimit",I:n.bkm,O:n.Vau,kind:s.MethodKind.Unary},setUserHardLimit:{name:"SetUserHardLimit",I:n.H16,O:n.Tw9,kind:s.MethodKind.Unary},setUserMonthlyLimit:{name:"SetUserMonthlyLimit",I:n.lEN,O:n.Z1Y,kind:s.MethodKind.Unary},toggleMarketingEmailOpt:{name:"ToggleMarketingEmailOpt",I:n.bQB,O:n.Z6E,kind:s.MethodKind.Unary},getMarketingEmailOpt:{name:"GetMarketingEmailOpt",I:n.fZH,O:n.hBo,kind:s.MethodKind.Unary},getGlobalLeaderboardOptIn:{name:"GetGlobalLeaderboardOptIn",I:n.A9x,O:n.u01,kind:s.MethodKind.Unary},setGlobalLeaderboardOptIn:{name:"SetGlobalLeaderboardOptIn",I:n.AB3,O:n.IXm,kind:s.MethodKind.Unary},createTeamApiKey:{name:"CreateTeamApiKey",I:n._C2,O:n.Mdl,kind:s.MethodKind.Unary},revokeTeamApiKey:{name:"RevokeTeamApiKey",I:n._Rg,O:n.ubM,kind:s.MethodKind.Unary},listTeamApiKeys:{name:"ListTeamApiKeys",I:n.dMs,O:n.Tsf,kind:s.MethodKind.Unary},listGrokApiKeys:{name:"ListGrokApiKeys",I:n.V5S,O:n.lc$,kind:s.MethodKind.Unary},getPersonalGrokApiKeyTeam:{name:"GetPersonalGrokApiKeyTeam",I:n.jWS,O:n.J41,kind:s.MethodKind.Unary},listGrokApiKeyAclOptions:{name:"ListGrokApiKeyAclOptions",I:n.yeW,O:n.ANW,kind:s.MethodKind.Unary},listGrokModels:{name:"ListGrokModels",I:n.flG,O:n.fMA,kind:s.MethodKind.Unary},listGrokBatches:{name:"ListGrokBatches",I:n.rih,O:n.dKG,kind:s.MethodKind.Unary},getGrokBatch:{name:"GetGrokBatch",I:n.jRA,O:n.RhX,kind:s.MethodKind.Unary},listGrokBatchRequests:{name:"ListGrokBatchRequests",I:n.Zav,O:n.DyZ,kind:s.MethodKind.Unary},getGrokBatchRequestResult:{name:"GetGrokBatchRequestResult",I:n.N2o,O:n.X26,kind:s.MethodKind.Unary},createGrokBatch:{name:"CreateGrokBatch",I:n.d7o,O:n.LRW,kind:s.MethodKind.Unary},cancelGrokBatch:{name:"CancelGrokBatch",I:n.Vi2,O:n.lXe,kind:s.MethodKind.Unary},listGrokBuiltInVoices:{name:"ListGrokBuiltInVoices",I:n.FFN,O:n.dO8,kind:s.MethodKind.Unary},listGrokCustomVoices:{name:"ListGrokCustomVoices",I:n.ned,O:n.R6h,kind:s.MethodKind.Unary},updateGrokCustomVoice:{name:"UpdateGrokCustomVoice",I:n.F5S,O:n.PTw,kind:s.MethodKind.Unary},deleteGrokCustomVoice:{name:"DeleteGrokCustomVoice",I:n.Pzk,O:n.n2r,kind:s.MethodKind.Unary},getGrokVoiceCloningAccess:{name:"GetGrokVoiceCloningAccess",I:n.dt7,O:n.p0o,kind:s.MethodKind.Unary},getGrokVoiceClonePassphrase:{name:"GetGrokVoiceClonePassphrase",I:n.Mly,O:n.QJW,kind:s.MethodKind.Unary},cloneGrokCustomVoice:{name:"CloneGrokCustomVoice",I:n.n$8,O:n.VxM,kind:s.MethodKind.Unary},listGrokFiles:{name:"ListGrokFiles",I:n.udh,O:n.ahg,kind:s.MethodKind.Unary},getGrokFile:{name:"GetGrokFile",I:n.Vt$,O:n.$X0,kind:s.MethodKind.Unary},updateGrokFile:{name:"UpdateGrokFile",I:n.gSd,O:n.Egt,kind:s.MethodKind.Unary},deleteGrokFile:{name:"DeleteGrokFile",I:n.yqI,O:n.YxF,kind:s.MethodKind.Unary},createGrokFilePublicUrl:{name:"CreateGrokFilePublicUrl",I:n.Vbl,O:n.lQ7,kind:s.MethodKind.Unary},revokeGrokFilePublicUrl:{name:"RevokeGrokFilePublicUrl",I:n.$lB,O:n.XSC,kind:s.MethodKind.Unary},listGrokCollections:{name:"ListGrokCollections",I:n.a_n,O:n.g$E,kind:s.MethodKind.Unary},getGrokCollection:{name:"GetGrokCollection",I:n.VGL,O:n.lj2,kind:s.MethodKind.Unary},createGrokCollection:{name:"CreateGrokCollection",I:n.Z9k,O:n.rxf,kind:s.MethodKind.Unary},updateGrokCollection:{name:"UpdateGrokCollection",I:n.kZD,O:n.U$g,kind:s.MethodKind.Unary},deleteGrokCollection:{name:"DeleteGrokCollection",I:n.W5o,O:n.c0r,kind:s.MethodKind.Unary},cloneGrokCollection:{name:"CloneGrokCollection",I:n.wKn,O:n.wIY,kind:s.MethodKind.Unary},generateGrokCollectionDescription:{name:"GenerateGrokCollectionDescription",I:n.ke0,O:n.q1P,kind:s.MethodKind.Unary},listRelatedGrokCollections:{name:"ListRelatedGrokCollections",I:n.zdO,O:n.HwU,kind:s.MethodKind.Unary},listGrokCollectionEmbeddingModels:{name:"ListGrokCollectionEmbeddingModels",I:n.Q_u,O:n.Sj7,kind:s.MethodKind.Unary},listGrokCollectionDocuments:{name:"ListGrokCollectionDocuments",I:n.RAf,O:n.nYQ,kind:s.MethodKind.Unary},batchGetGrokCollectionDocuments:{name:"BatchGetGrokCollectionDocuments",I:n.bJ2,O:n.TOY,kind:s.MethodKind.Unary},addGrokCollectionDocument:{name:"AddGrokCollectionDocument",I:n.zyk,O:n.LLT,kind:s.MethodKind.Unary},updateGrokCollectionDocument:{name:"UpdateGrokCollectionDocument",I:n.X0z,O:n.zxO,kind:s.MethodKind.Unary},removeGrokCollectionDocument:{name:"RemoveGrokCollectionDocument",I:n.GsS,O:n.YjQ,kind:s.MethodKind.Unary},reindexGrokCollectionDocument:{name:"ReindexGrokCollectionDocument",I:n.h$Z,O:n.lWu,kind:s.MethodKind.Unary},getGrokApiKeyAccess:{name:"GetGrokApiKeyAccess",I:n.Muw,O:n.OFG,kind:s.MethodKind.Unary},getGrokTeamWatermarking:{name:"GetGrokTeamWatermarking",I:n.Il7,O:n.SMz,kind:s.MethodKind.Unary},setGrokTeamWatermarking:{name:"SetGrokTeamWatermarking",I:n.iiN,O:n.Qdp,kind:s.MethodKind.Unary},getGrokTeamZdr:{name:"GetGrokTeamZdr",I:n.sLc,O:n.CC0,kind:s.MethodKind.Unary},setGrokTeamZdr:{name:"SetGrokTeamZdr",I:n.S8y,O:n.QjN,kind:s.MethodKind.Unary},getGrokApiKeyPropagation:{name:"GetGrokApiKeyPropagation",I:n.yED,O:n._2X,kind:s.MethodKind.Unary},createGrokApiKey:{name:"CreateGrokApiKey",I:n.m5V,O:n.MSw,kind:s.MethodKind.Unary},deleteGrokApiKey:{name:"DeleteGrokApiKey",I:n.nG3,O:n.T78,kind:s.MethodKind.Unary},updateGrokApiKey:{name:"UpdateGrokApiKey",I:n.laE,O:n.TCm,kind:s.MethodKind.Unary},setGrokApiKeyAcls:{name:"SetGrokApiKeyAcls",I:n.RDD,O:n.lmF,kind:s.MethodKind.Unary},rotateGrokApiKey:{name:"RotateGrokApiKey",I:n.pTw,O:n.DZc,kind:s.MethodKind.Unary},getGrokAdminFeatureControls:{name:"GetGrokAdminFeatureControls",I:n._NS,O:n.eTm,kind:s.MethodKind.Unary},updateGrokAdminFeatureControls:{name:"UpdateGrokAdminFeatureControls",I:n.XKz,O:n.H7s,kind:s.MethodKind.Unary},getGrokUserDataControls:{name:"GetGrokUserDataControls",I:n.eNQ,O:n.efP,kind:s.MethodKind.Unary},updateGrokUserDataControls:{name:"UpdateGrokUserDataControls",I:n.$yS,O:n.XrM,kind:s.MethodKind.Unary},listGrokRequestLogs:{name:"ListGrokRequestLogs",I:n.dU3,O:n.pxp,kind:s.MethodKind.Unary},listGrokRequestLogBodies:{name:"ListGrokRequestLogBodies",I:n._Yf,O:n.g9i,kind:s.MethodKind.Unary},listGrokVoiceConversations:{name:"ListGrokVoiceConversations",I:n.Vg9,O:n.xXb,kind:s.MethodKind.Unary},getGrokAdminTeamSettings:{name:"GetGrokAdminTeamSettings",I:n.SuU,O:n.yms,kind:s.MethodKind.Unary},updateGrokAdminTeamSettings:{name:"UpdateGrokAdminTeamSettings",I:n.rCL,O:n.nbk,kind:s.MethodKind.Unary},getGrokAdminOrganizationControls:{name:"GetGrokAdminOrganizationControls",I:n.lxC,O:n.nxh,kind:s.MethodKind.Unary},updateGrokAdminOrganizationControls:{name:"UpdateGrokAdminOrganizationControls",I:n.GKl,O:n.GIW,kind:s.MethodKind.Unary},listGrokAdminGuardrails:{name:"ListGrokAdminGuardrails",I:n.OOr,O:n.iwb,kind:s.MethodKind.Unary},getGrokAdminGuardrail:{name:"GetGrokAdminGuardrail",I:n.nxD,O:n.Hux,kind:s.MethodKind.Unary},createGrokAdminGuardrail:{name:"CreateGrokAdminGuardrail",I:n.ZN0,O:n.DdV,kind:s.MethodKind.Unary},updateGrokAdminGuardrail:{name:"UpdateGrokAdminGuardrail",I:n.uuc,O:n.eo$,kind:s.MethodKind.Unary},removeGrokAdminGuardrail:{name:"RemoveGrokAdminGuardrail",I:n.RJA,O:n.$ph,kind:s.MethodKind.Unary},setGrokAdminGuardrailActive:{name:"SetGrokAdminGuardrailActive",I:n.dhe,O:n.PjD,kind:s.MethodKind.Unary},deactivateGrokAdminGuardrail:{name:"DeactivateGrokAdminGuardrail",I:n.rhR,O:n.RVM,kind:s.MethodKind.Unary},getGrokAdminBlockedUrls:{name:"GetGrokAdminBlockedUrls",I:n.ovf,O:n._oI,kind:s.MethodKind.Unary},uploadGrokAdminBlockedUrls:{name:"UploadGrokAdminBlockedUrls",I:n.fRF,O:n.TkS,kind:s.MethodKind.Unary},deleteGrokAdminBlockedUrls:{name:"DeleteGrokAdminBlockedUrls",I:n.nc6,O:n.Hdd,kind:s.MethodKind.Unary},listGrokAdminOnboardingPrompts:{name:"ListGrokAdminOnboardingPrompts",I:n.cl3,O:n.cf9,kind:s.MethodKind.Unary},createGrokAdminOnboardingPrompt:{name:"CreateGrokAdminOnboardingPrompt",I:n.byf,O:n.vXf,kind:s.MethodKind.Unary},updateGrokAdminOnboardingPrompt:{name:"UpdateGrokAdminOnboardingPrompt",I:n.wOq,O:n.M2G,kind:s.MethodKind.Unary},deleteGrokAdminOnboardingPrompt:{name:"DeleteGrokAdminOnboardingPrompt",I:n.aW7,O:n._yh,kind:s.MethodKind.Unary},listXaiManagementApiKeys:{name:"ListXaiManagementApiKeys",I:n.ruw,O:n.xAe,kind:s.MethodKind.Unary},createXaiManagementApiKey:{name:"CreateXaiManagementApiKey",I:n.azC,O:n.cSQ,kind:s.MethodKind.Unary},updateXaiManagementApiKey:{name:"UpdateXaiManagementApiKey",I:n.dR6,O:n.P1K,kind:s.MethodKind.Unary},deleteXaiManagementApiKey:{name:"DeleteXaiManagementApiKey",I:n.hSg,O:n.rGX,kind:s.MethodKind.Unary},listXaiManagementApiKeyEndpointAcls:{name:"ListXaiManagementApiKeyEndpointAcls",I:n._Br,O:n.ylO,kind:s.MethodKind.Unary},createOrganizationApiKey:{name:"CreateOrganizationApiKey",I:n.KFb,O:n.WRW,kind:s.MethodKind.Unary},revokeOrganizationApiKey:{name:"RevokeOrganizationApiKey",I:n.W6d,O:n.G0c,kind:s.MethodKind.Unary},listOrganizationApiKeys:{name:"ListOrganizationApiKeys",I:n.bC9,O:n.Xtv,kind:s.MethodKind.Unary},createAutomationWebhookApiKey:{name:"CreateAutomationWebhookApiKey",I:n.nL6,O:n.rEt,kind:s.MethodKind.Unary},createTeamServiceAccount:{name:"CreateTeamServiceAccount",I:n.HYO,O:n.loJ,kind:s.MethodKind.Unary},listTeamServiceAccounts:{name:"ListTeamServiceAccounts",I:n.SMM,O:n.AhK,kind:s.MethodKind.Unary},deleteTeamServiceAccount:{name:"DeleteTeamServiceAccount",I:n.IaO,O:n.WLQ,kind:s.MethodKind.Unary},archiveTeamServiceAccount:{name:"ArchiveTeamServiceAccount",I:n.X2v,O:n.B6m,kind:s.MethodKind.Unary},updateTeamServiceAccount:{name:"UpdateTeamServiceAccount",I:n.Ca8,O:n.m6C,kind:s.MethodKind.Unary},suspendTeamServiceAccount:{name:"SuspendTeamServiceAccount",I:Up,O:Ap,kind:s.MethodKind.Unary},resumeTeamServiceAccount:{name:"ResumeTeamServiceAccount",I:$p,O:Mp,kind:s.MethodKind.Unary},rotateServiceAccountApiKey:{name:"RotateServiceAccountApiKey",I:n.OCy,O:n.sJP,kind:s.MethodKind.Unary},getTeamRepositoriesForServiceAccountScope:{name:"GetTeamRepositoriesForServiceAccountScope",I:n.EwB,O:n.Eav,kind:s.MethodKind.Unary},updateServiceAccountRepoScope:{name:"UpdateServiceAccountRepoScope",I:n.RZf,O:n.d6k,kind:s.MethodKind.Unary},startStepUp:{name:"StartStepUp",I:n.PZt,O:n.tJL,kind:s.MethodKind.Unary},getStepUpStatus:{name:"GetStepUpStatus",I:n.Din,O:n.BMV,kind:s.MethodKind.Unary},describeStepUpLink:{name:"DescribeStepUpLink",I:n._mp,O:n.sX6,kind:s.MethodKind.Unary},confirmStepUpLink:{name:"ConfirmStepUpLink",I:n.$bV,O:n.boh,kind:s.MethodKind.Unary},createUserApiKey:{name:"CreateUserApiKey",I:n.cEg,O:n.Aa9,kind:s.MethodKind.Unary},revokeUserApiKey:{name:"RevokeUserApiKey",I:n.GOY,O:n.yQR,kind:s.MethodKind.Unary},listUserApiKeys:{name:"ListUserApiKeys",I:n.juR,O:n.ZCs,kind:s.MethodKind.Unary},listMemberPersonalApiKeys:{name:"ListMemberPersonalApiKeys",I:n.Cl5,O:n.UEj,kind:s.MethodKind.Unary},revokeMemberPersonalApiKeys:{name:"RevokeMemberPersonalApiKeys",I:n.Gci,O:n.K_N,kind:s.MethodKind.Unary},searchApiKeys:{name:"SearchApiKeys",I:n.C4E,O:n.ya8,kind:s.MethodKind.Unary},listTeamCredentialsFromFormerMembers:{name:"ListTeamCredentialsFromFormerMembers",I:n.F70,O:n.$bL,kind:s.MethodKind.Unary},staffSearchApiKeys:{name:"StaffSearchApiKeys",I:n.S2v,O:n.w9I,kind:s.MethodKind.Unary},staffRevokeApiKey:{name:"StaffRevokeApiKey",I:n.vxR,O:n.bOn,kind:s.MethodKind.Unary},staffSuspendServiceAccount:{name:"StaffSuspendServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffResumeServiceAccount:{name:"StaffResumeServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffArchiveServiceAccount:{name:"StaffArchiveServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffDeleteServiceAccount:{name:"StaffDeleteServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffListOwnerApiKeys:{name:"StaffListOwnerApiKeys",I:n.Ja4,O:n.yY2,kind:s.MethodKind.Unary},staffListServiceAccountApiKeys:{name:"StaffListServiceAccountApiKeys",I:n.ogM,O:n.yY2,kind:s.MethodKind.Unary},listTeamMemberSessions:{name:"ListTeamMemberSessions",I:n.Ifk,O:n.NsN,kind:s.MethodKind.Unary},revokeTeamMemberSession:{name:"RevokeTeamMemberSession",I:n.vDi,O:n.ElN,kind:s.MethodKind.Unary},listOrganizationMemberSessions:{name:"ListOrganizationMemberSessions",I:n.AUt,O:n.NsN,kind:s.MethodKind.Unary},revokeOrganizationMemberSession:{name:"RevokeOrganizationMemberSession",I:n.fOQ,O:n.ElN,kind:s.MethodKind.Unary},createServiceToken:{name:"CreateServiceToken",I:n.C10,O:n.e7b,kind:s.MethodKind.Unary},listServiceTokens:{name:"ListServiceTokens",I:n.v0n,O:n.X1$,kind:s.MethodKind.Unary},listCursorApiKeys:{name:"ListCursorApiKeys",I:n.UkG,O:n.S$9,kind:s.MethodKind.Unary},updateServiceTokenPermissions:{name:"UpdateServiceTokenPermissions",I:n.Fo6,O:n.rA8,kind:s.MethodKind.Unary},revokeServiceToken:{name:"RevokeServiceToken",I:n.yYY,O:n.w$r,kind:s.MethodKind.Unary},rotateServiceToken:{name:"RotateServiceToken",I:n.Rbl,O:n.t8U,kind:s.MethodKind.Unary},listOAuthApplications:{name:"ListOAuthApplications",I:n._2n,O:n.WAf,kind:s.MethodKind.Unary},createOAuthApplication:{name:"CreateOAuthApplication",I:n.XQi,O:n.FGN,kind:s.MethodKind.Unary},updateOAuthApplication:{name:"UpdateOAuthApplication",I:n.yoo,O:n.fzp,kind:s.MethodKind.Unary},rotateOAuthApplicationSecret:{name:"RotateOAuthApplicationSecret",I:n.wid,O:n.MwB,kind:s.MethodKind.Unary},setOAuthApplicationEnabled:{name:"SetOAuthApplicationEnabled",I:n.sy,O:n.uV,kind:s.MethodKind.Unary},deleteOAuthApplication:{name:"DeleteOAuthApplication",I:n.qtO,O:n.eVU,kind:s.MethodKind.Unary},uploadOAuthApplicationLogo:{name:"UploadOAuthApplicationLogo",I:n.P1X,O:n.VxX,kind:s.MethodKind.Unary},listTrustedIssuers:{name:"ListTrustedIssuers",I:n.rd_,O:n.rkz,kind:s.MethodKind.Unary},getAuthApplicationsOwnerGate:{name:"GetAuthApplicationsOwnerGate",I:n.rav,O:n.$bx,kind:s.MethodKind.Unary},createTrustedIssuer:{name:"CreateTrustedIssuer",I:n._Qn,O:n.UzA,kind:s.MethodKind.Unary},updateTrustedIssuer:{name:"UpdateTrustedIssuer",I:n.Ebf,O:n.Huz,kind:s.MethodKind.Unary},setTrustedIssuerEnabled:{name:"SetTrustedIssuerEnabled",I:n.DEp,O:n.zBo,kind:s.MethodKind.Unary},revokeTrustedIssuer:{name:"RevokeTrustedIssuer",I:n.kUF,O:n.OV9,kind:s.MethodKind.Unary},registerTrustedIssuerPublicKey:{name:"RegisterTrustedIssuerPublicKey",I:n.hEC,O:n.XUz,kind:s.MethodKind.Unary},revokeTrustedIssuerPublicKey:{name:"RevokeTrustedIssuerPublicKey",I:n.g7r,O:n.A7H,kind:s.MethodKind.Unary},revokeTrustedIssuerGrants:{name:"RevokeTrustedIssuerGrants",I:n.VDS,O:n.nRh,kind:s.MethodKind.Unary},getOAuthAuthorizationRequest:{name:"GetOAuthAuthorizationRequest",I:n.NEG,O:n.dtn,kind:s.MethodKind.Unary},approveOAuthAuthorizationRequest:{name:"ApproveOAuthAuthorizationRequest",I:n.Wew,O:n.AZo,kind:s.MethodKind.Unary},listAuthorizedApplications:{name:"ListAuthorizedApplications",I:n.aul,O:n.c$T,kind:s.MethodKind.Unary},revokeAuthorizedApplication:{name:"RevokeAuthorizedApplication",I:n.X58,O:n.tXQ,kind:s.MethodKind.Unary},confirmGithubInstallation:{name:"ConfirmGithubInstallation",I:n.tI8,O:n.xpT,kind:s.MethodKind.Unary},updateTeamName:{name:"UpdateTeamName",I:n.l5I,O:n.FsH,kind:s.MethodKind.Unary},uploadTeamIcon:{name:"UploadTeamIcon",I:n.DLo,O:n.zQx,kind:s.MethodKind.Unary},updateTeamIcon:{name:"UpdateTeamIcon",I:n.Hdl,O:n.hHL,kind:s.MethodKind.Unary},updateTeamDashboardAnalyticsSetting:{name:"UpdateTeamDashboardAnalyticsSetting",I:n.CoZ,O:n.YZV,kind:s.MethodKind.Unary},updateTeamOriginSetting:{name:"UpdateTeamOriginSetting",I:n.YgU,O:n.G3W,kind:s.MethodKind.Unary},updateTeamScimRequireUserDirectorySetting:{name:"UpdateTeamScimRequireUserDirectorySetting",I:n.zul,O:n.L5U,kind:s.MethodKind.Unary},getTeamScimRequireUserDirectoryPreview:{name:"GetTeamScimRequireUserDirectoryPreview",I:n.Uto,O:n.EHd,kind:s.MethodKind.Unary},getEffectiveUserAgentStoreSkillsSettings:{name:"GetEffectiveUserAgentStoreSkillsSettings",I:n.hVj,O:n.b$E,kind:s.MethodKind.Unary},updateUserAgentStoreSkillsSettings:{name:"UpdateUserAgentStoreSkillsSettings",I:n.Vry,O:n.nNe,kind:s.MethodKind.Unary},getSlackUserSettings:{name:"GetSlackUserSettings",I:n.e0r,O:n.ewI,kind:s.MethodKind.Unary},updateSlackUserSettings:{name:"UpdateSlackUserSettings",I:n.F5_,O:n.Lt9,kind:s.MethodKind.Unary},setSlackCursorTeam:{name:"SetSlackCursorTeam",I:n.GLj,O:n.deZ,kind:s.MethodKind.Unary},getSlackRepoRoutingRules:{name:"GetSlackRepoRoutingRules",I:n.hE5,O:n.LGY,kind:s.MethodKind.Unary},createSlackRepoRoutingRule:{name:"CreateSlackRepoRoutingRule",I:n.EMn,O:n.QEY,kind:s.MethodKind.Unary},updateSlackRepoRoutingRule:{name:"UpdateSlackRepoRoutingRule",I:n.xcI,O:n.hbx,kind:s.MethodKind.Unary},deleteSlackRepoRoutingRule:{name:"DeleteSlackRepoRoutingRule",I:n.Bz7,O:n.Tfn,kind:s.MethodKind.Unary},getSlackDefaultWorkerRules:{name:"GetSlackDefaultWorkerRules",I:n.eOv,O:n.gpX,kind:s.MethodKind.Unary},setSlackDefaultWorkerRule:{name:"SetSlackDefaultWorkerRule",I:n.dn0,O:n.P7l,kind:s.MethodKind.Unary},deleteSlackDefaultWorkerRule:{name:"DeleteSlackDefaultWorkerRule",I:n.CGB,O:n.sHT,kind:s.MethodKind.Unary},isOnNewPricing:{name:"IsOnNewPricing",I:n.HxK,O:n.jAL,kind:s.MethodKind.Unary},getLinearAuthUrl:{name:"GetLinearAuthUrl",I:n._9N,O:n.wet,kind:s.MethodKind.Unary},connectLinearCallback:{name:"ConnectLinearCallback",I:n.wlK,O:n.Adp,kind:s.MethodKind.Unary},getMicrosoftTeamsLinkContext:{name:"GetMicrosoftTeamsLinkContext",I:n.vDB,O:n.bIf,kind:s.MethodKind.Unary},setMicrosoftTeamsAuth:{name:"SetMicrosoftTeamsAuth",I:n.ak0,O:n.YrR,kind:s.MethodKind.Unary},getLinearStatus:{name:"GetLinearStatus",I:n.xGO,O:n.zOq,kind:s.MethodKind.Unary},disconnectLinear:{name:"DisconnectLinear",I:n.Xqi,O:n.vXd,kind:s.MethodKind.Unary},getLinearTeams:{name:"GetLinearTeams",I:n.v5z,O:n.HMD,kind:s.MethodKind.Unary},getLinearSettings:{name:"GetLinearSettings",I:n.MFi,O:n.C0g,kind:s.MethodKind.Unary},updateLinearTeamSetting:{name:"UpdateLinearTeamSetting",I:n.$H8,O:n.XMd,kind:s.MethodKind.Unary},updateLinearProjectSetting:{name:"UpdateLinearProjectSetting",I:n.tJW,O:n.RYJ,kind:s.MethodKind.Unary},getLinearLabels:{name:"GetLinearLabels",I:n.a3w,O:n.eZU,kind:s.MethodKind.Unary},getLinearIssues:{name:"GetLinearIssues",I:n.PG$,O:n.bBu,kind:s.MethodKind.Unary},batchGetLinearIssueSummaries:{name:"BatchGetLinearIssueSummaries",I:n.aFD,O:n.W5r,kind:s.MethodKind.Unary},getXaiTeamLinkStatus:{name:"GetXaiTeamLinkStatus",I:n.$TS,O:n.$0p,kind:s.MethodKind.Unary},startXaiTeamLink:{name:"StartXaiTeamLink",I:n.ptw,O:n.zlM,kind:s.MethodKind.Unary},confirmXaiTeamLink:{name:"ConfirmXaiTeamLink",I:n.bWR,O:n.FQR,kind:s.MethodKind.Unary},cancelXaiTeamLinkProposal:{name:"CancelXaiTeamLinkProposal",I:n.pAq,O:n.LOM,kind:s.MethodKind.Unary},unlinkXaiTeam:{name:"UnlinkXaiTeam",I:n.GTA,O:n.ev7,kind:s.MethodKind.Unary},getXaiCursorTeamMergeStatus:{name:"GetXaiCursorTeamMergeStatus",I:$e,O:Me,kind:s.MethodKind.Unary},getXaiCursorTeamMembershipPreview:{name:"GetXaiCursorTeamMembershipPreview",I:De,O:Fe,kind:s.MethodKind.Unary},updateXaiCursorTeamMemberRoles:{name:"UpdateXaiCursorTeamMemberRoles",I:je,O:He,kind:s.MethodKind.Unary},startXaiCursorTeamMerge:{name:"StartXaiCursorTeamMerge",I:We,O:Qe,kind:s.MethodKind.Unary},getXaiCursorTeamMergeGrokTeams:{name:"GetXaiCursorTeamMergeGrokTeams",I:Ve,O:Ye,kind:s.MethodKind.Unary},selectXaiCursorTeamMergeGrokTeam:{name:"SelectXaiCursorTeamMergeGrokTeam",I:Ze,O:tn,kind:s.MethodKind.Unary},confirmXaiCursorTeamMerge:{name:"ConfirmXaiCursorTeamMerge",I:rn,O:on,kind:s.MethodKind.Unary},prepareXaiCursorTeamMergeCheckout:{name:"PrepareXaiCursorTeamMergeCheckout",I:an,O:un,kind:s.MethodKind.Unary},unprepareXaiCursorTeamMergeCheckout:{name:"UnprepareXaiCursorTeamMergeCheckout",I:cn,O:ln,kind:s.MethodKind.Unary},finalizeXaiCursorTeamMergeCheckout:{name:"FinalizeXaiCursorTeamMergeCheckout",I:mn,O:fn,kind:s.MethodKind.Unary},ensureXaiCursorTeamForMerge:{name:"EnsureXaiCursorTeamForMerge",I:dn,O:pn,kind:s.MethodKind.Unary},getXaiCursorTeamMergePrepaidPreview:{name:"GetXaiCursorTeamMergePrepaidPreview",I:hn,O:gn,kind:s.MethodKind.Unary},cancelXaiCursorTeamMergeProposal:{name:"CancelXaiCursorTeamMergeProposal",I:_n,O:Jn,kind:s.MethodKind.Unary},transferXaiCredits:{name:"TransferXaiCredits",I:n.hDl,O:n.hWK,kind:s.MethodKind.Unary},grantXaiSubscription:{name:"GrantXaiSubscription",I:Gp,O:Lp,kind:s.MethodKind.Unary},getXaiCreditTransferStatus:{name:"GetXaiCreditTransferStatus",I:n.yq2,O:n.hWK,kind:s.MethodKind.Unary},listXaiCreditTransfers:{name:"ListXaiCreditTransfers",I:n.R_i,O:n.hN$,kind:s.MethodKind.Unary},getPagerDutyAuthUrl:{name:"GetPagerDutyAuthUrl",I:n.Ig_,O:n.Esv,kind:s.MethodKind.Unary},connectPagerDutyCallback:{name:"ConnectPagerDutyCallback",I:n.ecT,O:n.YdR,kind:s.MethodKind.Unary},getPagerDutyStatus:{name:"GetPagerDutyStatus",I:n.JmO,O:n.bUD,kind:s.MethodKind.Unary},getPagerDutyServices:{name:"GetPagerDutyServices",I:n.bo4,O:n.twU,kind:s.MethodKind.Unary},disconnectPagerDuty:{name:"DisconnectPagerDuty",I:n.dBq,O:n.VS,kind:s.MethodKind.Unary},getJiraInstallUrl:{name:"GetJiraInstallUrl",I:n.m8H,O:n.G4o,kind:s.MethodKind.Unary},linkJiraInstallation:{name:"LinkJiraInstallation",I:n.Uao,O:n.Gdv,kind:s.MethodKind.Unary},getJiraStatus:{name:"GetJiraStatus",I:n.CJ0,O:n.qZs,kind:s.MethodKind.Unary},listJiraInstallations:{name:"ListJiraInstallations",I:n.LuE,O:n.VG3,kind:s.MethodKind.Unary},getBitbucketForgeStatus:{name:"GetBitbucketForgeStatus",I:n.y90,O:n.YmN,kind:s.MethodKind.Unary},disconnectJira:{name:"DisconnectJira",I:n.KQv,O:n.S0I,kind:s.MethodKind.Unary},disconnectBitbucketForge:{name:"DisconnectBitbucketForge",I:n.I5D,O:n.e0h,kind:s.MethodKind.Unary},getBitbucketForgeInstallationGrants:{name:"GetBitbucketForgeInstallationGrants",I:n.DfW,O:n.lpX,kind:s.MethodKind.Unary},grantBitbucketForgeInstallation:{name:"GrantBitbucketForgeInstallation",I:n.UEe,O:n.I67,kind:s.MethodKind.Unary},revokeBitbucketForgeInstallation:{name:"RevokeBitbucketForgeInstallation",I:n.Eh$,O:n.aIo,kind:s.MethodKind.Unary},getJiraProjects:{name:"GetJiraProjects",I:n.k0s,O:n.EGh,kind:s.MethodKind.Unary},getJiraTeamSettings:{name:"GetJiraTeamSettings",I:n.WCk,O:n.CyC,kind:s.MethodKind.Unary},updateJiraTeamSettings:{name:"UpdateJiraTeamSettings",I:n.Fuf,O:n.HCj,kind:s.MethodKind.Unary},getJiraRoutingRules:{name:"GetJiraRoutingRules",I:n.XUt,O:n.ZU4,kind:s.MethodKind.Unary},createJiraRoutingRule:{name:"CreateJiraRoutingRule",I:n.OoP,O:n.gZI,kind:s.MethodKind.Unary},updateJiraRoutingRule:{name:"UpdateJiraRoutingRule",I:n.zFs,O:n.bQQ,kind:s.MethodKind.Unary},deleteJiraRoutingRule:{name:"DeleteJiraRoutingRule",I:n.XeB,O:n.zNr,kind:s.MethodKind.Unary},linkJiraUser:{name:"LinkJiraUser",I:n.DWb,O:n.Fi2,kind:s.MethodKind.Unary},listJiraUserLinks:{name:"ListJiraUserLinks",I:n.KaV,O:n.ySt,kind:s.MethodKind.Unary},unlinkJiraUser:{name:"UnlinkJiraUser",I:n.ceB,O:n.WXO,kind:s.MethodKind.Unary},deleteBedrockIamRole:{name:"DeleteBedrockIamRole",I:n.o0f,O:n.mTO,kind:s.MethodKind.Unary},unlinkSlackAccess:{name:"UnlinkSlackAccess",I:n.h0F,O:n.dTt,kind:s.MethodKind.Unary},listSlackLinkedWorkspaces:{name:"ListSlackLinkedWorkspaces",I:n.N8I,O:n.pZm,kind:s.MethodKind.Unary},setSandAutomationSlackWorkspace:{name:"SetSandAutomationSlackWorkspace",I:Ef,O:Cf,kind:s.MethodKind.Unary},getSlackLinkPreview:{name:"GetSlackLinkPreview",I:n.aew,O:n.gjm,kind:s.MethodKind.Unary},listSlackConversations:{name:"ListSlackConversations",I:n.iHk,O:n.gsv,kind:s.MethodKind.Unary},listSlackConnectedWorkspaces:{name:"ListSlackConnectedWorkspaces",I:n.vV7,O:n.vcR,kind:s.MethodKind.Unary},listOrganizationSlackConnectedWorkspaces:{name:"ListOrganizationSlackConnectedWorkspaces",I:n.quH,O:n.eK8,kind:s.MethodKind.Unary},listMicrosoftTeamsChannels:{name:"ListMicrosoftTeamsChannels",I:n.wLf,O:n.Sot,kind:s.MethodKind.Unary},getSlackConversationsByIds:{name:"GetSlackConversationsByIds",I:n.BaG,O:n.zYR,kind:s.MethodKind.Unary},logSlackbotAuthConversionFunnel:{name:"LogSlackbotAuthConversionFunnel",I:n.HOD,O:n.pQL,kind:s.MethodKind.Unary},logClickedConnectSlack:{name:"LogClickedConnectSlack",I:n.Not,O:n.T0x,kind:s.MethodKind.Unary},checkUserApiKeyAccess:{name:"CheckUserApiKeyAccess",I:n.QKN,O:n.wmq,kind:s.MethodKind.Unary},isAllowedFreeTrialUsage:{name:"IsAllowedFreeTrialUsage",I:n.p$r,O:n.Jag,kind:s.MethodKind.Unary},isNextSetupRunFree:{name:"IsNextSetupRunFree",I:n.vfb,O:n.$8m,kind:s.MethodKind.Unary},completedLinkSlackAccount:{name:"CompletedLinkSlackAccount",I:n.wm7,O:n.O$A,kind:s.MethodKind.Unary},notifyBugbotTeamAdmins:{name:"NotifyBugbotTeamAdmins",I:n.anf,O:n.WJW,kind:s.MethodKind.Unary},getAdminNotificationStatus:{name:"GetAdminNotificationStatus",I:n.gJU,O:n.mib,kind:s.MethodKind.Unary},optOutNewPricing:{name:"OptOutNewPricing",I:n.P4,O:n.HdK,kind:s.MethodKind.Unary},submitFeedback:{name:"SubmitFeedback",I:n.h5c,O:n.b9h,kind:s.MethodKind.Unary},submitFeedbackAnon:{name:"SubmitFeedbackAnon",I:n.h5c,O:n.b9h,kind:s.MethodKind.Unary},submitRepositoryProtectionClaim:{name:"SubmitRepositoryProtectionClaim",I:n.zuj,O:n.NMG,kind:s.MethodKind.Unary},activateRepositoryProtectionInvite:{name:"ActivateRepositoryProtectionInvite",I:n.bo5,O:n.xWW,kind:s.MethodKind.Unary},getActiveOffboardingBanner:{name:"GetActiveOffboardingBanner",I:n.pg$,O:n.fSY,kind:s.MethodKind.Unary},clientAction:{name:"ClientAction",I:n.H5i,O:n.zah,kind:s.MethodKind.Unary},listUsageAlerts:{name:"ListUsageAlerts",I:n.wfW,O:n.UB9,kind:s.MethodKind.Unary},createUsageAlerts:{name:"CreateUsageAlerts",I:n.Q1P,O:n.kJb,kind:s.MethodKind.Unary},deleteUsageAlerts:{name:"DeleteUsageAlerts",I:n.LME,O:n.rJY,kind:s.MethodKind.Unary},updateUsageAlerts:{name:"UpdateUsageAlerts",I:n.D3G,O:n.rew,kind:s.MethodKind.Unary},requestIndividualLimitsOptOut:{name:"RequestIndividualLimitsOptOut",I:n.JrS,O:n.HJo,kind:s.MethodKind.Unary},listMarketplacePlugins:{name:"ListMarketplacePlugins",I:n.ZMX,O:n.vEP,kind:s.MethodKind.Unary},listPublisherPublicPlugins:{name:"ListPublisherPublicPlugins",I:n.nMU,O:n.lqq,kind:s.MethodKind.Unary},getUserProfile:{name:"GetUserProfile",I:n.mH6,O:n.CZF,kind:s.MethodKind.Unary},updateUserProfile:{name:"UpdateUserProfile",I:n.LjR,O:n.Hoz,kind:s.MethodKind.Unary},claimUserProfileHandle:{name:"ClaimUserProfileHandle",I:n.iOH,O:n.g5C,kind:s.MethodKind.Unary},getPublicProfileByHandle:{name:"GetPublicProfileByHandle",I:n.dwF,O:n.t5n,kind:s.MethodKind.Unary},getViewableProfileByHandle:{name:"GetViewableProfileByHandle",I:n.hsE,O:n.vuk,kind:s.MethodKind.Unary},getTeamMemberProfileByHandle:{name:"GetTeamMemberProfileByHandle",I:n.jcw,O:n.X5_,kind:s.MethodKind.Unary},getProfileOriginContributions:{name:"GetProfileOriginContributions",I:n.kSp,O:n.O5b,kind:s.MethodKind.Unary},getPlugin:{name:"GetPlugin",I:n.vVx,O:n.fAb,kind:s.MethodKind.Unary},startPluginMcpConnectorSignIn:{name:"StartPluginMcpConnectorSignIn",I:n.sGA,O:n.MmU,kind:s.MethodKind.Unary},createPlugin:{name:"CreatePlugin",I:n.hzU,O:n.rfl,kind:s.MethodKind.Unary},updatePluginMcpConfig:{name:"UpdatePluginMcpConfig",I:ea,O:na,kind:s.MethodKind.Unary},publishPlugin:{name:"PublishPlugin",I:n.qkO,O:n.YPJ,kind:s.MethodKind.Unary},unpublishPlugin:{name:"UnpublishPlugin",I:n.VJo,O:n.ZuH,kind:s.MethodKind.Unary},parseGitHubRepoForPlugins:{name:"ParseGitHubRepoForPlugins",I:n.ggh,O:n.nXe,kind:s.MethodKind.Unary},parsePluginPublisherRepoInternal:{name:"ParsePluginPublisherRepoInternal",I:n.VWM,O:n.HiH,kind:s.MethodKind.Unary},previewReindexPluginRepoInternal:{name:"PreviewReindexPluginRepoInternal",I:n.dOz,O:n.smL,kind:s.MethodKind.Unary},applyReindexPluginRepoInternal:{name:"ApplyReindexPluginRepoInternal",I:n.flJ,O:n.SZm,kind:s.MethodKind.Unary},previewMigrateReindexPluginRepoInternal:{name:"PreviewMigrateReindexPluginRepoInternal",I:n.Q66,O:n.b48,kind:s.MethodKind.Unary},applyMigrateReindexPluginRepoInternal:{name:"ApplyMigrateReindexPluginRepoInternal",I:n.GJd,O:n.LmS,kind:s.MethodKind.Unary},updateTeamMarketplaceOriginDistributionInternal:{name:"UpdateTeamMarketplaceOriginDistributionInternal",I:n.WFw,O:n.gqu,kind:s.MethodKind.Unary},getXaiEmailEligibilityInternal:{name:"GetXaiEmailEligibilityInternal",I:wn,O:yn,kind:s.MethodKind.Unary},getUserServedPlanInternal:{name:"GetUserServedPlanInternal",I:n.SC5,O:n._kg,kind:s.MethodKind.Unary},lookupGrokAccountsByXUserInternal:{name:"LookupGrokAccountsByXUserInternal",I:Sn,O:Bn,kind:s.MethodKind.Unary},createSupportImpersonationSessionInternal:{name:"CreateSupportImpersonationSessionInternal",I:n.Cbz,O:n.Gf$,kind:s.MethodKind.Unary},revokeSupportImpersonationSessionsInternal:{name:"RevokeSupportImpersonationSessionsInternal",I:n.$qF,O:n.JUz,kind:s.MethodKind.Unary},removeOrganizationMemberInternal:{name:"RemoveOrganizationMemberInternal",I:n.sw6,O:n.qVu,kind:s.MethodKind.Unary},linkOrganizationTeamToXaiInternal:{name:"LinkOrganizationTeamToXaiInternal",I:n.AkD,O:n.w2N,kind:s.MethodKind.Unary},submitPluginForApproval:{name:"SubmitPluginForApproval",I:n.vCC,O:n.D7h,kind:s.MethodKind.Unary},approvePlugin:{name:"ApprovePlugin",I:n.c2n,O:n.ISv,kind:s.MethodKind.Unary},rejectPlugin:{name:"RejectPlugin",I:n.WZo,O:n.oGE,kind:s.MethodKind.Unary},listUserPluginInstalls:{name:"ListUserPluginInstalls",I:n.OHt,O:n.UgB,kind:s.MethodKind.Unary},installUserPlugin:{name:"InstallUserPlugin",I:n.Bi3,O:n.jsr,kind:s.MethodKind.Unary},updateUserPluginInstall:{name:"UpdateUserPluginInstall",I:n.__V,O:n.c3q,kind:s.MethodKind.Unary},uninstallUserPlugin:{name:"UninstallUserPlugin",I:n.w66,O:n.Mmr,kind:s.MethodKind.Unary},getTeamPluginPopularity:{name:"GetTeamPluginPopularity",I:n.LGu,O:n.PnF,kind:s.MethodKind.Unary},recordConnectorPolicyBlocked:{name:"RecordConnectorPolicyBlocked",I:n.QL_,O:n.iMY,kind:s.MethodKind.Unary},getTeamPluginPrimitiveUsage:{name:"GetTeamPluginPrimitiveUsage",I:n.i9d,O:n.sev,kind:s.MethodKind.Unary},listTeamAvailableMarketplacePlugins:{name:"ListTeamAvailableMarketplacePlugins",I:n.$_i,O:n.B0l,kind:s.MethodKind.Unary},getTeamPinnedMarketplacePlugins:{name:"GetTeamPinnedMarketplacePlugins",I:n.ax8,O:n._lt,kind:s.MethodKind.Unary},updateTeamPinnedMarketplacePlugins:{name:"UpdateTeamPinnedMarketplacePlugins",I:n.hLv,O:n.VCH,kind:s.MethodKind.Unary},installTeamPlugin:{name:"InstallTeamPlugin",I:n.Jjf,O:n.hsS,kind:s.MethodKind.Unary},updateTeamPluginInstall:{name:"UpdateTeamPluginInstall",I:n.iRP,O:n.y13,kind:s.MethodKind.Unary},uninstallTeamPlugin:{name:"UninstallTeamPlugin",I:n.m,O:n.E3F,kind:s.MethodKind.Unary},getEffectiveUserPlugins:{name:"GetEffectiveUserPlugins",I:n.EwF,O:n.KhO,kind:s.MethodKind.Unary},downloadPluginContent:{name:"DownloadPluginContent",I:n.m_x,O:n.EPm,kind:s.MethodKind.ServerStreaming},listInstalledPlugins:{name:"ListInstalledPlugins",I:n.AB7,O:n.g7m,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},getInstalledPluginDetail:{name:"GetInstalledPluginDetail",I:n.E8o,O:n.C17,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},listTeamPluginsTable:{name:"ListTeamPluginsTable",I:n.IJt,O:n.pNK,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},listStorefrontPlugins:{name:"ListStorefrontPlugins",I:n.W22,O:n.SwX,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},resolvePluginsByRef:{name:"ResolvePluginsByRef",I:n.WvV,O:n.UgI,kind:s.MethodKind.Unary},listMarketplaces:{name:"ListMarketplaces",I:n.iPX,O:n.A8F,kind:s.MethodKind.Unary},addMarketplace:{name:"AddMarketplace",I:n.Y9_,O:n.CeW,kind:s.MethodKind.Unary},getOrCreateDefaultTeamMarketplace:{name:"GetOrCreateDefaultTeamMarketplace",I:n.q$3,O:n.mht,kind:s.MethodKind.Unary},updateMarketplace:{name:"UpdateMarketplace",I:n.UJO,O:n.Cel,kind:s.MethodKind.Unary},removeMarketplace:{name:"RemoveMarketplace",I:n.Bqo,O:n.PQd,kind:s.MethodKind.Unary},refreshMarketplace:{name:"RefreshMarketplace",I:n.YDo,O:n.cBR,kind:s.MethodKind.Unary},reindexAndApplyTeamMarketplaceChanges:{name:"ReindexAndApplyTeamMarketplaceChanges",I:n.BRM,O:n.loc,kind:s.MethodKind.Unary},registerMarketplaceAndPlugins:{name:"RegisterMarketplaceAndPlugins",I:n.Dxc,O:n.ZHm,kind:s.MethodKind.Unary},updateTeamMarketplaceConfig:{name:"UpdateTeamMarketplaceConfig",I:n.Vpq,O:n.vfz,kind:s.MethodKind.Unary},setTeamMarketplaceRepository:{name:"SetTeamMarketplaceRepository",I:n.kMn,O:n.YOY,kind:s.MethodKind.Unary},setMarketplaceOriginDistribution:{name:"SetMarketplaceOriginDistribution",I:n.xHb,O:n.fxk,kind:s.MethodKind.Unary},getMarketplaceOriginDistributionStatus:{name:"GetMarketplaceOriginDistributionStatus",I:n.pUz,O:n.hHr,kind:s.MethodKind.Unary},setTeamMarketplacePluginPolicies:{name:"SetTeamMarketplacePluginPolicies",I:n.rJW,O:n.RZJ,kind:s.MethodKind.Unary},completeSharepointOauth:{name:"CompleteSharepointOauth",I:n.vJq,O:n.PaT,kind:s.MethodKind.Unary},getTeamSharepointConnector:{name:"GetTeamSharepointConnector",I:n.FO$,O:n.hFv,kind:s.MethodKind.Unary},disconnectTeamSharepoint:{name:"DisconnectTeamSharepoint",I:n.sg4,O:n.a3K,kind:s.MethodKind.Unary},setTeamSharepointAllowedSites:{name:"SetTeamSharepointAllowedSites",I:n.kau,O:n.YMP,kind:s.MethodKind.Unary},setTeamMarketplacePluginPolicyVariables:{name:"SetTeamMarketplacePluginPolicyVariables",I:n.sst,O:n.Kfp,kind:s.MethodKind.Unary},saveTeamPluginServerSettings:{name:"SaveTeamPluginServerSettings",I:n.v35,O:n.pdK,kind:s.MethodKind.Unary},linkPluginsToTeamMarketplace:{name:"LinkPluginsToTeamMarketplace",I:n.PuH,O:n.n1r,kind:s.MethodKind.Unary},unlinkPluginsFromTeamMarketplace:{name:"UnlinkPluginsFromTeamMarketplace",I:n.nun,O:n.bzo,kind:s.MethodKind.Unary},previewTeamMarketplaceMcpImpact:{name:"PreviewTeamMarketplaceMcpImpact",I:ia,O:la,kind:s.MethodKind.Unary},getManagedSkills:{name:"GetManagedSkills",I:n.X8g,O:n.p_E,kind:s.MethodKind.Unary},getCursorUserState:{name:"GetCursorUserState",I:n.y4P,O:n.WY9,kind:s.MethodKind.Unary},setJobData:{name:"SetJobData",I:n.B$8,O:n.JgL,kind:s.MethodKind.Unary},listFinancialConnections:{name:"ListFinancialConnections",I:n.mbE,O:n.y5v,kind:s.MethodKind.Unary},listFinancialAccounts:{name:"ListFinancialAccounts",I:n.bHh,O:n.jWD,kind:s.MethodKind.Unary},deleteFinancialConnection:{name:"DeleteFinancialConnection",I:n.Yiy,O:n.YY6,kind:s.MethodKind.Unary},startFinancialLink:{name:"StartFinancialLink",I:n.tVV,O:n.zHj,kind:s.MethodKind.Unary},updateBitbucketServerInstanceOauthApp:{name:"UpdateBitbucketServerInstanceOauthApp",I:n.KEO,O:n.qA0,kind:s.MethodKind.Unary},disconnectBitbucketServerAccount:{name:"DisconnectBitbucketServerAccount",I:n.ru_,O:n.dyp,kind:s.MethodKind.Unary},listDashboardApps:{name:"ListDashboardApps",I:n.CCH,O:n.EdW,kind:s.MethodKind.Unary},getDashboardApp:{name:"GetDashboardApp",I:n.hst,O:n.zUO,kind:s.MethodKind.Unary},listAppReviewOverrides:{name:"ListAppReviewOverrides",I:n.upR,O:n.U2t,kind:s.MethodKind.Unary},decideAppReviewOverride:{name:"DecideAppReviewOverride",I:n.ndP,O:n.FRR,kind:s.MethodKind.Unary},revokeAppReviewOverride:{name:"RevokeAppReviewOverride",I:n.HCf,O:n.x6X,kind:s.MethodKind.Unary},grantAppReviewOverride:{name:"GrantAppReviewOverride",I:n.Pt$,O:n.Tmx,kind:s.MethodKind.Unary},listServiceTokenApps:{name:"ListServiceTokenApps",I:n.A_u,O:n.IWi,kind:s.MethodKind.Unary},setServiceTokenApps:{name:"SetServiceTokenApps",I:n.gNG,O:n.QNN,kind:s.MethodKind.Unary},listAppMemberAppsApiKeys:{name:"ListAppMemberAppsApiKeys",I:n.pVr,O:n.jNM,kind:s.MethodKind.Unary},listTeamAppsApiKeys:{name:"ListTeamAppsApiKeys",I:n.l2q,O:n.Lsm,kind:s.MethodKind.Unary},listXaiSessions:{name:"ListXaiSessions",I:n.DJN,O:n.X4T,kind:s.MethodKind.Unary},revokeXaiSession:{name:"RevokeXaiSession",I:n.QAx,O:n._Hq,kind:s.MethodKind.Unary}}}},"../proto/dist/generated/aiserver/v1/docs_pb.js"(t,r,e){e.d(r,{KC:()=>o,ci:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class o extends i{constructor(t){super(),this.prefixUrl="",this.docName="",this.isDifferentPrefixOrigin=!1,this.truePrefixUrl="",this.public=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["DocumentationMetadata|1 prefix_url 9|2 doc_name 9|3 is_different_prefix_origin 8|4 true_prefix_url 9|5 public 8|6 team_id 5?"]}}class a extends i{constructor(t){super(),this.docName="",this.pageUrl="",this.documentationChunk="",this.score=0,this.pageTitle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["DocumentationChunk|1 doc_name 9|2 page_url 9|3 documentation_chunk 9|4 score 2|5 page_title 9"]}}n.proto3},"../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"(t,r,e){e.d(r,{Y:()=>s});var n=e("@bufbuild/protobuf"),s=(0,e("../proto/dist/runtime/compact.js").QT)(n.proto3,"aiserver.v1.","PrivacyMode",[[0,"UNSPECIFIED"],[1,"NO_STORAGE"],[2,"NO_TRAINING"],[3,"USAGE_DATA_TRAINING_ALLOWED"],[4,"USAGE_CODEBASE_TRAINING_ALLOWED"]],1)},"../proto/dist/generated/aiserver/v1/repository_pb.js"(t,r,e){e.d(r,{PT:()=>h,yX:()=>g,bq:()=>p,xq:()=>d,bn:()=>_,se:()=>m,bD:()=>y});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class a extends o{constructor(t){super(),this.indexId="",this.id="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ReflectionData|1 index_id 9|2 id 9|3 summary 9"]}}class u extends o{constructor(t){super(),this.nodeId="",this.stage="",this.content="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["IndexFileData.NodeData|1 node_id 9|2 stage 9|3 content 9|4 summary 9"]}}n.proto3;const c="aiserver.v1.";class l extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return c}}n.proto3,n.proto3,n.proto3;var m=(0,i.QT)(n.proto3,c,"RerankerAlgorithm",[[0,"UNSPECIFIED"],[1,"LULEA"],[2,"UMEA"],[3,"NONE"],[4,"LLAMA"],[5,"STARCODER_V1"],[6,"GPT_3_5_LOGPROBS"],[7,"LULEA_HAIKU"],[8,"COHERE"],[9,"VOYAGE"],[10,"VOYAGE_EMBEDS"],[11,"IDENTITY"],[12,"ADA_EMBEDS"]],1),f=(0,i.QT)(n.proto3,c,"DatabaseProvider",[[0,"UNSPECIFIED"],[1,"AURORA"],[2,"PLANETSCALE"]],1),d=(0,i.QT)(n.proto3,c,"RechunkerChoice",[[0,"RECHUNKER_CHOICE_UNSPECIFIED"],[1,"RECHUNKER_CHOICE_IDENTITY"],[2,"RECHUNKER_CHOICE_600_TOKS"],[3,"RECHUNKER_CHOICE_2400_TOKS"],[4,"RECHUNKER_CHOICE_4000_TOKS"]]);n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3;class p extends l{constructor(t){super(),this.ownerAuthId="",this.accessToken="",this.userRepoOwner="",this.userRepoName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["QueryOnlyRepoAccess|1 owner_auth_id 9|2 access_token 9|3 user_repo_owner 9|4 user_repo_name 9"]}}class h extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["CodeResult|1 code_block #0|2 score 2",s.NG]}}class g extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["FileResult|1 file #0|2 score 2",s.ZH]}}n.proto3,n.proto3,n.proto3;class _ extends l{constructor(t){super(),this.relativeWorkspacePath="",this.remoteUrls=[],this.remoteNames=[],this.repoName="",this.repoOwner="",this.isTracked=!1,this.isLocal=!1,this.workspaceUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["RepositoryInfo|1 relative_workspace_path 9|2 remote_urls 9*|3 remote_names 9*|4 repo_name 9|5 repo_owner 9|6 is_tracked 8|7 is_local 8|8 num_files 5?|9 orthogonal_transform_seed 1?|10 preferred_embedding_model #0?|11 workspace_uri 9|12 preferred_db_provider #1?",s.Nj,f]}}class J extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["NodeResult|1 node #0|2 file #1|3 score 2",u,s.ZH]}}class w extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ReflectionResult|1 reflection #0|2 score 2",a]}}class y extends l{constructor(t){super(),this.topNodes=[],this.reflections=[],this.indexId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SearchRepositoryDeepContextResponse|1 top_nodes #0*|2 reflections #1*|3 index_id 9",J,w]}}n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3},"../proto/dist/generated/aiserver/v1/tools_pb.js"(t,r,e){e.d(r,{$PL:()=>ut,$rP:()=>Wn,AUe:()=>O,Dm_:()=>ur,Faf:()=>D,I8K:()=>cr,KRm:()=>W,MtQ:()=>x,PfC:()=>q,TE4:()=>C,Ue3:()=>T,XaY:()=>y,bR2:()=>N,kWq:()=>Gn,q20:()=>be});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"),u=e("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),c=e("../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"),l=e("../proto/dist/generated/aiserver/v1/repository_pb.js"),m=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),f=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),d=e("../proto/dist/generated/agent/v1/subagents_pb.js"),p=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),h=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),g=e("../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"),_=e("../proto/dist/runtime/compact.js");const J="aiserver.v1.";class w extends _.HL{static get runtime(){return(0,_.kU)(this,"runtime",n.proto3)}static $p(){return J}}var y=(0,_.QT)(n.proto3,J,"ClientSideToolV2",[[0,"UNSPECIFIED"],[1,"READ_SEMSEARCH_FILES"],[3,"RIPGREP_SEARCH"],[5,"READ_FILE"],[6,"LIST_DIR"],[7,"EDIT_FILE"],[8,"FILE_SEARCH"],[9,"SEMANTIC_SEARCH_FULL"],[11,"DELETE_FILE"],[12,"REAPPLY"],[15,"RUN_TERMINAL_COMMAND_V2"],[16,"FETCH_RULES"],[18,"WEB_SEARCH"],[19,"MCP"],[23,"SEARCH_SYMBOLS"],[24,"BACKGROUND_COMPOSER_FOLLOWUP"],[25,"KNOWLEDGE_BASE"],[26,"FETCH_PULL_REQUEST"],[27,"DEEP_SEARCH"],[28,"CREATE_DIAGRAM"],[29,"FIX_LINTS"],[30,"READ_LINTS"],[31,"GO_TO_DEFINITION"],[32,"TASK"],[33,"AWAIT_TASK"],[34,"TODO_READ"],[35,"TODO_WRITE"],[38,"EDIT_FILE_V2"],[39,"LIST_DIR_V2"],[40,"READ_FILE_V2"],[41,"RIPGREP_RAW_SEARCH"],[42,"GLOB_FILE_SEARCH"],[43,"CREATE_PLAN"],[44,"LIST_MCP_RESOURCES"],[45,"READ_MCP_RESOURCE"],[46,"READ_PROJECT"],[47,"UPDATE_PROJECT"],[48,"TASK_V2"],[49,"CALL_MCP_TOOL"],[50,"APPLY_AGENT_DIFF"],[51,"ASK_QUESTION"],[52,"SWITCH_MODE"],[53,"GENERATE_IMAGE"],[54,"COMPUTER_USE"],[55,"WRITE_SHELL_STDIN"],[56,"RECORD_SCREEN"],[57,"WEB_FETCH"],[58,"REPORT_BUGFIX_RESULTS"],[59,"AI_ATTRIBUTION"],[60,"MCP_AUTH"],[61,"REFLECT"],[62,"AWAIT"],[63,"GET_MCP_TOOLS"],[65,"SEND_TO_USER"],[66,"CONNECT_SCM"]],1),S=(0,_.QT)(n.proto3,J,"BuiltinTool",[[0,"UNSPECIFIED"],[1,"SEARCH"],[2,"READ_CHUNK"],[3,"GOTODEF"],[4,"EDIT"],[5,"UNDO_EDIT"],[6,"END"],[7,"NEW_FILE"],[8,"ADD_TEST"],[9,"RUN_TEST"],[10,"DELETE_TEST"],[11,"SAVE_FILE"],[12,"GET_TESTS"],[13,"GET_SYMBOLS"],[14,"SEMANTIC_SEARCH"],[15,"GET_PROJECT_STRUCTURE"],[16,"CREATE_RM_FILES"],[17,"RUN_TERMINAL_COMMANDS"],[18,"NEW_EDIT"],[19,"READ_WITH_LINTER"]],1),q=(0,_.QT)(n.proto3,J,"RunTerminalCommandEndedReason",[[0,"UNSPECIFIED"],[1,"EXECUTION_COMPLETED"],[2,"EXECUTION_ABORTED"],[3,"EXECUTION_FAILED"],[4,"ERROR_OCCURRED_CHECKING_REASON"],[5,"IDLE_TIMEOUT"]],1);class B extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ReapplyParams|1 relative_workspace_path 9"]}}class I extends w{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ApplyAgentDiffParams|1 agent_id 9"]}}class P extends w{constructor(t){super(),this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ReapplyResult|1 diff #0|2 is_applied 8|3 apply_failed 8|4 linter_errors #1*|5 rejected 8?",W,s.bO]}}class b extends w{constructor(t){super(),this.ruleNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["FetchRulesParams|1 rule_names 9*"]}}class R extends w{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["FetchRulesResult|1 rules #0*",s.DX]}}class v extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ReapplyStream"]}}class x extends w{constructor(t){super(),this.clientVisibleErrorMessage="",this.modelVisibleErrorMessage="",this.errorDetails={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ToolResultError|1 client_visible_error_message 9|2 model_visible_error_message 9|3 actual_error_message_only_send_from_client_to_server_never_the_other_way_around_because_that_may_be_a_security_risk 9?|5 edit_file_error_details #0 error_details|6 search_replace_error_details #1 error_details",k,E]}}class k extends w{constructor(t){super(),this.numLinesInFileBeforeEdit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ToolResultError.EditFileError|1 num_lines_in_file_before_edit 5"]}}class E extends w{constructor(t){super(),this.numLinesInFileBeforeEdit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ToolResultError.SearchReplaceError|1 num_lines_in_file_before_edit 5"]}}class C extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.params={case:void 0},this.toolCallId="",this.name="",this.isStreaming=!1,this.isLastMessage=!1,this.internal=!1,this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ClientSideToolV2Call|1 tool #0|2 read_semsearch_files_params #1 params|5 ripgrep_search_params #2 params|8 read_file_params #3 params|12 list_dir_params #4 params|13 edit_file_params #5 params|16 file_search_params #6 params|17 semantic_search_full_params #7 params|19 delete_file_params #8 params|20 reapply_params #9 params|23 run_terminal_command_v2_params #10 params|24 fetch_rules_params #11 params|26 web_search_params #12 params|27 mcp_params #13 params|31 search_symbols_params #14 params|41 gotodef_params #15 params|32 background_composer_followup_params #16 params|33 knowledge_base_params #17 params|34 fetch_pull_request_params #18 params|35 deep_search_params #19 params|36 create_diagram_params #20 params|37 fix_lints_params #21 params|38 read_lints_params #22 params|42 task_params #23 params|43 await_task_params #24 params|44 todo_read_params #25 params|45 todo_write_params #26 params|50 edit_file_v2_params #27 params|52 list_dir_v2_params #28 params|53 read_file_v2_params #29 params|54 ripgrep_raw_search_params #30 params|55 glob_file_search_params #31 params|56 create_plan_params #32 params|57 list_mcp_resources_params #33 params|58 read_mcp_resource_params #34 params|59 read_project_params #35 params|60 update_project_params #36 params|61 task_v2_params #37 params|62 call_mcp_tool_params #38 params|63 apply_agent_diff_params #39 params|64 ask_question_params #40 params|65 switch_mode_params #41 params|66 computer_use_params #42 params|67 write_shell_stdin_params #43 params|68 record_screen_params #44 params|69 web_fetch_params #45 params|70 report_bugfix_results_params #46 params|71 mcp_auth_params #47 params|72 get_mcp_tools_params #48 params|73 connect_scm_params #49 params|3 tool_call_id 9|6 timeout_ms 1?|9 name 9|14 is_streaming 8|15 is_last_message 8|51 internal 8|10 raw_args 9|48 tool_index 13?|49 model_call_id 9?",y,Ft,pt,mt,at,j,nt,Vt,Zt,B,he,b,Se,Pe,De,Or,Fe,je,Qe,tn,nn,an,mn,hn,$n,Nn,Kn,G,Hn,Yn,Bn,rs,ms,ke,Te,_s,Ss,yn,Ae,I,Is,ks,Ts,i.LL,o.zH,Ms,Ns,Fs,Me,js]}}class T extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.result={case:void 0},this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ClientSideToolV2Result|1 tool #0|2 read_semsearch_files_result #1 result|4 ripgrep_search_result #2 result|6 read_file_result #3 result|9 list_dir_result #4 result|10 edit_file_result #5 result|11 file_search_result #6 result|18 semantic_search_full_result #7 result|20 delete_file_result #8 result|21 reapply_result #9 result|24 run_terminal_command_v2_result #10 result|25 fetch_rules_result #11 result|27 web_search_result #12 result|28 mcp_result #13 result|32 search_symbols_result #14 result|33 background_composer_followup_result #15 result|34 knowledge_base_result #16 result|36 fetch_pull_request_result #17 result|37 deep_search_result #18 result|38 create_diagram_result #19 result|39 fix_lints_result #20 result|40 read_lints_result #21 result|41 gotodef_result #22 result|42 task_result #23 result|43 await_task_result #24 result|44 todo_read_result #25 result|45 todo_write_result #26 result|51 edit_file_v2_result #27 result|52 list_dir_v2_result #28 result|53 read_file_v2_result #29 result|54 ripgrep_raw_search_result #30 result|55 glob_file_search_result #31 result|56 create_plan_result #32 result|57 list_mcp_resources_result #33 result|58 read_mcp_resource_result #34 result|59 read_project_result #35 result|60 update_project_result #36 result|61 task_v2_result #37 result|62 call_mcp_tool_result #38 result|63 apply_agent_diff_result #39 result|64 ask_question_result #40 result|65 switch_mode_result #41 result|66 computer_use_result #42 result|67 generate_image_result #43 result|68 write_shell_stdin_result #44 result|69 record_screen_result #45 result|70 web_fetch_result #46 result|71 report_bugfix_results_result #47 result|72 ai_attribution_result #48 result|73 mcp_auth_result #49 result|74 get_mcp_tools_result #50 result|75 connect_scm_result #51 result|35 tool_call_id 9|8 error #52?|48 model_call_id 9?|49 tool_index 13?|50 attachments #53?",y,Wt,It,ft,ut,H,it,Xt,tr,P,Je,R,qe,ve,Ne,Ke,He,Ve,rn,sn,un,fn,Nr,gn,Mn,Ln,zn,K,Wn,Zn,In,es,fs,Ee,Ue,Js,qs,Sn,$e,a.y$,Rs,Es,Us,u.k4,i.nt,o.Tj,Os,Gs,c.Zc,Ks,Oe,Qs,x,A]}}class U extends w{constructor(t){super(),this.rawMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["NudgeMessage|1 raw_message 9"]}}class A extends w{constructor(t){super(),this.originalTodos=[],this.updatedTodos=[],this.nudgeMessages=[],this.shouldShowTodoWriteReminder=!1,this.todoReminderType=$.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ToolResultAttachments|1 original_todos #0*|2 updated_todos #0*|3 nudge_messages #1*|4 should_show_todo_write_reminder 8|5 todo_reminder_type #2|6 discovery_budget_reminder #3?",Gn,U,$,M]}}var $=(0,_.QT)(n.proto3,J,"ToolResultAttachments.TodoReminderType",[[0,"UNSPECIFIED"],[1,"EVERY_10_TURNS"],[2,"AFTER_EDIT"]],1);class M extends w{constructor(t){super(),this.discoveryRoundsRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ToolResultAttachments.DiscoveryBudgetReminder|1 discovery_rounds_remaining 5|2 discovery_effort 9?"]}}class O extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["StreamedBackPartialToolCall|1 tool #0|2 tool_call_id 9|3 name 9|4 tool_index 13?|5 model_call_id 9?",y]}}class D extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.params={case:void 0},this.name="",this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["StreamedBackToolCall|1 tool #0|2 tool_call_id 9|3 read_semsearch_files_stream #1 params|5 ripgrep_search_stream #2 params|7 read_file_stream #3 params|12 list_dir_stream #4 params|13 edit_file_stream #5 params|14 file_search_stream #6 params|19 semantic_search_full_stream #7 params|21 delete_file_stream #8 params|22 reapply_stream #9 params|25 run_terminal_command_v2_stream #10 params|26 fetch_rules_stream #11 params|28 web_search_stream #12 params|29 mcp_stream #13 params|33 search_symbols_stream #14 params|41 gotodef_stream #15 params|34 background_composer_followup_stream #16 params|35 knowledge_base_stream #17 params|36 fetch_pull_request_stream #18 params|37 deep_search_stream #19 params|38 create_diagram_stream #20 params|39 fix_lints_stream #21 params|40 read_lints_stream #22 params|42 task_stream #23 params|43 await_task_stream #24 params|44 todo_read_stream #25 params|45 todo_write_stream #26 params|52 edit_file_v2_stream #27 params|53 list_dir_v2_stream #28 params|54 read_file_v2_stream #29 params|55 ripgrep_raw_search_stream #30 params|56 glob_file_search_stream #31 params|57 create_plan_stream #32 params|58 list_mcp_resources_stream #33 params|59 read_mcp_resource_stream #34 params|60 read_project_stream #35 params|61 update_project_stream #36 params|62 task_v2_stream #37 params|63 call_mcp_tool_stream #38 params|64 ask_question_stream #39 params|65 switch_mode_stream #40 params|66 computer_use_stream #41 params|67 write_shell_stdin_stream #42 params|68 web_fetch_stream #43 params|69 report_bugfix_results_stream #44 params|70 mcp_auth_stream #45 params|71 connect_scm_stream #46 params|8 name 9|9 raw_args 9|10 error #47?|50 tool_index 13?|51 model_call_id 9?",y,Qt,Lt,dt,lt,et,st,Yt,rr,v,we,ye,Ie,xe,Le,pn,ze,We,Ye,en,on,ln,dn,wn,Dn,Fn,jn,z,Xn,ts,An,is,gs,os,us,ws,Bs,qn,as,xs,Cs,As,$s,Ds,Ls,zs,Vs,x]}}class N extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.params={case:void 0},this.name="",this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["StreamedBackToolCallV2|1 tool #0|2 tool_call_id 9|3 read_semsearch_files_params #1 params|5 ripgrep_search_params #2 params|9 read_file_params #3 params|12 list_dir_params #4 params|13 edit_file_params #5 params|16 file_search_params #6 params|17 semantic_search_full_params #7 params|19 delete_file_params #8 params|20 reapply_params #9 params|23 run_terminal_command_v2_params #10 params|24 fetch_rules_params #11 params|26 web_search_params #12 params|27 mcp_params #13 params|31 search_symbols_params #14 params|41 gotodef_params #15 params|32 background_composer_followup_params #16 params|33 knowledge_base_params #17 params|34 fetch_pull_request_params #18 params|35 deep_search_params #19 params|36 create_diagram_params #20 params|37 fix_lints_params #21 params|38 read_lints_params #22 params|42 task_params #23 params|43 await_task_params #24 params|44 todo_read_params #25 params|45 todo_write_params #26 params|48 edit_file_v2_params #27 params|49 list_dir_v2_params #28 params|61 read_file_v2_params #29 params|62 ripgrep_raw_search_params #30 params|63 glob_file_search_params #31 params|64 create_plan_params #32 params|65 list_mcp_resources_params #33 params|66 read_mcp_resource_params #34 params|67 read_project_params #35 params|68 update_project_params #36 params|69 task_v2_params #37 params|70 call_mcp_tool_params #38 params|71 apply_agent_diff_params #39 params|72 ask_question_params #40 params|73 switch_mode_params #41 params|74 computer_use_params #42 params|75 write_shell_stdin_params #43 params|76 record_screen_params #44 params|77 web_fetch_params #45 params|78 report_bugfix_results_params #46 params|79 mcp_auth_params #47 params|80 get_mcp_tools_params #48 params|81 connect_scm_params #49 params|8 name 9|10 raw_args 9|11 error #50?|50 tool_index 13?|51 model_call_id 9?",y,Ft,pt,mt,at,j,nt,Vt,Zt,B,he,b,Se,Pe,De,Or,Fe,je,Qe,tn,nn,an,mn,hn,$n,Nn,Kn,G,Hn,Yn,Bn,rs,ms,ke,Te,_s,Ss,yn,Ae,I,Is,ks,Ts,i.LL,o.zH,Ms,Ns,Fs,Me,js,x]}}class G extends w{constructor(t){super(),this.relativeWorkspacePath="",this.streamingEdit={case:void 0},this.shouldSendBackLinterErrors=!1,this.resultForModel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["EditFileV2Params|1 relative_workspace_path 9|2 contents_after_edit 9?|3 waiting_for_file_contents 8?|4 text #0 streaming_edit|5 code #1 streaming_edit|6 should_send_back_linter_errors 8|7 diff #2?|8 result_for_model 9|9 streaming_content 9?|10 no_codeblock 8?|11 cloud_agent_edit 8?",L,F,W]}}class L extends w{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["EditFileV2Params.StreamingEditText|1 text 9"]}}class F extends w{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["EditFileV2Params.StreamingEditCode|1 code 9"]}}class K extends w{constructor(t){super(),this.fileWasCreated=!1,this.linterErrors=[],this.sentBackLinterErrors=!1,this.shouldAutoFixLints=!1,this.resultForModel="",this.afterContentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["EditFileV2Result|1 contents_before_edit 9?|9 eol_sequence 9?|11 detected_language 9?|2 file_was_created 8|3 diff #0?|4 rejected 8?|5 linter_errors #1*|6 sent_back_linter_errors 8|8 should_auto_fix_lints 8|7 human_review_v2 #2?|10 result_for_model 9|12 contents_after_edit 9?|13 before_content_id 9?|14 after_content_id 9",W,s.bO,rt]}}class z extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["EditFileV2Stream"]}}class j extends w{constructor(t){super(),this.relativeWorkspacePath="",this.language="",this.blocking=!1,this.contents="",this.lineRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["EditFileParams|1 relative_workspace_path 9|2 language 9|4 blocking 8|3 contents 9|5 instructions 9?|12 should_edit_file_fail_for_large_files 8?|6 old_string 9?|7 new_string 9?|8 allow_multiple_matches 8?|10 use_whitespace_insensitive_fallback 8?|11 use_did_you_mean_fuzzy_match 8?|16 gracefully_handle_recoverable_errors 8?|9 line_ranges #0*|13 notebook_cell_idx 5?|14 is_new_cell 8?|15 cell_language 9?|17 edit_category 9?|18 should_eagerly_process_lints 8?",s.MT]}}class H extends w{constructor(t){super(),this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["EditFileResult|1 diff #0|2 is_applied 8|3 apply_failed 8|4 linter_errors #1*|5 rejected 8?|6 num_matches 5?|7 whitespace_insensitive_fallback_found_match 8?|8 no_match_found_in_line_ranges 8?|11 recoverable_error #2?|9 num_lines_in_file 5?|10 is_subagent_edit 8?|12 diff_became_no_op_due_to_on_save_fixes 8?|13 human_review #3?|14 human_feedback #4?|15 should_eagerly_process_lints 8?|16 human_review_v2 #5?|17 were_all_new_linter_errors_resolved_by_this_edit 8?",W,s.bO,X,Z,tt,rt]}}class W extends w{constructor(t){super(),this.chunks=[],this.editor=Q.UNSPECIFIED,this.hitTimeout=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["EditFileResult.FileDiff|1 chunks #0*|2 editor #1|3 hit_timeout 8",V,Q]}}var Q=(0,_.QT)(n.proto3,J,"EditFileResult.FileDiff.Editor",[[0,"UNSPECIFIED"],[1,"AI"],[2,"HUMAN"]],1);class V extends w{constructor(t){super(),this.diffString="",this.oldStart=0,this.newStart=0,this.oldLines=0,this.newLines=0,this.linesRemoved=0,this.linesAdded=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["EditFileResult.FileDiff.ChunkDiff|1 diff_string 9|2 old_start 5|3 new_start 5|4 old_lines 5|5 new_lines 5|6 lines_removed 5|7 lines_added 5"]}}class X extends w{constructor(t){super(),this.errorType=Y.UNSPECIFIED,this.modelMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["EditFileResult.RecoverableError|1 error_type #0|2 model_message 9",Y]}}var Y=(0,_.QT)(n.proto3,J,"EditFileResult.RecoverableError.RecoverableErrorType",[[0,"UNSPECIFIED"],[1,"SEARCH_STRING_NOT_FOUND"],[2,"AMBIGUOUS_SEARCH_STRING"]],1);class Z extends w{constructor(t){super(),this.isEditAccepted=!1,this.textResult="",this.stopAndGetNewUserInput=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["EditFileResult.EditFileHumanReview|1 is_edit_accepted 8|2 text_result 9|3 stop_and_get_new_user_input 8"]}}class tt extends w{constructor(t){super(),this.selectedOption="",this.feedbackText="",this.submitFeedbackAsNewMessage=!1,this.bubbleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["EditFileResult.HumanFeedback|1 selected_option 9|2 feedback_text 9|3 submit_feedback_as_new_message 8|4 bubble_id 9"]}}class rt extends w{constructor(t){super(),this.selectedOption="",this.feedbackText="",this.submitFeedbackAsNewMessage=!1,this.bubbleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["HumanReview|1 selected_option 9|2 feedback_text 9|3 submit_feedback_as_new_message 8|4 bubble_id 9"]}}class et extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["EditFileStream"]}}class nt extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ToolCallFileSearchParams|1 query 9"]}}class st extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["ToolCallFileSearchStream|1 query 9"]}}class it extends w{constructor(t){super(),this.files=[],this.numResults=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["ToolCallFileSearchResult|1 files #0*|2 limit_hit 8?|3 num_results 5",ot]}}class ot extends w{constructor(t){super(),this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["ToolCallFileSearchResult.File|1 uri 9"]}}class at extends w{constructor(t){super(),this.directoryPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["ListDirParams|1 directory_path 9"]}}class ut extends w{constructor(t){super(),this.files=[],this.directoryRelativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["ListDirResult|1 files #0*|2 directory_relative_workspace_path 9",ct]}}class ct extends w{constructor(t){super(),this.name="",this.isDirectory=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["ListDirResult.File|1 name 9|2 is_directory 8|3 size 3?|4 last_modified #0?|5 num_children 5?|6 num_lines 5?",n.Timestamp]}}class lt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["ListDirStream"]}}class mt extends w{constructor(t){super(),this.relativeWorkspacePath="",this.readEntireFile=!1,this.fileIsAllowedToBeReadEntirely=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["ReadFileParams|1 relative_workspace_path 9|2 read_entire_file 8|3 start_line_one_indexed 5?|4 end_line_one_indexed_inclusive 5?|5 file_is_allowed_to_be_read_entirely 8|6 max_lines 5?|7 max_chars 5?|8 min_lines 5?"]}}class ft extends w{constructor(t){super(),this.contents="",this.didDowngradeToLineRange=!1,this.didShortenLineRange=!1,this.didSetDefaultLineRange=!1,this.relativeWorkspacePath="",this.didShortenCharRange=!1,this.matchingCursorRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ReadFileResult|1 contents 9|2 did_downgrade_to_line_range 8|3 did_shorten_line_range 8|4 did_set_default_line_range 8|5 full_file_contents 9?|6 outline 9?|7 start_line_one_indexed 5?|8 end_line_one_indexed_inclusive 5?|9 relative_workspace_path 9|10 did_shorten_char_range 8|11 read_full_file 8?|12 total_lines 5?|13 matching_cursor_rules #0*|14 file_git_context #1",s.DX,s.fL]}}class dt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["ReadFileStream"]}}class pt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["RipgrepSearchParams|1 options #0|2 pattern_info #1",_t,ht]}}class ht extends w{constructor(t){super(),this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["RipgrepSearchParams.IPatternInfoProto|1 pattern 9|2 is_reg_exp 8?|3 is_word_match 8?|4 word_separators 9?|5 is_multiline 8?|6 is_unicode 8?|7 is_case_sensitive 8?|8 notebook_info #0|9 pattern_was_escaped 8?",gt]}}class gt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["RipgrepSearchParams.IPatternInfoProto.INotebookPatternInfoProto|1 is_in_notebook_markdown_input 8?|2 is_in_notebook_markdown_preview 8?|3 is_in_notebook_cell_input 8?|4 is_in_notebook_cell_output 8?"]}}class _t extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto|1 preview_options #0|2 file_encoding 9?|3 surrounding_context 5?|4 is_smart_case 8?|5 notebook_search_config #1|6 exclude_pattern #2|7 include_pattern #3|8 expand_patterns 8?|9 max_results 5?|10 max_file_size 5?|11 disregard_ignore_files 8?|12 disregard_global_ignore_files 8?|13 disregard_parent_ignore_files 8?|14 disregard_exclude_settings 8?|15 disregard_search_exclude_settings 8?|16 ignore_symlinks 8?|17 only_open_editors 8?|18 only_file_scheme 8?|19 reason 9?|20 extra_file_resources #4",qt,Bt,wt,St,Jt]}}class Jt extends w{constructor(t){super(),this.extraFileResources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ExtraFileResourcesProto|1 extra_file_resources 9*"]}}class wt extends w{constructor(t){super(),this.excludePattern=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ExcludePatternProto|1 exclude_pattern #0*",yt]}}class yt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ISearchPatternBuilderProto|1 uri 9?|2 pattern #0",St]}}class St extends w{constructor(t){super(),this.patterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(St,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ISearchPathPatternBuilderProto|1 pattern 9?|2 patterns 9*"]}}class qt extends w{constructor(t){super(),this.matchLines=0,this.charsPerLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ITextSearchPreviewOptionsProto|1 match_lines 5|2 chars_per_line 5"]}}class Bt extends w{constructor(t){super(),this.includeMarkupInput=!1,this.includeMarkupPreview=!1,this.includeCodeInput=!1,this.includeOutput=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.INotebookSearchConfigProto|1 include_markup_input 8|2 include_markup_preview 8|3 include_code_input 8|4 include_output 8"]}}class It extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["RipgrepSearchResult|1 internal #0",Pt]}}class Pt extends w{constructor(t){super(),this.results=[],this.messages=[],this.stats={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["RipgrepSearchResultInternal|1 results #0*|2 exit #1?|3 limit_hit 8?|4 messages #2*|5 file_search_stats #3 stats|6 text_search_stats #4 stats",vt,Rt,Ut,At,Mt]}}var bt=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.TextSearchCompleteMessageType",[[0,"UNSPECIFIED"],[1,"INFORMATION"],[2,"WARNING"]],1),Rt=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.SearchCompletionExitCode",[[0,"UNSPECIFIED"],[1,"NORMAL"],[2,"NEW_SEARCH_STARTED"]],1);class vt extends w{constructor(t){super(),this.resource="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["RipgrepSearchResultInternal.IFileMatch|1 resource 9|2 results #0*",xt]}}class xt extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchResult|1 match #0 result|2 context #1 result",kt,Et]}}class kt extends w{constructor(t){super(),this.rangeLocations=[],this.previewText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchMatch|1 uri 9?|2 range_locations #0*|3 preview_text 9|4 webview_index 5?|5 cell_fragment 9?",Ct]}}class Et extends w{constructor(t){super(),this.text="",this.lineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchContext|1 uri 9?|2 text 9|3 line_number 5"]}}class Ct extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchRangeSetPairing|1 source #0|2 preview #0",Tt]}}class Tt extends w{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumber=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchRange|1 start_line_number 5|2 start_column 5|3 end_line_number 5|4 end_column 5"]}}class Ut extends w{constructor(t){super(),this.text="",this.type=bt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchCompleteMessage|1 text 9|2 type #0|3 trusted 8?",bt]}}class At extends w{constructor(t){super(),this.fromCache=!1,this.detailStats={case:void 0},this.resultCount=0,this.type=$t.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(At,t,r)}static $(){return["RipgrepSearchResultInternal.IFileSearchStats|1 from_cache 8|2 search_engine_stats #0 detail_stats|3 cached_search_stats #1 detail_stats|4 file_search_provider_stats #2 detail_stats|5 result_count 5|6 type #3|7 sorting_time 5?",Dt,Nt,Gt,$t]}}var $t=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.IFileSearchStats.FileSearchProviderType",[[0,"UNSPECIFIED"],[1,"FILE_SEARCH_PROVIDER"],[2,"SEARCH_PROCESS"]],1);class Mt extends w{constructor(t){super(),this.type=Ot.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchStats|1 type #0",Ot]}}var Ot=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.ITextSearchStats.TextSearchProviderType",[[0,"UNSPECIFIED"],[1,"TEXT_SEARCH_PROVIDER"],[2,"SEARCH_PROCESS"],[3,"AI_TEXT_SEARCH_PROVIDER"]],1);class Dt extends w{constructor(t){super(),this.fileWalkTime=0,this.directoriesWalked=0,this.filesWalked=0,this.cmdTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchEngineStats|1 file_walk_time 5|2 directories_walked 5|3 files_walked 5|4 cmd_time 5|5 cmd_result_count 5?"]}}class Nt extends w{constructor(t){super(),this.cacheWasResolved=!1,this.cacheLookupTime=0,this.cacheFilterTime=0,this.cacheEntryCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["RipgrepSearchResultInternal.ICachedSearchStats|1 cache_was_resolved 8|2 cache_lookup_time 5|3 cache_filter_time 5|4 cache_entry_count 5"]}}class Gt extends w{constructor(t){super(),this.providerTime=0,this.postProcessTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gt,t,r)}static $(){return["RipgrepSearchResultInternal.IFileSearchProviderStats|1 provider_time 5|2 post_process_time 5"]}}class Lt extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lt,t,r)}static $(){return["RipgrepSearchStream|1 query 9"]}}class Ft extends w{constructor(t){super(),this.codeResults=[],this.query="",this.prReferences=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["ReadSemsearchFilesParams|1 repository_info #0|2 code_results #1*|3 query 9|4 pr_references #2*|5 pr_search_on 8?",l.bn,l.PT,Ze]}}class Kt extends w{constructor(t){super(),this.relativeWorkspacePath="",this.missingReason=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["MissingFile|1 relative_workspace_path 9|2 missing_reason #0|3 num_lines 5?",zt]}}var zt=(0,_.QT)(n.proto3,J,"MissingFile.MissingReason",[[0,"UNSPECIFIED"],[1,"TOO_LARGE"],[2,"NOT_FOUND"]],1);class jt extends w{constructor(t){super(),this.knowledge="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["Knowledge|1 knowledge 9|2 title 9"]}}class Ht extends w{constructor(t){super(),this.sha="",this.fullPrContents="",this.score=0,this.changedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["ToolPullRequestResult|1 sha 9|2 full_pr_contents 9|3 score 2|4 title 9?|5 summary 9?|6 pr_number 13?|7 changed_files 9*|8 author 9?|9 date 9?"]}}class Wt extends w{constructor(t){super(),this.codeResults=[],this.allFiles=[],this.missingFiles=[],this.knowledgeResults=[],this.prResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wt,t,r)}static $(){return["ReadSemsearchFilesResult|1 code_results #0*|2 all_files #1*|3 missing_files #2*|4 knowledge_results #3*|5 pr_results #4*|6 git_remote_url 9?|7 pr_hydration_timed_out 8?",l.PT,s.ZH,Kt,jt,Ht]}}class Qt extends w{constructor(t){super(),this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["ReadSemsearchFilesStream|1 num_files 5"]}}class Vt extends w{constructor(t){super(),this.query="",this.topK=0,this.prReferences=[],this.codeResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["SemanticSearchFullParams|1 repository_info #0|2 query 9|3 include_pattern 9?|4 exclude_pattern 9?|5 top_k 5|6 pr_references #1*|7 pr_search_on 8?|8 explanation 9?|9 code_results #2*",l.bn,Ze,l.PT]}}class Xt extends w{constructor(t){super(),this.codeResults=[],this.allFiles=[],this.missingFiles=[],this.knowledgeResults=[],this.prResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["SemanticSearchFullResult|1 code_results #0*|2 all_files #1*|3 missing_files #2*|4 knowledge_results #3*|5 pr_results #4*|6 git_remote_url 9?|7 pr_hydration_timed_out 8?",l.PT,s.ZH,Kt,jt,Ht]}}class Yt extends w{constructor(t){super(),this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["SemanticSearchFullStream|1 num_files 5"]}}class Zt extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["DeleteFileParams|1 relative_workspace_path 9"]}}class tr extends w{constructor(t){super(),this.rejected=!1,this.fileNonExistent=!1,this.fileDeletedSuccessfully=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tr,t,r)}static $(){return["DeleteFileResult|1 rejected 8|2 file_non_existent 8|3 file_deleted_successfully 8"]}}class rr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rr).fromBinary(t,r)}static fromJson(t,r){return(new rr).fromJson(t,r)}static fromJsonString(t,r){return(new rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rr,t,r)}static $(){return["DeleteFileStream|1 relative_workspace_path 9"]}}class er extends w{constructor(t){super(),this.tool=S.UNSPECIFIED,this.params={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(er,t,r)}static $(){return["BuiltinToolCall|1 tool #0|2 search_params #1 params|3 read_chunk_params #2 params|4 gotodef_params #3 params|5 edit_params #4 params|6 undo_edit_params #5 params|7 end_params #6 params|8 new_file_params #7 params|9 add_test_params #8 params|10 run_test_params #9 params|11 delete_test_params #10 params|12 save_file_params #11 params|13 get_tests_params #12 params|14 get_symbols_params #13 params|15 semantic_search_params #14 params|16 get_project_structure_params #15 params|17 create_rm_files_params #16 params|18 run_terminal_commands_params #17 params|19 new_edit_params #18 params|20 read_with_linter_params #19 params|21 add_ui_step_params #20 params|23 read_semsearch_files_params #21 params|26 delete_file_params #22 params|22 tool_call_id 9?",S,Pr,xr,Or,Kr,Er,Cr,wr,Qr,Zr,se,oe,re,ue,yr,gr,pr,fr,Lr,lr,sr,Ft,Zt]}}class nr extends w{constructor(t){super(),this.tool=S.UNSPECIFIED,this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nr,t,r)}static $(){return["BuiltinToolResult|1 tool #0|2 search_result #1 result|3 read_chunk_result #2 result|4 gotodef_result #3 result|5 edit_result #4 result|6 undo_edit_result #5 result|7 end_result #6 result|8 new_file_result #7 result|9 add_test_result #8 result|10 run_test_result #9 result|11 delete_test_result #10 result|12 save_file_result #11 result|13 get_tests_result #12 result|14 get_symbols_result #13 result|15 semantic_search_result #14 result|16 get_project_structure_result #15 result|17 create_rm_files_result #16 result|18 run_terminal_commands_result #17 result|19 new_edit_result #18 result|20 read_with_linter_result #19 result|21 add_ui_step_result #20 result|22 read_semsearch_files_result #21 result|24 delete_file_result #22 result",S,vr,kr,Nr,jr,Ur,Ar,Tr,Vr,te,ie,ae,ee,le,Br,_r,hr,dr,Fr,mr,ar,Wt,tr]}}class sr extends w{constructor(t){super(),this.conversationId="",this.step={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sr).fromBinary(t,r)}static fromJson(t,r){return(new sr).fromJson(t,r)}static fromJsonString(t,r){return(new sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sr,t,r)}static $(){return["AddUiStepParams|1 conversation_id 9|2 search_results #0 step",or]}}class ir extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ir,t,r)}static $(){return["AddUiStepParams.SearchResult|1 relative_workspace_path 9"]}}class or extends w{constructor(t){super(),this.searchResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["AddUiStepParams.SearchResults|1 search_results #0*",ir]}}class ar extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["AddUiStepResult"]}}class ur extends w{constructor(t){super(),this.toolCall={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["ToolCall|1 builtin_tool_call #0 tool_call|2 custom_tool_call #1 tool_call",er,$r]}}class cr extends w{constructor(t){super(),this.toolResult={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["ToolResult|1 builtin_tool_result #0 tool_result|2 custom_tool_result #1 tool_result|3 error_tool_result #2 tool_result",nr,Mr,Gr]}}class lr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["ReadWithLinterParams|1 relative_workspace_path 9"]}}class mr extends w{constructor(t){super(),this.contents="",this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["ReadWithLinterResult|1 contents 9|2 diagnostics #0*",s.oQ]}}class fr extends w{constructor(t){super(),this.commands=[],this.commandsUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["RunTerminalCommandsParams|1 commands 9*|2 commands_uuid 9"]}}class dr extends w{constructor(t){super(),this.outputs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dr,t,r)}static $(){return["RunTerminalCommandsResult|1 outputs 9*"]}}class pr extends w{constructor(t){super(),this.removedFilePaths=[],this.createdFilePaths=[],this.createdDirectoryPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["CreateRmFilesParams|1 removed_file_paths 9*|2 created_file_paths 9*|3 created_directory_paths 9*"]}}class hr extends w{constructor(t){super(),this.createdFilePaths=[],this.removedFilePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["CreateRmFilesResult|1 created_file_paths 9*|2 removed_file_paths 9*"]}}class gr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["GetProjectStructureParams"]}}class _r extends w{constructor(t){super(),this.files=[],this.rootWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["GetProjectStructureResult|1 files #0*|2 root_workspace_path 9",Jr]}}class Jr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.outline="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jr,t,r)}static $(){return["GetProjectStructureResult.File|1 relative_workspace_path 9|2 outline 9"]}}class wr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wr).fromBinary(t,r)}static fromJson(t,r){return(new wr).fromJson(t,r)}static fromJsonString(t,r){return(new wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wr,t,r)}static $(){return["NewFileParams|1 relative_workspace_path 9"]}}class yr extends w{constructor(t){super(),this.query="",this.topK=0,this.grabWholeFile=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yr,t,r)}static $(){return["SemanticSearchParams|1 query 9|2 include_pattern 9?|3 exclude_pattern 9?|4 top_k 5|5 index_id 9?|6 grab_whole_file 8"]}}class Sr extends w{constructor(t){super(),this.startLine=0,this.startCharacter=0,this.endLine=0,this.endCharacter=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sr,t,r)}static $(){return["Range|1 start_line 5|2 start_character 5|3 end_line 5|4 end_character 5"]}}class qr extends w{constructor(t){super(),this.start=0,this.end=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qr,t,r)}static $(){return["MatchRange|1 start 5|2 end 5"]}}class Br extends w{constructor(t){super(),this.results=[],this.files={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Br,t,r)}static $(){return["SemanticSearchResult|1 results #0*|2 files 9,9",Ir]}}class Ir extends w{constructor(t){super(),this.relativeWorkspacePath="",this.score=0,this.content="",this.detailedLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ir,t,r)}static $(){return["SemanticSearchResult.Item|1 relative_workspace_path 9|2 score 2|3 content 9|4 range #0|5 original_content 9?|6 detailed_lines #1*",s._u,s.d7]}}class Pr extends w{constructor(t){super(),this.query="",this.regex=!1,this.includePattern="",this.excludePattern="",this.filenameSearch=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pr).fromBinary(t,r)}static fromJson(t,r){return(new Pr).fromJson(t,r)}static fromJsonString(t,r){return(new Pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pr,t,r)}static $(){return["SearchParams|1 query 9|2 regex 8|3 include_pattern 9|4 exclude_pattern 9|5 filename_search 8"]}}class br extends w{constructor(t){super(),this.relativeWorkspacePath="",this.numMatches=0,this.potentiallyRelevantLines=[],this.cropped=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(br,t,r)}static $(){return["SearchToolFileSearchResult|1 relative_workspace_path 9|2 num_matches 5|3 potentially_relevant_lines #0*|4 cropped 8",Rr]}}class Rr extends w{constructor(t){super(),this.lineNumber=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rr,t,r)}static $(){return["SearchToolFileSearchResult.Line|1 line_number 5|2 text 9"]}}class vr extends w{constructor(t){super(),this.fileResults=[],this.numTotalMatches=0,this.numTotalMatchedFiles=0,this.numTotalMayBeIncomplete=!1,this.filesOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vr,t,r)}static $(){return["SearchResult|1 file_results #0*|2 num_total_matches 5|3 num_total_matched_files 5|4 num_total_may_be_incomplete 8|5 files_only 8",br]}}class xr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xr,t,r)}static $(){return["ReadChunkParams|1 relative_workspace_path 9|2 start_line_number 5|3 num_lines 5?"]}}class kr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.totalNumLines=0,this.cropped=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kr,t,r)}static $(){return["ReadChunkResult|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 total_num_lines 5|5 cropped 8"]}}class Er extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Er).fromBinary(t,r)}static fromJson(t,r){return(new Er).fromJson(t,r)}static fromJsonString(t,r){return(new Er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Er,t,r)}static $(){return["UndoEditParams"]}}class Cr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cr,t,r)}static $(){return["EndParams"]}}class Tr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.fileTotalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tr,t,r)}static $(){return["NewFileResult|1 relative_workspace_path 9|2 file_total_lines 5"]}}class Ur extends w{constructor(t){super(),this.feedback=[],this.relativeWorkspacePath="",this.contextStartLineNumber=0,this.contextLines=[],this.contextTotalNumLines=0,this.fileTotalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ur,t,r)}static $(){return["UndoEditResult|1 feedback 9*|4 relative_workspace_path 9|2 context_start_line_number 5|3 context_lines 9*|5 context_total_num_lines 5|6 file_total_lines 5"]}}class Ar extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ar,t,r)}static $(){return["EndResult"]}}class $r extends w{constructor(t){super(),this.toolId="",this.params="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($r,t,r)}static $(){return["CustomToolCall|1 tool_id 9|2 params 9"]}}class Mr extends w{constructor(t){super(),this.toolId="",this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mr).fromBinary(t,r)}static fromJson(t,r){return(new Mr).fromJson(t,r)}static fromJsonString(t,r){return(new Mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mr,t,r)}static $(){return["CustomToolResult|1 tool_id 9|2 result 9"]}}class Or extends w{constructor(t){super(),this.relativeWorkspacePath="",this.symbol="",this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Or,t,r)}static $(){return["GotodefParams|1 relative_workspace_path 9|2 symbol 9|3 start_line 5|4 end_line 5"]}}class Dr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLine=0,this.endLine=0,this.codeContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dr,t,r)}static $(){return["GotodefDefinition|1 relative_workspace_path 9|2 fully_qualified_name 9?|3 symbol_kind 9?|4 start_line 5|5 end_line 5|6 code_context_lines 9*"]}}class Nr extends w{constructor(t){super(),this.definitions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nr,t,r)}static $(){return["GotodefResult|1 definitions #0*",Dr]}}class Gr extends w{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gr,t,r)}static $(){return["ErrorToolResult|1 error_message 9"]}}class Lr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.text="",this.editId="",this.firstEdit=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lr,t,r)}static $(){return["NewEditParams|1 relative_workspace_path 9|2 start_line_number 5?|3 end_line_number 5?|4 text 9|5 edit_id 9|6 first_edit 8"]}}class Fr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fr).fromBinary(t,r)}static fromJson(t,r){return(new Fr).fromJson(t,r)}static fromJsonString(t,r){return(new Fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fr,t,r)}static $(){return["NewEditResult"]}}class Kr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.replaceNumLines=0,this.newLines=[],this.editId="",this.frontendEditType=zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kr).fromBinary(t,r)}static fromJson(t,r){return(new Kr).fromJson(t,r)}static fromJsonString(t,r){return(new Kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kr,t,r)}static $(){return["EditParams|1 relative_workspace_path 9|2 line_number 5?|3 replace_num_lines 5|4 new_lines 9*|7 replace_whole_file 8?|5 edit_id 9|6 frontend_edit_type #0|8 auto_fix_all_linter_errors_in_file 8?",zr]}}var zr=(0,_.QT)(n.proto3,J,"EditParams.FrontendEditType",[[0,"UNSPECIFIED"],[1,"INLINE_DIFFS"],[2,"SIMPLE"]],1);class jr extends w{constructor(t){super(),this.feedback=[],this.contextStartLineNumber=0,this.contextLines=[],this.file="",this.fileTotalLines=0,this.structuredFeedback=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jr,t,r)}static $(){return["EditResult|1 feedback 9*|2 context_start_line_number 5|3 context_lines 9*|4 file 9|5 file_total_lines 5|6 structured_feedback #0*",Wr]}}class Hr extends w{constructor(t){super(),this.message="",this.startLineNumber=0,this.endLineNumber=0,this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hr,t,r)}static $(){return["EditResult.RelatedInformation|1 message 9|2 start_line_number 5|3 end_line_number 5|4 relative_workspace_path 9"]}}class Wr extends w{constructor(t){super(),this.message="",this.severity="",this.startLineNumber=0,this.endLineNumber=0,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wr,t,r)}static $(){return["EditResult.Feedback|1 message 9|2 severity 9|3 start_line_number 5|4 end_line_number 5|5 related_information #0*",Hr]}}class Qr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.testName="",this.testCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qr,t,r)}static $(){return["AddTestParams|1 relative_workspace_path 9|2 test_name 9|3 test_code 9"]}}class Vr extends w{constructor(t){super(),this.feedback=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vr).fromBinary(t,r)}static fromJson(t,r){return(new Vr).fromJson(t,r)}static fromJsonString(t,r){return(new Vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vr,t,r)}static $(){return["AddTestResult|1 feedback #0*",Yr]}}class Xr extends w{constructor(t){super(),this.message="",this.startLineNumber=0,this.endLineNumber=0,this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xr,t,r)}static $(){return["AddTestResult.RelatedInformation|1 message 9|2 start_line_number 5|3 end_line_number 5|4 relative_workspace_path 9"]}}class Yr extends w{constructor(t){super(),this.message="",this.severity="",this.startLineNumber=0,this.endLineNumber=0,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yr,t,r)}static $(){return["AddTestResult.Feedback|1 message 9|2 severity 9|3 start_line_number 5|4 end_line_number 5|5 related_information #0*",Xr]}}class Zr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zr,t,r)}static $(){return["RunTestParams|1 relative_workspace_path 9|2 test_name 9?"]}}class te extends w{constructor(t){super(),this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(te,t,r)}static $(){return["RunTestResult|1 result 9"]}}class re extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(re,t,r)}static $(){return["GetTestsParams|1 relative_workspace_path 9"]}}class ee extends w{constructor(t){super(),this.tests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ee,t,r)}static $(){return["GetTestsResult|1 tests #0*",ne]}}class ne extends w{constructor(t){super(),this.name="",this.lines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ne,t,r)}static $(){return["GetTestsResult.Test|1 name 9|2 lines 9*"]}}class se extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new se).fromBinary(t,r)}static fromJson(t,r){return(new se).fromJson(t,r)}static fromJsonString(t,r){return(new se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(se,t,r)}static $(){return["DeleteTestParams|1 relative_workspace_path 9|2 test_name 9?"]}}class ie extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ie,t,r)}static $(){return["DeleteTestResult"]}}class oe extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oe,t,r)}static $(){return["SaveFileParams|1 relative_workspace_path 9"]}}class ae extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ae,t,r)}static $(){return["SaveFileResult"]}}class ue extends w{constructor(t){super(),this.relativeWorkspacePath="",this.includeChildren=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ue,t,r)}static $(){return["GetSymbolsParams|1 relative_workspace_path 9|2 line_range #0?|3 include_children 8",ce]}}class ce extends w{constructor(t){super(),this.startLineNumber=0,this.endLineNumberInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ce,t,r)}static $(){return["GetSymbolsParams.LineRange|1 start_line_number 5|2 end_line_number_inclusive 5"]}}class le extends w{constructor(t){super(),this.symbols=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(le,t,r)}static $(){return["GetSymbolsResult|1 symbols #0*",s.Az]}}class me extends w{constructor(t){super(),this.parsingFailed=!1,this.executableCommands=[],this.hasRedirects=!1,this.hasCommandSubstitution=!1,this.redirects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(me,t,r)}static $(){return["ShellCommandParsingResult|1 parsing_failed 8|2 executable_commands #0*|3 has_redirects 8|4 has_command_substitution 8|5 all_redirects_are_dev_null 8?|6 redirects #1*",de,pe]}}class fe extends w{constructor(t){super(),this.type="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fe).fromBinary(t,r)}static fromJson(t,r){return(new fe).fromJson(t,r)}static fromJsonString(t,r){return(new fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fe,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommandArg|1 type 9|2 value 9"]}}class de extends w{constructor(t){super(),this.name="",this.args=[],this.fullText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(de,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommand|1 name 9|2 args #0*|3 full_text 9",fe]}}class pe extends w{constructor(t){super(),this.operator="",this.destinationFds=[],this.targetNodeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pe,t,r)}static $(){return["ShellCommandParsingResult.Redirect|1 operator 9|2 destination_fds 13*|3 target_node_type 9|4 target_text 9?"]}}class he extends w{constructor(t){super(),this.command="",this.isBackground=!1,this.requireUserApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(he,t,r)}static $(){return["RunTerminalCommandV2Params|1 command 9|2 cwd 9?|3 new_session 8?|4 options #0?|5 is_background 8|6 require_user_approval 8|7 parsing_result #1?|8 idle_timeout_seconds 5?|9 requested_sandbox_policy #2?|10 file_output_threshold_bytes 3?|11 command_description 9?|12 classifier_result #3?",ge,me,m.Mw,f.E4]}}class ge extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ge,t,r)}static $(){return["RunTerminalCommandV2Params.ExecutionOptions|1 timeout 5?|2 skip_ai_check 8?|3 command_run_timeout_ms 5?|4 command_change_check_interval_ms 5?|5 ai_finish_check_max_attempts 5?|6 ai_finish_check_interval_ms 5?|7 delayer_interval_ms 5?|8 ai_check_for_hangs 8?"]}}class _e extends w{constructor(t){super(),this.filePath="",this.sizeBytes=n.protoInt64.zero,this.lineCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_e,t,r)}static $(){return["OutputLocation|1 file_path 9|2 size_bytes 3|3 line_count 3"]}}class Je extends w{constructor(t){super(),this.output="",this.exitCode=0,this.poppedOutIntoBackground=!1,this.isRunningInBackground=!1,this.notInterrupted=!1,this.resultingWorkingDirectory="",this.didUserChange=!1,this.endedReason=q.UNSPECIFIED,this.outputRaw="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Je).fromBinary(t,r)}static fromJson(t,r){return(new Je).fromJson(t,r)}static fromJsonString(t,r){return(new Je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Je,t,r)}static $(){return["RunTerminalCommandV2Result|1 output 9|2 exit_code 5|3 rejected 8?|4 popped_out_into_background 8|5 is_running_in_background 8|6 not_interrupted 8|7 resulting_working_directory 9|8 did_user_change 8|9 ended_reason #0|10 exit_code_v2 5?|11 updated_command 9?|12 output_raw 9|13 human_review_v2 #1?|14 effective_sandbox_policy #2?|15 terminal_instance_id 5?|16 output_location #3?|17 terminal_instance_path 9?|18 background_shell_id 13?",q,rt,m.Mw,_e]}}class we extends w{constructor(t){super(),this.command="",this.isBackground=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(we,t,r)}static $(){return["RunTerminalCommandV2Stream|1 command 9|2 is_background 8|7 parsing_result #0?|8 idle_timeout_seconds 5?|9 requested_sandbox_policy #1?",me,m.Mw]}}class ye extends w{constructor(t){super(),this.ruleNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ye,t,r)}static $(){return["FetchRulesStream|1 rule_names 9*"]}}class Se extends w{constructor(t){super(),this.searchTerm="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Se,t,r)}static $(){return["WebSearchParams|1 search_term 9"]}}class qe extends w{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qe,t,r)}static $(){return["WebSearchResult|1 references #0*|2 is_final 8?|3 rejected 8?",Be]}}class Be extends w{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Be,t,r)}static $(){return["WebSearchResult.WebReference|1 title 9|2 url 9|3 chunk 9"]}}class Ie extends w{constructor(t){super(),this.searchTerm="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ie).fromBinary(t,r)}static fromJson(t,r){return(new Ie).fromJson(t,r)}static fromJsonString(t,r){return(new Ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ie,t,r)}static $(){return["WebSearchStream|1 search_term 9"]}}class Pe extends w{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pe).fromBinary(t,r)}static fromJson(t,r){return(new Pe).fromJson(t,r)}static fromJsonString(t,r){return(new Pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pe,t,r)}static $(){return["MCPParams|1 tools #0*|2 file_output_threshold_bytes 3?",be]}}class be extends w{constructor(t){super(),this.name="",this.description="",this.parameters="",this.serverName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new be).fromBinary(t,r)}static fromJson(t,r){return(new be).fromJson(t,r)}static fromJsonString(t,r){return(new be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(be,t,r)}static $(){return["MCPParams.Tool|1 name 9|2 description 9|3 parameters 9|4 server_name 9|5 transcript_display #0?",Re]}}class Re extends w{constructor(t){super(),this.loading="",this.success="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Re,t,r)}static $(){return["MCPParams.TranscriptDisplay|1 loading 9|2 success 9|3 error 9"]}}class ve extends w{constructor(t){super(),this.selectedTool="",this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ve).fromBinary(t,r)}static fromJson(t,r){return(new ve).fromJson(t,r)}static fromJsonString(t,r){return(new ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ve,t,r)}static $(){return["MCPResult|1 selected_tool 9|2 result 9"]}}class xe extends w{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xe).fromBinary(t,r)}static fromJson(t,r){return(new xe).fromJson(t,r)}static fromJsonString(t,r){return(new xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xe,t,r)}static $(){return["MCPStream|1 tools #0*",be]}}class ke extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ke).fromBinary(t,r)}static fromJson(t,r){return(new ke).fromJson(t,r)}static fromJsonString(t,r){return(new ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ke,t,r)}static $(){return["ListMcpResourcesParams|1 server 9?"]}}class Ee extends w{constructor(t){super(),this.resources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ee,t,r)}static $(){return["ListMcpResourcesResult|1 resources #0*",Ce]}}class Ce extends w{constructor(t){super(),this.uri="",this.server="",this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ce,t,r)}static $(){return["ListMcpResourcesResult.MCPResource|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 server 9|6 annotations 9,9"]}}class Te extends w{constructor(t){super(),this.server="",this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Te,t,r)}static $(){return["ReadMcpResourceParams|1 server 9|2 uri 9|3 download_path 9?"]}}class Ue extends w{constructor(t){super(),this.uri="",this.content={case:void 0},this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ue,t,r)}static $(){return["ReadMcpResourceResult|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 text 9 content|6 blob 12 content|7 annotations 9,9"]}}class Ae extends w{constructor(t){super(),this.server="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ae,t,r)}static $(){return["CallMcpToolParams|1 server 9|2 tool_name 9|3 tool_args #0",n.Struct]}}class $e extends w{constructor(t){super(),this.server="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($e,t,r)}static $(){return["CallMcpToolResult|1 server 9|2 tool_name 9|3 result #0",n.Struct]}}class Me extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Me,t,r)}static $(){return["GetMcpToolsParams|1 server 9?|2 tool_name 9?|3 pattern 9?"]}}class Oe extends w{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oe,t,r)}static $(){return["GetMcpToolsResult|1 content 9|2 output_file_path 9?"]}}class De extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(De,t,r)}static $(){return["SearchSymbolsParams|1 query 9"]}}class Ne extends w{constructor(t){super(),this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ne).fromBinary(t,r)}static fromJson(t,r){return(new Ne).fromJson(t,r)}static fromJsonString(t,r){return(new Ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ne,t,r)}static $(){return["SearchSymbolsResult|1 matches #0*|2 rejected 8?",Ge]}}class Ge extends w{constructor(t){super(),this.name="",this.uri="",this.secondaryText="",this.labelMatches=[],this.descriptionMatches=[],this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ge).fromBinary(t,r)}static fromJson(t,r){return(new Ge).fromJson(t,r)}static fromJsonString(t,r){return(new Ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ge,t,r)}static $(){return["SearchSymbolsResult.SymbolMatch|1 name 9|2 uri 9|3 range #0|4 secondary_text 9|5 label_matches #1*|6 description_matches #1*|7 score 1",Sr,qr]}}class Le extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Le).fromBinary(t,r)}static fromJson(t,r){return(new Le).fromJson(t,r)}static fromJsonString(t,r){return(new Le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Le,t,r)}static $(){return["SearchSymbolsStream|1 query 9"]}}class Fe extends w{constructor(t){super(),this.proposedFollowup="",this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fe,t,r)}static $(){return["BackgroundComposerFollowupParams|1 proposed_followup 9|2 bc_id 9"]}}class Ke extends w{constructor(t){super(),this.proposedFollowup="",this.isSent=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ke,t,r)}static $(){return["BackgroundComposerFollowupResult|1 proposed_followup 9|2 is_sent 8"]}}class ze extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ze,t,r)}static $(){return["BackgroundComposerFollowupStream"]}}class je extends w{constructor(t){super(),this.knowledgeToStore="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(je,t,r)}static $(){return["KnowledgeBaseParams|1 knowledge_to_store 9|2 title 9|3 existing_knowledge_id 9?|4 action 9?"]}}class He extends w{constructor(t){super(),this.success=!1,this.confirmationMessage="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(He,t,r)}static $(){return["KnowledgeBaseResult|1 success 8|2 confirmation_message 9|3 id 9"]}}class We extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(We,t,r)}static $(){return["KnowledgeBaseStream"]}}class Qe extends w{constructor(t){super(),this.pullNumberOrCommitHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qe,t,r)}static $(){return["FetchPullRequestParams|1 pull_number_or_commit_hash 9|2 repo 9?|3 is_github 8?"]}}class Ve extends w{constructor(t){super(),this.content="",this.prNumber=0,this.title="",this.body="",this.author="",this.date="",this.diff="",this.comments=[],this.labels=[],this.assignees=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ve,t,r)}static $(){return["FetchPullRequestResult|1 content 9|2 pr_number 13|3 title 9|4 body 9|5 author 9|6 date 9|7 diff 9|8 sha 9?|9 external_link 9?|10 url 9?|11 comments #0*|12 labels 9*|13 assignees 9*|14 is_issue 8?|15 state 9?|16 prompt_connect_github 8?",Xe]}}class Xe extends w{constructor(t){super(),this.id=0,this.body="",this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xe,t,r)}static $(){return["IssueComment|1 id 13|2 body 9|3 author 9?|4 created_at 9|5 updated_at 9|6 author_association 9?"]}}class Ye extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ye).fromBinary(t,r)}static fromJson(t,r){return(new Ye).fromJson(t,r)}static fromJsonString(t,r){return(new Ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ye,t,r)}static $(){return["FetchPullRequestStream"]}}class Ze extends w{constructor(t){super(),this.sha="",this.score=0,this.changedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ze,t,r)}static $(){return["PullRequestReference|1 sha 9|2 score 2|3 title 9?|4 summary 9?|5 pr_number 13?|6 author 9?|7 date 9?|8 changed_files 9*"]}}class tn extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tn,t,r)}static $(){return["DeepSearchParams|1 query 9"]}}class rn extends w{constructor(t){super(),this.success=!1,this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rn,t,r)}static $(){return["DeepSearchResult|1 success 8|2 result 9"]}}class en extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(en,t,r)}static $(){return["DeepSearchStream"]}}class nn extends w{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nn,t,r)}static $(){return["CreateDiagramParams|1 content 9"]}}class sn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sn,t,r)}static $(){return["CreateDiagramResult|1 error 9?"]}}class on extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(on,t,r)}static $(){return["CreateDiagramStream"]}}class an extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(an,t,r)}static $(){return["FixLintsParams"]}}class un extends w{constructor(t){super(),this.fileResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(un,t,r)}static $(){return["FixLintsResult|1 file_results #0*",cn]}}class cn extends w{constructor(t){super(),this.filePath="",this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cn,t,r)}static $(){return["FixLintsResult.FileResult|1 file_path 9|2 diff #0|3 is_applied 8|4 apply_failed 8|5 error 9?|6 linter_errors #1*",W,s.bO]}}class ln extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ln,t,r)}static $(){return["FixLintsStream"]}}class mn extends w{constructor(t){super(),this.path="",this.paths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mn,t,r)}static $(){return["ReadLintsParams|1 path 9|2 paths 9*"]}}class fn extends w{constructor(t){super(),this.path="",this.linterErrors=[],this.linterErrorsByFile=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fn,t,r)}static $(){return["ReadLintsResult|1 path 9|2 linter_errors #0*|3 linter_errors_by_file #1*",s.bO,s.wZ]}}class dn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dn,t,r)}static $(){return["ReadLintsStream"]}}class pn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pn,t,r)}static $(){return["GotodefStream"]}}class hn extends w{constructor(t){super(),this.taskDescription="",this.taskTitle="",this.allowedWriteDirectories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hn,t,r)}static $(){return["TaskParams|1 task_description 9|4 task_title 9|2 async 8?|3 allowed_write_directories 9*|5 model_override 9?|6 max_mode_override 8?|7 default_expanded_while_running 8?"]}}class gn extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gn,t,r)}static $(){return["TaskResult|1 completed_task_result #0 result|2 async_task_result #1 result",_n,Jn]}}class _n extends w{constructor(t){super(),this.summary="",this.fileResults=[],this.userAborted=!1,this.subagentErrored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_n,t,r)}static $(){return["TaskResult.CompletedTaskResult|1 summary 9|2 file_results #0*|3 user_aborted 8|4 subagent_errored 8",cn]}}class Jn extends w{constructor(t){super(),this.taskId="",this.userAborted=!1,this.subagentErrored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["TaskResult.AsyncTaskResult|1 task_id 9|2 user_aborted 8|3 subagent_errored 8"]}}class wn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wn,t,r)}static $(){return["TaskStream"]}}class yn extends w{constructor(t){super(),this.description="",this.prompt="",this.subagentType="",this.name="",this.mode=d.FL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["TaskV2Params|1 description 9|2 prompt 9|3 subagent_type 9|4 model 9?|5 name 9|6 mode #0",d.FL]}}class Sn extends w{constructor(t){super(),this.isBackground=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["TaskV2Result|1 agent_id 9?|2 is_background 8|3 cloud_agent_bc_id 9?"]}}class qn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["TaskV2Stream"]}}class Bn extends w{constructor(t){super(),this.pattern="",this.ignoreGlobs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["RipgrepRawSearchParams|1 pattern 9|2 path 9?|3 glob 9?|4 output_mode 9?|5 context_before 5?|6 context_after 5?|7 context 5?|8 case_insensitive 8?|9 type 9?|10 head_limit 5?|11 multiline 8?|12 sort 9?|13 sort_ascending 8?|14 ignore_globs 9*|15 offset 5?"]}}class In extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(In,t,r)}static $(){return["RipgrepRawSearchResult|1 success #0 result|2 error #1 result",bn,Pn]}}class Pn extends w{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pn,t,r)}static $(){return["RipgrepRawSearchError|1 error 9"]}}class bn extends w{constructor(t){super(),this.pattern="",this.path="",this.outputMode="",this.workspaceResults={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["RipgrepRawSearchSuccess|1 pattern 9|2 path 9|3 output_mode 9|4 workspace_results 9,#0|5 active_editor_result #0?",Rn]}}class Rn extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["RipgrepRawSearchUnionResult|1 count #0 result|2 files #1 result|3 content #2 result",vn,kn,Cn]}}class vn extends w{constructor(t){super(),this.counts=[],this.totalFiles=0,this.totalMatches=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["RipgrepRawSearchCountResult|1 counts #0*|2 total_files 5|3 total_matches 5|4 client_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?|5 ripgrep_truncated 8",xn]}}class xn extends w{constructor(t){super(),this.file="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xn,t,r)}static $(){return["RipgrepRawSearchFileCount|1 file 9|2 count 5|3 is_dirty 8?|4 is_out_of_workspace 8?|5 absolute_path 9?"]}}class kn extends w{constructor(t){super(),this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,this.filesWithMeta=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["RipgrepRawSearchFilesResult|1 files 9*|2 total_files 5|3 client_truncated 8|4 ripgrep_truncated 8|5 files_with_meta #0*|6 head_limit_applied 5?|7 offset_applied 5?",En]}}class En extends w{constructor(t){super(),this.file="",this.isDirty=!1,this.isOutOfWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["RipgrepRawSearchFilesResult.FileEntry|1 file 9|2 is_dirty 8|3 is_out_of_workspace 8|4 absolute_path 9?"]}}class Cn extends w{constructor(t){super(),this.matches=[],this.totalLines=0,this.totalMatchedLines=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["RipgrepRawSearchContentResult|1 matches #0*|2 total_lines 5|3 total_matched_lines 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",Tn]}}class Tn extends w{constructor(t){super(),this.file="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["RipgrepRawSearchFileMatch|1 file 9|2 matches #0*|3 is_dirty 8?|4 is_out_of_workspace 8?|5 absolute_path 9?",Un]}}class Un extends w{constructor(t){super(),this.lineNumber=0,this.content="",this.contentTruncated=!1,this.isContextLine=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["RipgrepRawSearchContentMatch|1 line_number 5|2 content 9|3 content_truncated 8|4 is_context_line 8"]}}class An extends w{constructor(t){super(),this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["RipgrepRawSearchStream|1 pattern 9"]}}class $n extends w{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["AwaitTaskParams|1 ids 9*"]}}class Mn extends w{constructor(t){super(),this.taskResults=[],this.missingTaskIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["AwaitTaskResult|1 task_results #0*|2 missing_task_ids 9*",On]}}class On extends w{constructor(t){super(),this.taskId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["AwaitTaskResult.TaskResultItem|1 task_id 9|2 result #0",_n]}}class Dn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["AwaitTaskStream"]}}class Nn extends w{constructor(t){super(),this.read=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["TodoReadParams|1 read 8"]}}class Gn extends w{constructor(t){super(),this.content="",this.status="",this.id="",this.dependencies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["TodoItem|1 content 9|2 status 9|3 id 9|4 dependencies 9*"]}}class Ln extends w{constructor(t){super(),this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["TodoReadResult|1 todos #0*",Gn]}}class Fn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["TodoReadStream"]}}class Kn extends w{constructor(t){super(),this.todos=[],this.merge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["TodoWriteParams|1 todos #0*|2 merge 8",Gn]}}class zn extends w{constructor(t){super(),this.success=!1,this.readyTaskIds=[],this.needsInProgressTodos=!1,this.finalTodos=[],this.initialTodos=[],this.wasMerge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["TodoWriteResult|1 success 8|2 ready_task_ids 9*|3 needs_in_progress_todos 8|4 final_todos #0*|5 initial_todos #0*|6 was_merge 8",Gn]}}class jn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["TodoWriteStream"]}}class Hn extends w{constructor(t){super(),this.targetDirectory="",this.ignoreGlobs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["ListDirV2Params|1 target_directory 9|2 ignore_globs 9*|3 should_enrich_terminal_metadata 8?"]}}class Wn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["ListDirV2Result|1 directory_tree_root #0",Qn]}}class Qn extends w{constructor(t){super(),this.absPath="",this.childrenDirs=[],this.childrenFiles=[],this.childrenWereProcessed=!1,this.fullSubtreeExtensionCounts={},this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["ListDirV2Result.DirectoryTreeNode|1 abs_path 9|2 children_dirs #0*|3 children_files #1*|4 children_were_processed 8|5 full_subtree_extension_counts 9,5|6 num_files 5",Qn,Vn]}}class Vn extends w{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["ListDirV2Result.DirectoryTreeNode.File|1 name 9|2 terminal_metadata #0?",p.Y$]}}class Xn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["ListDirV2Stream"]}}class Yn extends w{constructor(t){super(),this.targetFile="",this.charsLimit=0,this.effectiveUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ReadFileV2Params|1 target_file 9|2 offset 5?|3 limit 5?|4 chars_limit 5|5 effective_uri 9|6 enable_line_numbers 8?"]}}class Zn extends w{constructor(t){super(),this.numCharactersInRequestedRange=0,this.matchingCursorRules=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ReadFileV2Result|1 contents 9?|2 num_characters_in_requested_range 5|3 offset_is_bigger_than_number_of_lines_in_file 8?|4 total_lines_in_file 5?|5 matching_cursor_rules #0*|6 images #1*",s.DX,s.UR]}}class ts extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["ReadFileV2Stream|1 params #0?",Yn]}}class rs extends w{constructor(t){super(),this.targetDirectory="",this.globPattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["GlobFileSearchParams|1 target_directory 9|2 glob_pattern 9"]}}class es extends w{constructor(t){super(),this.directories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["GlobFileSearchResult|1 directories #0*",ss]}}class ns extends w{constructor(t){super(),this.relPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["GlobFileSearchResult.File|1 rel_path 9"]}}class ss extends w{constructor(t){super(),this.absPath="",this.files=[],this.totalFiles=0,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["GlobFileSearchResult.Directory|1 abs_path 9|2 files #0*|3 total_files 5|4 ripgrep_truncated 8",ns]}}class is extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["GlobFileSearchStream"]}}class os extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["ListMcpResourcesStream"]}}class as extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["CallMcpToolStream"]}}class us extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["ReadMcpResourceStream"]}}class cs extends w{constructor(t){super(),this.id="",this.title="",this.description="",this.instructions="",this.prerequisites=[],this.subComposerId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["Step|1 id 9|2 title 9|3 description 9|4 instructions 9|5 prerequisites 9*|6 sub_composer_id 9"]}}class ls extends w{constructor(t){super(),this.name="",this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["PlanPhase|1 name 9|2 todos #0*",Gn]}}class ms extends w{constructor(t){super(),this.plan="",this.title="",this.summary="",this.steps=[],this.oldStr="",this.newStr="",this.name="",this.todos=[],this.overview="",this.isSpec=!1,this.isProject=!1,this.phases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["CreatePlanParams|1 plan 9|2 title 9|3 summary 9|4 steps #0*|5 old_str 9|6 new_str 9|7 name 9|8 todos #1*|9 overview 9|10 is_spec 8|11 is_project 8|12 phases #2*",cs,Gn,ls]}}class fs extends w{constructor(t){super(),this.result={case:void 0},this.planUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["CreatePlanResult|1 accepted #0 result|2 rejected #1 result|3 modified #2 result|4 plan_uri 9",ds,ps,hs]}}class ds extends w{constructor(t){super(),this.finalTodos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["CreatePlanResult.Accepted|1 final_todos #0*",Gn]}}class ps extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["CreatePlanResult.Rejected"]}}class hs extends w{constructor(t){super(),this.newPlan="",this.finalTodos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["CreatePlanResult.Modified|1 new_plan 9|2 final_todos #0*",Gn]}}class gs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["CreatePlanStream"]}}class _s extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["ReadProjectParams"]}}class Js extends w{constructor(t){super(),this.plan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["ReadProjectResult|1 plan 9"]}}class ws extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["ReadProjectStream"]}}class ys extends w{constructor(t){super(),this.oldString="",this.newString="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["UpdateProjectStringReplacement|1 old_string 9|2 new_string 9"]}}class Ss extends w{constructor(t){super(),this.stringReplacements=[],this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["UpdateProjectParams|1 string_replacements #0*|2 summary 9",ys]}}class qs extends w{constructor(t){super(),this.success=!1,this.updatedPlan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["UpdateProjectResult|1 success 8|2 updated_plan 9"]}}class Bs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["UpdateProjectStream"]}}class Is extends w{constructor(t){super(),this.title="",this.questions=[],this.runAsync=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["AskQuestionParams|1 title 9|2 questions #0*|3 run_async 8",Ps]}}class Ps extends w{constructor(t){super(),this.id="",this.prompt="",this.options=[],this.allowMultiple=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["AskQuestionParams.Question|1 id 9|2 prompt 9|3 options #0*|4 allow_multiple 8|5 prompt_markdown 9?",bs]}}class bs extends w{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["AskQuestionParams.Option|1 id 9|2 label 9"]}}class Rs extends w{constructor(t){super(),this.answers=[],this.isAsync=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["AskQuestionResult|1 answers #0*|2 is_async 8",vs]}}class vs extends w{constructor(t){super(),this.questionId="",this.selectedOptionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["AskQuestionResult.Answer|1 question_id 9|2 selected_option_ids 9*|3 freeform_text 9?"]}}class xs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["AskQuestionStream|1 params #0",Is]}}class ks extends w{constructor(t){super(),this.fromModeId="",this.toModeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["SwitchModeParams|1 from_mode_id 9|2 to_mode_id 9|3 explanation 9?"]}}class Es extends w{constructor(t){super(),this.fromModeId="",this.toModeId="",this.autoApproved=!1,this.userApproved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["SwitchModeResult|1 from_mode_id 9|2 to_mode_id 9|3 auto_approved 8|4 user_approved 8"]}}class Cs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["SwitchModeStream|1 params #0",ks]}}class Ts extends w{constructor(t){super(),this.actions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["ComputerUseParams|1 actions #0*",h.ho]}}class Us extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Us,t,r)}static $(){return["ComputerUseResult|1 success #0 result|2 error #1 result",h.Wd,h.Jb]}}class As extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(As,t,r)}static $(){return["ComputerUseStream|1 params #0",Ts]}}class $s extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($s,t,r)}static $(){return["WriteShellStdinStream|1 params #0",i.LL]}}class Ms extends w{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ms,t,r)}static $(){return["WebFetchParams|1 url 9"]}}class Os extends w{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["WebFetchResult|1 url 9|2 markdown 9?|3 error 9?"]}}class Ds extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["WebFetchStream|1 params #0",Ms]}}class Ns extends w{constructor(t){super(),this.summary="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["ReportBugfixResultsParams|1 summary 9|2 results #0*",g.Y6]}}class Gs extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["ReportBugfixResultsResult|1 success #0 result|2 error #1 result",g.RH,g.q3]}}class Ls extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["ReportBugfixResultsStream|1 params #0",Ns]}}class Fs extends w{constructor(t){super(),this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["McpAuthParams|1 server_identifier 9"]}}class Ks extends w{constructor(t){super(),this.success=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["McpAuthResult|1 success 8|2 message 9"]}}class zs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["McpAuthStream"]}}class js extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["ConnectScmParams|1 github #0|2 provider 9?|3 provider_instance 9?|4 reconnect 8?|5 instance_host 9?",Hs]}}class Hs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["ConnectScmGithub|1 repository #0|2 ghe_application 9?",Ws]}}class Ws extends w{constructor(t){super(),this.owner="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["ConnectScmGithubRepository|1 owner 9|2 repo 9"]}}class Qs extends w{constructor(t){super(),this.success=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["ConnectScmResult|1 success 8|2 message 9"]}}class Vs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["ConnectScmStream"]}}},"../proto/dist/generated/aiserver/v1/usage_pb.js"(t,r,e){e.d(r,{GF:()=>R,aq:()=>b,kK:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"UsageEventKind",[[0,"UNSPECIFIED"],[1,"USAGE_BASED"],[2,"USER_API_KEY"],[3,"INCLUDED_IN_PRO"],[4,"INCLUDED_IN_BUSINESS"],[5,"ERRORED_NOT_CHARGED"],[6,"ABORTED_NOT_CHARGED"],[7,"CUSTOM_SUBSCRIPTION"],[8,"INCLUDED_IN_PRO_PLUS"],[9,"INCLUDED_IN_ULTRA"],[10,"FREE_CREDIT"]],1);class u extends o{constructor(t){super(),this.modelId="",this.maxMode=!1,this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ModelSelectionSnapshot|1 model_id 9|2 max_mode 8|3 parameters #0*",c]}}class c extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ModelSelectionSnapshot.ModelParameterValue|1 id 9|2 value 9"]}}class l extends o{constructor(t){super(),this.feature={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["UsageEventDetails|1 chat #0 feature|2 context_chat #1 feature|3 cmd_k #2 feature|4 terminal_cmd_k #3 feature|5 ai_review_accepted_comment #4 feature|6 interpreter_chat #5 feature|7 slash_edit #6 feature|8 composer #7 feature|9 fast_apply #8 feature|10 warm_composer #9 feature|11 bug_finder_trigger_v1 #10 feature|12 tool_call_composer #11 feature|14 bug_bot #12 feature|15 prompt_hook #13 feature|20 agent_sdk_managed #14?|13 override_num_requests_counted 5?|16 override_num_requests_counted_millis 5?|17 routed_model 9?|18 requested_model_selection #15?|19 effective_model_selection #15?",p,w,y,S,q,B,I,g,h,J,f,_,d,m,P,u]}}class m extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["UsageEventDetails.PromptHook|1 model_intent 9|2 token_usage #0?|3 max_mode 8?|4 is_token_based_call 8?",v]}}class f extends o{constructor(t){super(),this.inBackgroundSubsidized=!1,this.costCents=0,this.isFast=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UsageEventDetails.BugFinderTriggerV1|1 in_background_subsidized 8|2 cost_cents 5|3 is_fast 8"]}}class d extends o{constructor(t){super(),this.modelIntent="",this.isTokenBasedCall=!1,this.maxMode=!1,this.discount={case:void 0},this.billingMode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["UsageEventDetails.BugBot|1 model_intent 9|2 token_usage #0|3 is_token_based_call 8|4 max_mode 8|5 no_discount #1 discount|6 free #1 discount|7 billing_mode 9",v,n.Empty]}}class p extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["UsageEventDetails.Chat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class h extends o{constructor(t){super(),this.isOptimistic=!1,this.willingToPayExtraForSpeed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["UsageEventDetails.FastApply|1 is_optimistic 8|2 willing_to_pay_extra_for_speed 8"]}}class g extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["UsageEventDetails.Composer|1 model_intent 9|2 override_num_requests_counted 5?|3 is_headless 8?|4 is_token_based_call 8?|5 token_usage #0?|6 max_mode 8?",v]}}class _ extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["UsageEventDetails.ToolCallComposer|1 model_intent 9|2 override_num_requests_counted 5?|3 is_headless 8?|4 is_token_based_call 8?|5 token_usage #0?|6 max_mode 8?",v]}}class J extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["UsageEventDetails.WarmComposer|1 model_intent 9|2 max_mode 8?"]}}class w extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["UsageEventDetails.ContextChat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class y extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["UsageEventDetails.CmdK|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class S extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["UsageEventDetails.TerminalCmdK|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class q extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["UsageEventDetails.AiReviewAcceptedComment"]}}class B extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["UsageEventDetails.InterpreterChat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class I extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["UsageEventDetails.SlashEdit|1 model_intent 9|2 max_mode 8?"]}}class P extends o{constructor(t){super(),this.managedType="",this.applicationSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["UsageEventDetails.AgentSdkManagedProduct|1 managed_type 9|2 application_slug 9"]}}class b extends o{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.isSlow=!1,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["UsageEvent|1 timestamp 3|2 details #0|3 subscription_product_id 9?|4 usage_price_id 9?|5 is_slow 8|6 status 9|7 owning_user 9?|8 owning_team 9?|9 price_cents 2?|10 team_membership_type 9?",l]}}class R extends o{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.model="",this.kind=a.UNSPECIFIED,this.maxMode=!1,this.requestsCosts=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["UsageEventDisplay|1 timestamp 3|2 model 9|3 kind #0|4 custom_subscription_name 9?|5 max_mode 8|6 requests_costs 2|7 usage_based_costs 9?|8 is_token_based_call 8?|9 token_usage #1?|10 owning_user 9?|11 owning_team 9?|12 user_email 9?|13 cursor_token_fee 2?|14 is_chargeable 8?|15 service_account_name 9?|16 service_account_id 9?|17 is_headless 8?|18 charged_cents 2?|19 cloud_agent_id 9?|20 automation_id 9?|21 automation_managed_type 9?|22 client_type 9?|23 conversation_id 9?|24 subscription_product_id 9?|25 pr_author 9?|26 repo 9?|27 pr_number 5?|28 usage_event_id 9?|29 usage_type 9?|30 credit_consumed_cents 2?",a,v]}}class v extends o{constructor(t){super(),this.inputTokens=0,this.outputTokens=0,this.cacheWriteTokens=0,this.cacheReadTokens=0,this.totalCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["TokenUsage|1 input_tokens 5|2 output_tokens 5|3 cache_write_tokens 5|4 cache_read_tokens 5|5 total_cents 2|6 discount_percent_off 5?|7 enterprise_usage_discount_percent 2?|8 enterprise_product_usage_discount_percent 2?"]}}},"../proto/dist/generated/aiserver/v1/utils_pb.js"(t,r,e){e.d(r,{Az:()=>ot,Bo:()=>pt,CX:()=>Y,DX:()=>nt,EZ:()=>Ot,Ei:()=>I,FY:()=>Tt,Gm:()=>W,LI:()=>xt,M6:()=>Q,MT:()=>E,NG:()=>U,Nj:()=>c,O2:()=>ht,Q9:()=>kt,QP:()=>B,Se:()=>f,U$:()=>et,U1:()=>L,UR:()=>It,Uf:()=>C,Us:()=>Ct,Vq:()=>g,Wf:()=>q,Wj:()=>X,Xr:()=>bt,Y1:()=>st,Yd:()=>l,ZH:()=>O,_u:()=>P,bO:()=>tt,bV:()=>_t,c5:()=>Dt,d7:()=>T,df:()=>J,e$:()=>m,ej:()=>mt,ek:()=>_,fL:()=>M,gO:()=>p,l2:()=>y,lo:()=>u,n6:()=>b,o$:()=>S,oQ:()=>D,ot:()=>vt,qW:()=>K,qv:()=>Et,sr:()=>Rt,vj:()=>ct,wZ:()=>rt,x$:()=>a,yM:()=>lt,zH:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"LintSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFO"],[4,"HINT"],[5,"AI"]],1),u=(0,s.QT)(n.proto3,i,"FeatureType",[[0,"UNSPECIFIED"],[1,"EDIT"],[2,"GENERATE"],[3,"INLINE_LONG_COMPLETION"]],1),c=(0,s.QT)(n.proto3,i,"EmbeddingModel",[[0,"UNSPECIFIED"],[1,"VOYAGE_CODE_2"],[2,"TEXT_EMBEDDINGS_LARGE_3"],[3,"QWEN_1_5B_CUSTOM"],[4,"MOCK_CHUNKER_ERROR"],[5,"QWEN_1_5B_0618_CUSTOM"],[6,"QWEN_1_5B_0618_FP8_MM_CUSTOM"]],1);class l extends o{constructor(t){super(),this.line=0,this.column=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CursorPosition|1 line 5|2 column 5"]}}class m extends o{constructor(t){super(),this.totalmem=0,this.freemem=0,this.loadavg=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["VscodeOSStatistics|1 totalmem 1|2 freemem 1|3 loadavg 1*"]}}class f extends o{constructor(t){super(),this.type="",this.release="",this.arch="",this.platform="",this.cpus=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["VscodeOSProperties|1 type 9|2 release 9|3 arch 9|4 platform 9|5 cpus #0*",d]}}class d extends o{constructor(t){super(),this.model="",this.speed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["VscodeCPUProperties|1 model 9|2 speed 1"]}}class p extends o{constructor(t){super(),this.workspaceUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["EnvironmentInfo|1 exthost_platform 9?|2 exthost_arch 9?|3 exthost_release 9?|4 exthost_shell 9?|5 local_timestamp 9?|6 workspace_uris 9*|7 cursor_version 9?|8 is_remote 8?|9 local_os_type 9?|10 home_directory 9?|11 local_timezone 9?"]}}class h extends o{constructor(t){super(),this.selectionStartLineNumber=0,this.selectionStartColumn=0,this.positionLineNumber=0,this.positionColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SelectionWithOrientation|1 selection_start_line_number 5|2 selection_start_column 5|3 position_line_number 5|4 position_column 5"]}}class g extends o{constructor(t){super(),this.cwd="",this.ref="",this.baseRef="",this.mergeBase=!1,this.targetPaths=[],this.maxUntrackedFiles=0,this.submoduleRecurseDepth=0,this.includeSpaceChanges=!1,this.committedOnly=!1,this.computePatchId=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GetDiffRequest|1 cwd 9|2 ref 9|3 base_ref 9|4 merge_base 8|5 target_paths 9*|6 unified_context_lines 5?|7 max_untracked_files 5|9 submodule_recurse_depth 5|10 include_space_changes 8|11 committed_only 8|12 compute_patch_id 8|13 return_head_sha 8?|14 max_response_bytes 5?|15 max_files_with_contents 13?|16 max_content_bytes 13?|8 output_format #0?",_]}}var _=(0,s.QT)(n.proto3,i,"GetDiffRequest.OutputFormat",[[0,"UNSPECIFIED"],[1,"NAME_STATUS"],[2,"NAME_STATUS_AND_NUMSTAT"],[3,"FILE_DIFFS"],[4,"DIFFS_WITH_BEFORE_AND_AFTER"]],1);class J extends o{constructor(t){super(),this.submoduleDiffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["GetDiffResponse|1 diff #0|2 submodule_diffs #1*|3 patch_id 9?|4 head_sha 9?|5 has_uncommitted_changes 8?",S,w]}}class w extends o{constructor(t){super(),this.relativePath="",this.errored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GetDiffResponse.SubmoduleDiff|1 relative_path 9|2 diff #0|3 errored 8",S]}}class y extends o{constructor(t){super(),this.startLine=0,this.endLineInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SimplestRange|1 start_line 5|2 end_line_inclusive 5"]}}class S extends o{constructor(t){super(),this.diffs=[],this.diffType=q.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["GitDiff|1 diffs #0*|2 diff_type #1|3 file_contents_omitted 8?",B,q]}}var q=(0,s.QT)(n.proto3,i,"GitDiff.DiffType",[[0,"UNSPECIFIED"],[1,"DIFF_TO_HEAD"],[2,"DIFF_FROM_BRANCH_TO_MAIN"]],1);class B extends o{constructor(t){super(),this.added=0,this.removed=0,this.from="",this.to="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["FileDiff|4 added 5|5 removed 5|1 from 9|2 to 9|3 chunks #0*|6 before_file_contents 9?|7 after_file_contents 9?|8 is_generated 8?|9 old_mode 9?|10 new_mode 9?",I]}}class I extends o{constructor(t){super(),this.content="",this.lines=[],this.oldStart=0,this.oldLines=0,this.newStart=0,this.newLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["FileDiff.Chunk|1 content 9|2 lines 9*|3 old_start 5|4 old_lines 5|5 new_start 5|6 new_lines 5"]}}class P extends o{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumberInclusive=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SimpleRange|1 start_line_number 5|2 start_column 5|3 end_line_number_inclusive 5|4 end_column 5"]}}class b extends o{constructor(t){super(),this.remoteUrl="",this.commitId="",this.gitPatch="",this.unsavedFiles=[],this.unixTimestampMs=0,this.openEditors=[],this.fileDiffHistories=[],this.branchName="",this.branchNotes="",this.branchNotesRich="",this.globalNotes="",this.pastThoughts=[],this.baseBranchName="",this.baseBranchCommitId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["CmdKDebugInfo|1 remote_url 9|2 commit_id 9|3 git_patch 9|4 unsaved_files #0*|5 unix_timestamp_ms 1|6 open_editors #1*|7 file_diff_histories #2*|8 branch_name 9|9 branch_notes 9|12 branch_notes_rich 9|10 global_notes 9|11 past_thoughts #3*|13 base_branch_name 9|14 base_branch_commit_id 9",R,v,x,k]}}class R extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["CmdKDebugInfo.UnsavedFiles|1 relative_workspace_path 9|2 contents 9"]}}class v extends o{constructor(t){super(),this.relativeWorkspacePath="",this.editorGroupIndex=0,this.editorGroupId=0,this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["CmdKDebugInfo.OpenEditor|1 relative_workspace_path 9|2 editor_group_index 5|3 editor_group_id 5|4 is_active 8"]}}class x extends o{constructor(t){super(),this.fileName="",this.diffHistory=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["CmdKDebugInfo.CppFileDiffHistory|1 file_name 9|2 diff_history 9*"]}}class k extends o{constructor(t){super(),this.text="",this.timeInUnixSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["CmdKDebugInfo.PastThought|1 text 9|2 time_in_unix_seconds 1"]}}class E extends o{constructor(t){super(),this.startLineNumber=0,this.endLineNumberInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["LineRange|1 start_line_number 5|2 end_line_number_inclusive 5"]}}class C extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["CursorRange|1 start_position #0|2 end_position #0",l]}}class T extends o{constructor(t){super(),this.text="",this.lineNumber=0,this.isSignature=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["DetailedLine|1 text 9|2 line_number 2|3 is_signature 8"]}}class U extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",this.detailedLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["CodeBlock|1 relative_workspace_path 9|2 file_contents 9?|9 file_contents_length 5?|3 range #0|4 contents 9|5 signatures #1|6 override_contents 9?|7 original_contents 9?|8 detailed_lines #2*|10 file_git_context #3",C,A,T,M]}}class A extends o{constructor(t){super(),this.ranges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["CodeBlock.Signatures|1 ranges #0*",C]}}class $ extends o{constructor(t){super(),this.commit="",this.author="",this.date="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["GitCommit|1 commit 9|2 author 9|3 date 9|4 message 9"]}}class M extends o{constructor(t){super(),this.commits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["FileGit|1 commits #0*",$]}}class O extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["File|1 relative_workspace_path 9|2 contents 9|3 file_git_context #0",M]}}class D extends o{constructor(t){super(),this.message="",this.severity=N.UNSPECIFIED,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["Diagnostic|1 message 9|2 range #0|3 severity #1|4 related_information #2*",C,N,G]}}var N=(0,s.QT)(n.proto3,i,"Diagnostic.DiagnosticSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFORMATION"],[4,"HINT"]],1);class G extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["Diagnostic.RelatedInformation|1 message 9|2 range #0",C]}}class L extends o{constructor(t){super(),this.message="",this.severity=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["Lint|1 message 9|2 range #0|3 severity #1",P,a]}}class F extends o{constructor(t){super(),this.content="",this.score=0,this.relativePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["BM25Chunk|1 content 9|2 range #0|3 score 5|4 relative_path 9",y]}}class K extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",this.relyOnFilesync=!1,this.cells=[],this.topChunks=[],this.contentsStartAtLine=0,this.dataframes=[],this.totalNumberOfLines=0,this.languageId="",this.diagnostics=[],this.cellStartLines=[],this.workspaceRootPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["CurrentFileInfo|1 relative_workspace_path 9|2 contents 9|18 rely_on_filesync 8|17 sha_256_hash 9?|16 cells #0*|10 top_chunks #1*|9 contents_start_at_line 5|3 cursor_position #2|4 dataframes #3*|8 total_number_of_lines 5|5 language_id 9|6 selection #4|11 alternative_version_id 5?|7 diagnostics #5*|14 file_version 5?|15 cell_start_lines 5*|19 workspace_root_path 9|20 line_ending 9?",z,F,l,Y,C,D]}}class z extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["CurrentFileInfo.NotebookCell"]}}class j extends o{constructor(t){super(),this.apiKey="",this.baseUrl="",this.deployment="",this.useAzure=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["AzureState|1 api_key 9|2 base_url 9|3 deployment 9|4 use_azure 8"]}}class H extends o{constructor(t){super(),this.accessKey="",this.secretKey="",this.region="",this.useBedrock=!1,this.sessionToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["BedrockState|1 access_key 9|2 secret_key 9|3 region 9|4 use_bedrock 8|5 session_token 9"]}}class W extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ModelDetails|1 model_name 9?|2 api_key 9?|3 enable_ghost_mode 8?|4 azure_state #0?|5 enable_slow_pool 8?|6 openai_api_base_url 9?|7 bedrock_state #1?|8 max_mode 8?",j,H]}}class Q extends o{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["CloudAgentModelSelection|1 model_id 9|2 parameters #0*|3 max_mode 8?",V]}}class V extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["CloudAgentModelSelection.ParameterValue|1 id 9|2 value 9"]}}class X extends o{constructor(t){super(),this.modelName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["ModelInfo|1 model_name 9"]}}class Y extends o{constructor(t){super(),this.name="",this.shape="",this.dataDimensionality=0,this.columns=[],this.rowCount=0,this.indexColumn="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["DataframeInfo|1 name 9|2 shape 9|3 data_dimensionality 5|6 columns #0*|7 row_count 5|8 index_column 9",Z]}}class Z extends o{constructor(t){super(),this.key="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["DataframeInfo.Column|1 key 9|2 type 9"]}}class tt extends o{constructor(t){super(),this.message="",this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["LinterError|1 message 9|2 range #0|3 source 9?|4 related_information #1*|5 severity #2?|6 is_stale 8?",C,G,N]}}class rt extends o{constructor(t){super(),this.relativeWorkspacePath="",this.errors=[],this.fileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["LinterErrors|1 relative_workspace_path 9|2 errors #0*|3 file_contents 9",tt]}}class et extends o{constructor(t){super(),this.relativeWorkspacePath="",this.errors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["LinterErrorsWithoutFileContents|1 relative_workspace_path 9|2 errors #0*",tt]}}class nt extends o{constructor(t){super(),this.name="",this.description="",this.environments=[],this.disabledEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["CursorRule|1 name 9|2 description 9|3 body 9?|4 is_from_glob 8?|5 always_apply 8?|6 attach_to_background_agents 8?|7 full_path 9?|8 environments 9*|9 disabled_environments 9*|10 plugin 9?|11 marketplace 9?"]}}class st extends o{constructor(t){super(),this.context="",this.rules=[],this.mcpInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["ExplicitContext|1 context 9|2 repo_context 9?|3 rules #0*|4 mode_specific_context 9?|5 mcp_instructions #1*",nt,it]}}class it extends o{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.instructions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["MCPInstructions|1 server_name 9|2 server_identifier 9|3 instructions 9"]}}n.proto3;class ot extends o{constructor(t){super(),this.name="",this.detail="",this.kind=at.UNSPECIFIED,this.containerName="",this.children=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["DocumentSymbol|1 name 9|2 detail 9|3 kind #0|5 container_name 9|6 range #1|7 selection_range #1|8 children #2*",at,ut,ot]}}var at=(0,s.QT)(n.proto3,i,"DocumentSymbol.SymbolKind",[[0,"UNSPECIFIED"],[1,"FILE"],[2,"MODULE"],[3,"NAMESPACE"],[4,"PACKAGE"],[5,"CLASS"],[6,"METHOD"],[7,"PROPERTY"],[8,"FIELD"],[9,"CONSTRUCTOR"],[10,"ENUM"],[11,"INTERFACE"],[12,"FUNCTION"],[13,"VARIABLE"],[14,"CONSTANT"],[15,"STRING"],[16,"NUMBER"],[17,"BOOLEAN"],[18,"ARRAY"],[19,"OBJECT"],[20,"KEY"],[21,"NULL"],[22,"ENUM_MEMBER"],[23,"STRUCT"],[24,"EVENT"],[25,"OPERATOR"],[26,"TYPE_PARAMETER"]],1);class ut extends o{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumber=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["DocumentSymbol.Range|1 start_line_number 5|2 start_column 5|3 end_line_number 5|4 end_column 5"]}}class ct extends o{constructor(t){super(),this.error=lt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["ErrorDetails|1 error #0|2 details #1|3 is_expected 8?",lt,mt]}}var lt=(0,s.QT)(n.proto3,i,"ErrorDetails.Error",[[0,"UNSPECIFIED"],[1,"BAD_API_KEY"],[42,"BAD_USER_API_KEY"],[2,"NOT_LOGGED_IN"],[3,"INVALID_AUTH_ID"],[4,"NOT_HIGH_ENOUGH_PERMISSIONS"],[18,"AGENT_REQUIRES_LOGIN"],[5,"BAD_MODEL_NAME"],[39,"NOT_FOUND"],[40,"DEPRECATED"],[6,"USER_NOT_FOUND"],[7,"FREE_USER_RATE_LIMIT_EXCEEDED"],[8,"PRO_USER_RATE_LIMIT_EXCEEDED"],[9,"FREE_USER_USAGE_LIMIT"],[10,"PRO_USER_USAGE_LIMIT"],[41,"RESOURCE_EXHAUSTED"],[11,"AUTH_TOKEN_NOT_FOUND"],[12,"AUTH_TOKEN_EXPIRED"],[13,"OPENAI"],[14,"OPENAI_RATE_LIMIT_EXCEEDED"],[20,"MAX_TOKENS"],[23,"PRO_USER_ONLY"],[21,"USER_ABORTED_REQUEST"],[25,"TIMEOUT"],[22,"GENERIC_RATE_LIMIT_EXCEEDED"],[28,"GPT_4_VISION_PREVIEW_RATE_LIMIT"],[29,"CUSTOM_MESSAGE"],[30,"OUTDATED_CLIENT"],[31,"CLAUDE_IMAGE_TOO_LARGE"],[33,"FILE_NOT_FOUND"],[34,"API_KEY_RATE_LIMIT"],[35,"DEBOUNCED"],[36,"BAD_REQUEST"],[37,"REPOSITORY_SERVICE_REPOSITORY_IS_NOT_INITIALIZED"],[38,"UNAUTHORIZED"],[43,"CONVERSATION_TOO_LONG"],[44,"USAGE_PRICING_REQUIRED"],[45,"USAGE_PRICING_REQUIRED_CHANGEABLE"],[46,"GITHUB_NO_USER_CREDENTIALS"],[47,"GITHUB_USER_NO_ACCESS"],[48,"GITHUB_APP_NO_ACCESS"],[49,"GITHUB_MULTIPLE_OWNERS"],[50,"RATE_LIMITED"],[51,"RATE_LIMITED_CHANGEABLE"],[52,"CUSTOM"],[53,"HOOKS_BLOCKED"],[54,"SUSPICIOUS_USAGE_BLOCKED"],[55,"EXTENSION_HOST_TIMEOUT"],[56,"NETWORK_ERROR"],[57,"PROVIDER_ERROR"],[58,"MODEL_BLOCKED"],[59,"INTERNAL"],[60,"MAX_MODE_REQUIRED"],[61,"MODEL_NO_LONGER_SUPPORTED"],[62,"PRICING_WARNING"],[63,"SLOW_POOL"],[64,"UNSUPPORTED_REGION"],[65,"ACCOUNT_CLOSED"],[66,"TENANT_RESTRICTION_VIOLATION"]],1);class mt extends o{constructor(t){super(),this.title="",this.detail="",this.buttons=[],this.additionalInfo={},this.planChoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["CustomErrorDetails|1 title 9|2 detail 9|3 allow_command_links_potentially_unsafe_please_only_use_for_handwritten_trusted_markdown 8?|4 is_retryable 8?|5 show_request_id 8?|6 should_show_immediate_error 8?|8 buttons #0*|7 additional_info 9,9|9 plan_choices #1*|10 analytics_metadata #2?",pt,dt,ft]}}class ft extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ErrorAnalyticsMetadata|1 action_required 9?"]}}class dt extends o{constructor(t){super(),this.label="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["PlanChoice|1 label 9|2 sublabel 9?|3 description 9?|4 value 9"]}}class pt extends o{constructor(t){super(),this.label="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["ErrorButton|1 label 9|2 upgrade #0 action|3 switch_model #1 action|4 configure_spend_limit #2 action|5 url #3 action|6 upgrade_choice #4 action|7 dashboard_action #5 action|8 reload_window #6 action|9 client_action #7 action",wt,yt,qt,Bt,Jt,_t,gt,ht]}}class ht extends o{constructor(t){super(),this.commandId="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["ClientAction|1 command_id 9|2 args 9,9"]}}class gt extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["ReloadWindowAction"]}}class _t extends o{constructor(t){super(),this.action="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["DashboardAction|1 action 9|2 args 9,9|3 success_message 9?"]}}class Jt extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jt,t,r)}static $(){return["UpgradeChoice"]}}class wt extends o{constructor(t){super(),this.membershipToUpgradeTo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["UpgradeAction|1 membership_to_upgrade_to 9|2 try_immediate_upgrade 8?|3 allow_trial 8?|4 dashboard_action #0?",_t]}}class yt extends o{constructor(t){super(),this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["SwitchModelAction|1 suggested_model 9?|2 parameters #0*|3 max_mode 8?",St]}}class St extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(St,t,r)}static $(){return["SwitchModelAction.ModelParameterValue|1 id 9|2 value 9"]}}class qt extends o{constructor(t){super(),this.confirmLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["ConfigureSpendLimitAction|1 confirm_label 9"]}}class Bt extends o{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["UrlAction|1 url 9"]}}class It extends o{constructor(t){super(),this.data=new Uint8Array(0),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["ImageProto|1 data 12|2 dimension #0|3 uuid 9|4 task_specific_description 9?",Pt]}}class Pt extends o{constructor(t){super(),this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["ImageProto.Dimension|1 width 5|2 height 5"]}}class bt extends o{constructor(t){super(),this.markdown="",this.bubbleId="",this.sectionIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bt,t,r)}static $(){return["ChatQuote|1 markdown 9|2 bubble_id 9|3 section_index 5"]}}class Rt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rt,t,r)}static $(){return["ChatExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?"]}}class vt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["ComposerExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?"]}}class xt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["CmdKExternalLink|1 url 9|2 uuid 9"]}}class kt extends o{constructor(t){super(),this.note="",this.commitHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["CommitNote|1 note 9|2 commit_hash 9"]}}class Et extends o{constructor(t){super(),this.note="",this.commitHash="",this.embeddings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["CommitNoteWithEmbeddings|1 note 9|2 commit_hash 9|3 embeddings 1*"]}}class Ct extends o{constructor(t){super(),this.diff="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["CommitDiffString|1 diff 9"]}}class Tt extends o{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.languageIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["CodeChunk|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 summarization_strategy #0?|5 language_identifier 9|6 intent #1?|7 is_final_version 8?|8 is_first_version 8?",At,Ut]}}var Ut=(0,s.QT)(n.proto3,i,"CodeChunk.Intent",[[0,"UNSPECIFIED"],[1,"COMPOSER_FILE"],[2,"COMPRESSED_COMPOSER_FILE"]],1),At=(0,s.QT)(n.proto3,i,"CodeChunk.SummarizationStrategy",[[0,"NONE_UNSPECIFIED"],[1,"SUMMARIZED"],[2,"EMBEDDED"]],1);class $t extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["RCPCallFrame|1 function_name 9?|2 url 9?|3 line_number 5?|4 column_number 5?"]}}class Mt extends o{constructor(t){super(),this.callFrames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["RCPStackTrace|1 call_frames #0*|2 raw_stack_trace 9?",$t]}}class Ot extends o{constructor(t){super(),this.message="",this.timestamp=0,this.level="",this.clientName="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["RCPLogEntry|1 message 9|2 timestamp 1|3 level 9|4 client_name 9|5 session_id 9|6 stack_trace #0?|7 object_data_json 9?",Mt]}}class Dt extends o{constructor(t){super(),this.element="",this.xpath="",this.textContent="",this.extra="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["RCPUIElementPicked|1 element 9|2 xpath 9|3 text_content 9|4 extra 9|5 component 9?|6 component_props_json 9?"]}}},"../proto/dist/runtime/compact.js"(t,r,e){e.d(r,{HL:()=>u,QT:()=>l,kU:()=>i});var n=e("@bufbuild/protobuf");const s={};function i(t,r,e){return Object.defineProperty(t,r,{value:e,writable:!0,enumerable:!0,configurable:!0}),e}function o(t,r,e){if("#"!==e.charAt(0))return{kind:"scalar",T:Number(e)};const n=r[Number(e.slice(1))];return"function"==typeof n?{kind:"message",T:n}:{kind:"enum",T:t.getEnumType(n)}}function a(t){return"?"===t?{opt:!0}:"*"===t?{repeated:!0}:void 0===t?s:{oneof:t}}class u extends n.Message{static get typeName(){const t=c(this);return i(t,"typeName",t.$p()+function(t){const r=t[0],e=r.indexOf("|");return-1===e?r:r.slice(0,e)}(t.$()))}static get fields(){const t=c(this),r=t.$(),e=t.runtime;return i(t,"fields",e.util.newFieldList((()=>function(t,r){const[e,...n]=r,s=e.split("|"),i=[];for(let r=1;r"_"+t))).toUpperCase()+"_"}(i);a=n.map((t=>t[1])),o=a.map((r=>t+r))}else o=n.map((t=>t[1])),a=void 0===s?function(t,r){const e=(t.charAt(0)+t.slice(1).replace(/[A-Z]/g,(t=>"_"+t))).toLowerCase()+"_",n=[];for(const t of r){if(!t.toLowerCase().startsWith(e))return r.slice();const s=t.slice(e.length);if(""===s||/^[0-9]/.test(s))return r.slice();n.push(s)}return n}(i,o):s;const u={},c=[];for(let t=0;tn});class n{}},"../utils/dist/fresh-uuid.js"(t,r,e){e.d(r,{C:()=>a});var n=e("node:crypto"),s=e("node:fs");let i,o=!1;function a(){const t=function(){if(!o)try{void 0===i&&(i=(0,s.openSync)("/dev/urandom","r"));const t=Buffer.alloc(16);let r=0;for(;r<16;){const e=(0,s.readSync)(i,t,r,16-r,null);if(e<=0)return;r+=e}return t}catch{if(o=!0,void 0!==i){try{(0,s.closeSync)(i)}catch{}i=void 0}return}}();return void 0===t?(0,n.randomUUID)({disableEntropyCache:!0}):function(t){const r=t[6]??0,e=t[8]??0;t[6]=15&r|64,t[8]=63&e|128;const n=t.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(t)}},"../utils/dist/private-file.js"(t,r,e){e.d(r,{Pl:()=>l,rV:()=>m});var n=e("node:crypto"),s=e("node:fs/promises"),i=e("node:path"),o=e("../utils/dist/promise-extras.js");const a=[10,25,50,100,200],u=new Set(["EPERM","EACCES","EBUSY"]),c=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EPERM"]);async function l(t,r,e={}){const c=(0,i.dirname)(t);await async function(t){await(0,s.mkdir)((0,i.dirname)(t),{recursive:!0});try{await(0,s.mkdir)(t,{mode:448})}catch(t){if("EEXIST"!==p(t))throw t}}(c),!1!==e.privateDirectory&&await f(c,"directory").catch(d);const l=(0,i.join)(c,`.${(0,i.basename)(t)}.${(0,n.randomBytes)(6).toString("hex")}.tmp`),m=await(0,s.open)(l,"wx",384);try{try{await m.chmod(384).catch(d),await m.writeFile(r),await m.sync()}finally{await m.close()}await async function(t,r){if("win32"===process.platform){for(const e of a)try{return void await(0,s.rename)(t,r)}catch(t){const r=p(t);if(void 0===r||!u.has(r))throw t;await(0,o.cb)(e)}await(0,s.rename)(t,r)}else await(0,s.rename)(t,r)}(l,t)}catch(t){throw await(0,s.rm)(l,{force:!0}),t}}async function m(t,r={}){"win32"!==process.platform&&(!1!==r.privateDirectory&&await f((0,i.dirname)(t),"directory").catch((()=>{})),await f(t,"file").catch((()=>{})))}async function f(t,r){if("win32"===process.platform)return;let e;try{e="file"===r?await(0,s.lstat)(t):await(0,s.stat)(t)}catch(t){if("ENOENT"===p(t))return;throw t}if(e.isSymbolicLink())return;const{mode:n,uid:i}=e;63&n&&(void 0!==process.getuid&&i!==process.getuid()||await(0,s.chmod)(t,511&n&-64))}function d(t){const r=p(t);if(!("win32"===process.platform||void 0!==r&&c.has(r)))throw t}function p(t){return t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:void 0}},"../utils/dist/promise-extras.js"(t,r,e){function n({array:t,selector:r,max:e,settleRejections:n,onSettled:s}){const i=Math.min(t.length,e>=1?e:1);return new Promise(((e,o)=>{let a=0,u=0,c=!1;const l=t=>{c=!0,o(t)},m=()=>{for(;!c&&u{u--,c||(s(e,{status:"fulfilled",value:t}),m())}),(t=>{u--,c||(n?(s(e,{status:"rejected",reason:t}),m()):l(t))}))}c||0!==u||a!==t.length||e()};m()}))}async function s(t,r,e){const{max:s=4}=e??{},i=new Map;return await n({array:t,selector:r,max:s,settleRejections:!1,onSettled:(r,e)=>{"fulfilled"===e.status&&i.set(t[r],e.value)}}),i}async function i(t,r,e){const{max:s=4}=e??{},i=[];return await n({array:t,selector:r,max:s,settleRejections:!1,onSettled:(t,r)=>{"fulfilled"===r.status&&(i[t]=r.value)}}),i}async function o(t,r,e){const{max:s=4}=e??{},i=[];return await n({array:t,selector:r,max:s,settleRejections:!0,onSettled:(t,r)=>{i[t]=r}}),i}function a(t){return new Promise((r=>{setTimeout(r,t)}))}function u(t,r){return new Promise((e=>{if(r.aborted)return void e();const n=()=>{clearTimeout(s),e()},s=setTimeout((()=>{r.removeEventListener("abort",n),e()}),t);r.addEventListener("abort",n,{once:!0})}))}e.d(r,{MU:()=>c,O$:()=>m,PH:()=>i,TJ:()=>f,cb:()=>a,st:()=>u,up:()=>o,wj:()=>l,xb:()=>s});class c extends Error{constructor(t){super(t),this.name="TimeoutError"}}function l(t,r,e){return new Promise(((n,s)=>{const i=setInterval((()=>{clearInterval(i),s(new c(e??`Promise timed out after ${r}ms`))}),r);t.then((t=>{clearInterval(i),n(t)}),(t=>{clearInterval(i),s(t)}))}))}async function m(t,r=3){for(let e=0;;e++)try{return await t()}catch(t){if(e>=r)throw t}}class f{constructor(t){this.running=0,this.closed=!1,this.idleWaiters=[];const{max:r=4}=t??{};this.max=r}enqueue(t){return this.closed?Promise.reject(new Error("PromiseQueue is closed")):new Promise(((r,e)=>{const n=()=>{let n;this.running++;try{n=Promise.resolve(t())}catch(t){n=Promise.reject(t)}n.then((t=>{this.settle(),r(t)}),(t=>{this.settle(),e(t)}))};if(this.runningthis.enqueue((()=>r(t))).then((r=>{e.set(t,r)}))))),e}close(){return this.closed=!0,0===this.running&&void 0===this.waitingHead?Promise.resolve():new Promise((t=>{this.idleWaiters.push(t)}))}settle(){this.running--;const t=this.waitingHead;if(void 0!==t)return this.waitingHead=t.next,void 0===this.waitingHead&&(this.waitingTail=void 0),void t.start();if(0===this.running)for(const t of this.idleWaiters.splice(0))t()}}},"../utils/dist/workspace-paths.js"(t,r,e){e.d(r,{O2:()=>n,Rv:()=>i,r_:()=>s,sh:()=>o});const n="agent-transcripts";function s(t){return t.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function i(t,r){return function(t,...r){if(!function(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")||t.startsWith("//")}(t))return[t.replace(/\/+$/,""),...r].join("/");const e=t.replace(/\//g,"\\").replace(/\\+$/,""),n=r.map((t=>t.replace(/\//g,"\\")));return 0===e.length?["","",...n].join("\\"):[e,...n].join("\\")}(t,".cursor","projects",s(r))}function o(t){let r=encodeURIComponent(t);return r=r.replace(/%/g,"_"),r.length>200&&(r=r.slice(0,200)),r}},"./package.json"(t){t.exports={rE:"1.4.2"}}},s={};function i(t){var r=s[t];if(void 0!==r)return r.exports;var e=s[t]={exports:{}};return n[t].call(e.exports,e,e.exports,i),e.exports}i.m=n,i.n=t=>{var r=t&&t.__esModule?()=>t.default:()=>t;return i.d(r,{a:r}),r},r=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,i.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var s=Object.create(null);i.r(s);var o={};t=t||[null,r({}),r([]),r(r)];for(var a=2&n&&e;("object"==typeof a||"function"==typeof a)&&!~t.indexOf(a);a=r(a))Object.getOwnPropertyNames(a).forEach((t=>o[t]=()=>e[t]));return o.default=()=>e,i.d(s,o),s},i.d=(t,r)=>{for(var e in r)i.o(r,e)&&!i.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:r[e]})},i.f={},i.e=t=>Promise.all(Object.keys(i.f).reduce(((r,e)=>(i.f[e](t,r),r)),[])),i.u=t=>t+".js",i.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.j=57,e={18:1,57:1},i.f.require=(t,r)=>{if(!e[t]){var n=require("./"+i.u(t));e[t]||(t=>{var r=t.modules,n=t.ids,s=t.runtime;for(var o in r)i.o(r,o)&&(i.m[o]=r[o]);s&&s(i);for(var a=0;a$e,AgentBusyError:()=>a.J1,AgentConversationTurnSchema:()=>je,AgentNotFoundError:()=>a.XB,AssistantMessageSchema:()=>Xe.lK,AuthenticationError:()=>a.v3,ConfigurationError:()=>a.j1,ConversationStepSchema:()=>ze,ConversationTurnSchema:()=>We,Cursor:()=>Me,CursorAgentError:()=>a.ud,CursorAgentPlatform:()=>or,CursorSdkError:()=>a.LF,DEFAULT_LOGIN_API_KEY_TTL_MS:()=>w,DeleteNotSupportedError:()=>B.x$,EditError:()=>B.F,FILE_SYSTEM_SCAN_LIMIT:()=>H.H,FeatureUnavailableError:()=>a.zz,FileCredentialStore:()=>u.Tg,FileNotFoundError:()=>B.kG,ImageSchema:()=>Xe.JY,InMemoryCredentialStore:()=>u.fZ,InMemoryRunEventNotifier:()=>Cr,IntegrationNotConnectedError:()=>a.VW,InteractionUpdateSchema:()=>Qe.Zs,InvalidGrepPatternError:()=>B.kp,JSONL_LOCAL_AGENT_STORE_FILES:()=>ge,JsonlLocalAgentStore:()=>we,LOCAL_RUN_STREAM_EVENT_TYPE:()=>W.do,LOCAL_RUN_STREAM_SCHEMA_VERSION:()=>W.MV,LocalRunEventNotifier:()=>kr,LocalRunEventNotifierServer:()=>Er,MessageSchema:()=>Xe.RB,ModelCallCompletedUpdateSchema:()=>Qe.Dx,NestedTaskUpdateSchema:()=>Qe.tq,NetworkError:()=>a.Dr,NoMountError:()=>B.VV,PartialToolCallUpdateSchema:()=>Qe.ON,PathError:()=>B.ER,RateLimitError:()=>a.OE,ReadOnlyMountError:()=>B.QK,SdkAssistantMessageSchema:()=>Ne,SdkThinkingMessageSchema:()=>Ge,SdkUserMessageSchema:()=>Le,ShellCommandSchema:()=>Fe,ShellConversationTurnSchema:()=>He,ShellOutputDeltaUpdateSchema:()=>Qe.M7,ShellOutputSchema:()=>Ke,SummaryCompletedUpdateSchema:()=>Qe.uj,SummaryStartedUpdateSchema:()=>Qe.Wf,SummaryUpdateSchema:()=>Qe.XP,TextDeltaUpdateSchema:()=>Qe.yP,ThinkingCompletedUpdateSchema:()=>Qe.Y3,ThinkingDeltaUpdateSchema:()=>Qe.p$,TokenDeltaUpdateSchema:()=>Qe.IO,ToolCallCompletedUpdateSchema:()=>Qe.EC,ToolCallDeltaUpdateSchema:()=>Qe.fr,ToolCallStartedUpdateSchema:()=>Qe.a7,TurnEndedUpdateSchema:()=>Qe.Ed,UnknownAgentError:()=>a.c$,UnsupportedRunOperationError:()=>_t,UserMessageAppendedUpdateSchema:()=>Qe.Sb,UserMessageSchema:()=>Xe.Kx,WriteFailedError:()=>B.JA,childOverlayFs:()=>q.w1,composeLocalAgentStore:()=>Rt.In,configureCursorSdk:()=>$r.xP,convertConnectError:()=>a.e_,convertError:()=>a.q3,createAgentPlatform:()=>cr,createFileSystemTools:()=>D,createInMemoryRunEventNotifier:()=>Ar,createLocalRunEventNotifier:()=>Tr,createSdkMessageRunStreamEvent:()=>W.Nk,decodeLocalRunStreamEvent:()=>W.LN,decodeSdkMessageRunStreamEvent:()=>W.bM,emptyFs:()=>O.f1,getDefaultSdkAuthPath:()=>u.rJ,getDefaultSdkStateRoot:()=>Ct.V,getTurnType:()=>Ve,isAssistantMessage:()=>Xe.mj,isFileNotFoundError:()=>B.Wp,isInvalidGrepPatternError:()=>B.q_,isMessage:()=>Xe.K8,isTerminalLocalRunStreamEvent:()=>W.J5,isUserMessage:()=>Xe.d0,localRunStreamEventToSdkMessage:()=>W.xc,overlayFs:()=>q.Mb,paginateAgentDocuments:()=>Rt.tg,paginateCheckpointBlobIds:()=>Rt.Jg,paginateRunDocuments:()=>Rt.f1,readOnlyFs:()=>O.iK,remapPathError:()=>B.Zu,startLocalRunEventNotifierServer:()=>Ur,strReplaceOnFileSystem:()=>O.i$,tempFs:()=>O.Om,unionFs:()=>q.VL,wrapSdkError:()=>a.Nt});var a=i("./src/agent/errors.ts"),u=i("./src/agent/auth/credential-store.ts"),c=i("node:os"),l=i("./src/agent/auth/login-flow.ts"),m=i("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"),f=i("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),d=i("@connectrpc/connect"),p=i("./src/agent/transport.ts");var h=i("node:child_process"),g=i("node:path");function _(t){try{const r=new URL(t);return"http:"===r.protocol||"https:"===r.protocol}catch{return!1}}var J=i("./src/agent/auth/stored-credentials.ts");const w=7776e6;function y(){return new u.Tg}function S(){let t;try{t=(0,c.hostname)()}catch{t="unknown-host"}return`Cursor SDK login (${t})`}var q=i("./src/agent/filesystem/compose.ts"),B=i("./src/agent/filesystem/errors.ts"),I=i("../context/dist/core.js"),P=i("../proto/dist/generated/agent/v1/delete_exec_pb.js"),b=i("../proto/dist/generated/agent/v1/grep_exec_pb.js"),R=i("../proto/dist/generated/agent/v1/ls_exec_pb.js"),v=i("../proto/dist/generated/agent/v1/read_exec_pb.js"),x=i("../proto/dist/generated/agent/v1/write_exec_pb.js"),k=i("./src/agent/filesystem/executors.ts"),E=i("./src/agent/filesystem/walk.ts");const C=5,T=200;function U(t){const r="/"===t.parent?"/":`${t.parent}/`;if(!t.entryPath.startsWith(r))return;const e=t.entryPath.slice(r.length),n=e.indexOf("/"),s=-1===n?e:e.slice(0,n);return""===s?void 0:s}function A(t){const r=g.posix.basename(t.replace(/\/$/,"")),e=r.lastIndexOf(".");return e>0?r.slice(0,e):r}function $(t,r){return t.startsWith(r)||r.startsWith(t)}function M(t,r){const e=Array.from({length:r.length+1},((t,r)=>r));for(let n=0;nasync function({executors:t,fs:r},e){const n=e.requiredString(["path","target_file","file_path"]),s=e.optionalInteger(["offset"]),i=e.optionalInteger(["limit"]);void 0!==i&&i<1&&e.invalid("limit must be at least 1");const o={type:"read",args:{path:n}},a=(await t.read.execute(N,new v.a2({path:n,offset:0===s?1:s,limit:i}))).result;switch(a.case){case"success":{const{value:t}=a;return(void 0!==s||void 0!==i)&&!t.rangeApplied&&"content"===t.output.case&&t.totalLines>0?{...o,result:K({message:`Offset ${s} is beyond file length (${t.totalLines} lines)`,path:t.path})}:{...o,result:{status:"success",value:{content:"content"===t.output.case?t.output.value:"",totalLines:t.totalLines,fileSize:Number(t.fileSize)}}}}case"error":return{...o,result:K({message:a.value.error,path:a.value.path})};case"fileNotFound":{const t=await async function(t,r){const e=(0,E.eI)(r),n=function(t){const r=g.posix.dirname(t);return"."===r||r===t?"/":r}(e),s=g.posix.basename(e),i=new Set;try{for await(const r of t.list(n,{maxDepth:1,limit:T})){const t=U({entryPath:(0,E.eI)(r.path),parent:n});void 0!==t&&t!==s&&i.add("directory"===r.kind?`${t}/`:t)}}catch{return}const o=function(t){const r=A(t.query);return[...t.names].sort(((t,e)=>{const n=A(t),s=A(e),i=$(r,n)?0:1,o=$(r,s)?0:1;if(i!==o)return i-o;const a=M(r,n)-M(r,s);return 0!==a?a:t.localeCompare(e)}))}({query:s,names:[...i]}).slice(0,C);if(0!==o.length)return`not found: ${e}. nearest: ${o.join(", ")}. do not retry.`}(r,a.value.path);return{...o,result:K({message:t??"File not found",path:a.value.path})}}case"permissionDenied":return{...o,result:K({message:"Permission denied",path:a.value.path})};case"invalidFile":return{...o,result:K({message:`${a.value.reason}: ${n}`,path:a.value.path})};case"rejected":return{...o,result:K({message:a.value.reason,path:a.value.path})};case void 0:return{...o,result:K({message:"read failed",path:n})};default:return a}}({executors:n,fs:t},new z("Read",r))},Write:{name:"Write",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e=r.requiredString(["path","file_path","target_file"]),n=r.requiredString(["contents","fileText","file_text","content"],{allowEmpty:!0}),s={type:"edit",args:{path:e}},i=(await t.write.execute(N,new x.hY({path:e,fileText:n}))).result;switch(i.case){case"success":return{...s,result:{status:"success",value:{}}};case"error":case"permissionDenied":return{...s,result:K({message:i.value.error,path:i.value.path})};case"rejected":return{...s,result:K({message:i.value.reason,path:i.value.path})};case"noSpace":return{...s,result:K({message:"No space left",path:i.value.path})};case void 0:return{...s,result:K({message:"write failed",path:e})};default:return i}}(n,new z("Write",t))},StrReplace:{name:"StrReplace",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},execute:r=>async function({fs:t,workspace:r},e){const n=(0,k.mv)({workspace:r,path:e.requiredString(["path","file_path","target_file"])}),s=e.requiredString(["old_string","oldText"],{allowEmpty:!0}),i=e.requiredString(["new_string","newText"],{allowEmpty:!0}),o=e.optionalBoolean(["replace_all","replaceAll"]),a={type:"edit",args:{path:n}};try{await(0,O.i$)(t,{path:n,oldText:s,newText:i,replaceAll:o})}catch(t){if(t instanceof B.ER)return{...a,result:K({message:t.message,path:t.path})};throw t}return{...a,result:{status:"success",value:{}}}}({fs:t,workspace:e},new z("StrReplace",r))},LS:{name:"LS",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function({executors:t,workspace:r},e){const n=e.optionalString(["target_directory","path"])??r,s=e.optionalStringArray(["ignore_globs","ignore"])??[],i=await t.ls.execute(N,new R.xe({path:n,ignore:s})),o={type:"ls",args:s.length>0?{path:n,ignore:s}:{path:n}},a=i.result;if("success"===a.case&&void 0!==a.value.directoryTreeRoot)return{...o,result:{status:"success",value:{directoryTreeRoot:G(a.value.directoryTreeRoot)}}};const u="error"===a.case?a.value.error:"rejected"===a.case?a.value.reason:"list failed";return{...o,result:K({message:u})}}({executors:n,workspace:e},new z("LS",t))},Grep:{name:"Grep",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e={pattern:r.requiredString(["pattern"],{allowEmpty:!0}),path:r.optionalString(["path"]),glob:r.optionalString(["glob"]),outputMode:r.optionalString(["output_mode","outputMode"]),contextBefore:r.optionalInteger(["-B","contextBefore"]),contextAfter:r.optionalInteger(["-A","contextAfter"]),context:r.optionalInteger(["-C","context"]),caseInsensitive:r.optionalBoolean(["-i","caseInsensitive"]),type:r.optionalString(["type"]),headLimit:r.optionalInteger(["head_limit","headLimit"]),offset:r.optionalInteger(["offset"]),multiline:r.optionalBoolean(["multiline"])},n=await t.grep.execute(N,new b.Qj(e));return{type:"grep",args:(s=e,Object.fromEntries(Object.entries(s).filter((([,t])=>void 0!==t)))),result:L(n)};var s}(n,new z("Grep",t))},Glob:{name:"Glob",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function({executors:t,workspace:r},e){const n=e.requiredString(["glob_pattern","globPattern"]),s=e.optionalString(["target_directory","targetDirectory","path"]),i={type:"glob",args:void 0===s?{globPattern:n}:{globPattern:n,targetDirectory:s}},o=function(t){let r=t.replace(/\\/g,"/");return r.startsWith("/")&&(r=r.slice(1)),r.endsWith("/")&&(r=r.slice(0,-1)),r.startsWith("**/")?r:`**/${r}`}(n);if("**/"===o)return{...i,result:K({message:'glob_pattern is empty. Pass "*" to match every file.'})};const a=(await t.grep.execute(N,new b.Qj({pattern:"",path:s,glob:o,outputMode:"files_with_matches"}))).result;if("success"!==a.case)return{...i,result:K({message:"error"===a.case?a.value.error:"glob failed"})};const u=Object.values(a.value.workspaceResults)[0]?.result;if("files"!==u?.case)return{...i,result:K({message:"glob failed"})};const c=void 0===s?void 0:(0,k.mv)({workspace:r,path:s});return{...i,result:{status:"success",value:{files:u.value.files.map((t=>void 0===c?t:g.posix.relative(c,t)||g.posix.basename(t))),totalFiles:u.value.totalFiles,clientTruncated:u.value.clientTruncated,ripgrepTruncated:u.value.ripgrepTruncated}}}}({executors:n,workspace:e},new z("Glob",t))},Delete:{name:"Delete",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e=r.requiredString(["path","target_file"]),n={type:"delete",args:{path:e}},s=(await t.delete.execute(N,new P.dn({path:e}))).result;switch(s.case){case"success":return{...n,result:{status:"success",value:{fileSize:Number(s.value.fileSize)}}};case"fileNotFound":return{...n,result:K({message:"File not found",path:s.value.path})};case"notFile":return{...n,result:K({message:`Path is a ${s.value.actualType}, not a file`,path:s.value.path})};case"permissionDenied":return{...n,result:K({message:s.value.clientVisibleError,path:s.value.path})};case"fileBusy":return{...n,result:K({message:"File is busy",path:s.value.path})};case"rejected":return{...n,result:K({message:s.value.reason,path:s.value.path})};case"error":return{...n,result:K({message:s.value.error,path:s.value.path})};case void 0:return{...n,result:K({message:"delete failed",path:e})};default:return s}}(n,new z("Delete",t))}}}const N=(0,I.q6)();function G(t){return{absPath:t.absPath,childrenDirs:t.childrenDirs.map(G),childrenFiles:t.childrenFiles.map((t=>({name:t.name}))),childrenWereProcessed:t.childrenWereProcessed,fullSubtreeExtensionCounts:{...t.fullSubtreeExtensionCounts},numFiles:t.numFiles}}function L(t){const r=t.result;if("success"!==r.case)return K({message:"error"===r.case?r.value.error:"grep failed"});const e={};for(const[t,n]of Object.entries(r.value.workspaceResults)){const r=F(n);void 0!==r&&(e[t]=r)}return{status:"success",value:{workspaceResults:e}}}function F(t){const r=t.result;switch(r.case){case"content":return{type:"content",output:{matches:r.value.matches.flatMap((t=>function(t){const r=t.matches,e=[];return r.forEach(((n,s)=>{if(n.isContextLine)return;const i=j({rows:r,from:s,step:-1}),o=j({rows:r,from:s,step:1});e.push({file:t.file,lineNumber:n.lineNumber,line:n.content,...i.length>0?{beforeContext:i}:{},...o.length>0?{afterContext:o}:{}})})),e}(t))),totalMatches:r.value.totalMatchedLines}};case"files":return{type:"files",output:{files:r.value.files,count:r.value.totalFiles}};case"count":return{type:"count",output:{counts:r.value.counts.map((t=>({file:t.file,count:t.count}))),total:r.value.totalMatches}};case void 0:return;default:return r}}function K(t){return{status:"error",error:t}}class z{constructor(t,r){this.toolName=t,this.input=r}invalid(t){throw new a.j1(`Invalid ${this.toolName} input: ${t}`,{isRetryable:!1})}requiredString(t,r){const e=this.optionalString(t);return void 0===e||""===e&&!0!==r?.allowEmpty?this.invalid(`${t[0]} is required`):e}optionalString(t){return this.read(t,"a string",(t=>"string"==typeof t?t:void 0))}optionalInteger(t){return this.read(t,"an integer",(t=>"number"==typeof t&&Number.isInteger(t)?t:void 0))}optionalBoolean(t){return this.read(t,"a boolean",(t=>"boolean"==typeof t?t:void 0))}optionalStringArray(t){return this.read(t,"an array of strings",(t=>Array.isArray(t)&&t.every((t=>"string"==typeof t))?t.map(String):void 0))}read(t,r,e){for(const n of t){const t=this.input[n];if(null==t)continue;const s=e(t);return void 0===s?this.invalid(`${n} must be ${r}`):s}}}function j(t){const r=[];let e=(t.rows[t.from]?.lineNumber??0)+t.step;for(let n=t.from+t.step;n>=0&&n{(0,h.execFile)(t,r,{cwd:e,timeout:1e4},((r,e)=>{if(r){const e=function(t){if("code"in t)return"string"==typeof t.code?t.code:void 0}(r);return"ENOENT"!==e&&"127"!==e||at.set(t,Date.now()+3e4),void n(null)}n({stdout:e})}))}))}function lt(t,r){try{const r=new URL(t),e=r.host.toLowerCase();if(ut.has(e))return r.pathname.startsWith("/github/")?"github":"origin";if(e.includes("github"))return"github"}catch{}return r}async function mt(t){if(function(t){const r=at.get(t);return void 0!==r&&Date.now()async function(t){const r=await async function(t){const r=await ct("git",["rev-parse","--abbrev-ref","HEAD"],t),e=r?.stdout.trim();return e&&"HEAD"!==e?e:null}(t);return r?(await Promise.all([ft({cwd:t,branch:r}),dt({cwd:t,branch:r})])).filter((t=>null!==t)):[]}(t)))),e=new Map;for(const t of r.flat())e.has(t.url)||e.set(t.url,t);return[...e.values()]}catch{return[]}}(t.cwds);for(const e of r){const r=`${t.agentId}\0${e.url}`;ht.has(r)||(ht.add(r),(0,rt.id)(t.apiKey,{agent_id:t.agentId,run_id:t.runId,request_id:t.requestId,runtime:t.runtime,pr_url:e.url,pr_number:e.number,branch:e.branch,code_forge:e.codeForge,creation_path:"shell_cli",pr_created_at:e.createdAt}))}}catch{}}class _t extends a.j1{constructor(t,r){super(r??`Run operation "${t}" is not supported`,{operation:`run.${t}`,isRetryable:!1}),this.name="UnsupportedRunOperationError"}}var Jt=i("./src/agent/utils/logger.ts");class wt{constructor(t){this.eventStore=t.eventStore,this.eventStreamStore=t.eventStreamStore??(t.eventNotifier?new yt(t.eventStore,t.eventNotifier):void 0),this.eventNotifier=t.eventNotifier,this.loadRunStatus=t.loadRunStatus,this.defaultPollIntervalMs=t.defaultPollIntervalMs??250}async*streamRunEvents(t,r={}){const e=r.mode??"replay";r.limit,It(r.signal),"replay"!==e&&this.eventStreamStore?yield*this.streamAttachedRunEvents(t,r):yield*this.streamPolledRunEvents(t,r)}async*streamAttachedRunEvents(t,r){const e=r.mode??"replay-and-tail",n=r.limit,s=r.signal;let i=r.afterOffset;"tail"!==e||i||(i=await this.drainExistingEvents(t,n,s));try{for await(const r of this.eventStreamStore.attachRunEvents({runId:t,afterOffset:i,signal:s})){It(s),i=r.offset;const t=this.decodeRunEventRecord(r);if(!t)continue;const e=(0,W.xc)(t);if(e&&(yield e),(0,W.J5)(t))return}}catch(t){if(s?.aborted)throw Pt(s);if(!this.eventNotifier)throw t}await this.isTerminalAndDrained(t,i,n)||(yield*this.streamPolledRunEvents(t,{...r,afterOffset:i}))}async*streamPolledRunEvents(t,r){const e=r.mode??"replay",n=r.limit,s=r.pollIntervalMs??this.defaultPollIntervalMs,i=r.signal;It(i);let o,a,u=r.afterOffset;"tail"!==e||u||(u=await this.drainExistingEvents(t,n,i));try{for("replay"!==e&&this.eventNotifier&&(o=Bt(i),a=function(t){if(!t)return;t.ready?.catch((()=>{}));const r=t[Symbol.asyncIterator](),e=()=>r.next().then((t=>t.done?"closed":"wakeup"),(()=>"error"));let n=e();return{async wait(){const t=n;return n=t.then((()=>e())),t},async close(){o?.abort(),await n.catch((()=>{})),await(r.return?.().catch((()=>{})))}}}(this.eventNotifier.subscribeRunEvents({runId:t,signal:o.signal})));;){It(i);const r=await this.listAvailableEvents({runId:t,afterOffset:u,pageLimit:n,signal:i});u=r.afterOffset;for(const t of r.events)yield t;if(r.sawTerminalEvent)return;if("replay"===e)return;if(await this.isTerminalAndDrained(t,u,n))return;"wakeup"!==await qt({wakeups:a,pollIntervalMs:s,signal:i})&&(await(a?.close()),a=void 0)}}finally{await(a?.close()),o?.abort()}}async drainExistingEvents(t,r,e){let n;for(;;){It(e);const s=await this.eventStore.listRunEvents({runId:t,afterOffset:n,limit:r});for(const t of s.events)n=t.offset;if(!s.nextOffset)return n}}async listAvailableEvents(t){const r=[];let e=!1,n=t.afterOffset;for(;;){It(t.signal);const s=await this.eventStore.listRunEvents({runId:t.runId,afterOffset:n,limit:t.pageLimit});for(const t of s.events){n=t.offset;const s=this.decodeRunEventRecord(t);if(!s)continue;const i=(0,W.xc)(s);i&&r.push(i),e||=(0,W.J5)(s)}if(!s.nextOffset)return{afterOffset:n,events:r,sawTerminalEvent:e}}}decodeRunEventRecord(t){try{return(0,W.LN)(t.payload)}catch(r){return void Jt.v.log(`Skipping unsupported local run event for run ${t.runId} at offset ${t.offset}: ${r instanceof Error?r.message:String(r)}`)}}async isTerminalAndDrained(t,r,e){if((await this.eventStore.listRunEvents({runId:t,afterOffset:r,limit:e})).events.length>0)return!1;const n=await this.loadRunStatus(t);return!(!n||!(0,Y.Qb)(n))}}class yt{constructor(t,r){this.eventStore=t,this.eventNotifier=r}appendRunEvent(t){return this.eventStore.appendRunEvent(t)}listRunEvents(t){return this.eventStore.listRunEvents(t)}async*attachRunEvents(t){const r=Bt(t.signal),e=this.eventNotifier.subscribeRunEvents({runId:t.runId,signal:r.signal}),n=e[Symbol.asyncIterator]();let s,i=t.afterOffset??void 0;try{for(;;){It(t.signal),i=yield*St(this.eventStore,t.runId,i,t.signal);const r=(s??=n.next(),s);await e.ready,i=yield*St(this.eventStore,t.runId,i,t.signal);const o=await r;if(s=void 0,o.done)return}}finally{r.abort(),await(s?.catch((()=>{}))),await(n.return?.().catch((()=>{})))}}}async function*St(t,r,e,n){let s=e;for(;;){It(n);const e=await t.listRunEvents({runId:r,afterOffset:s});for(const t of e.events)s=t.offset,yield t;if(!e.nextOffset)return s}}async function qt(t){It(t.signal);const r=Bt(t.signal),e=[(n=t.pollIntervalMs,s=r.signal,n<=0?Promise.resolve():new Promise(((t,r)=>{const e=setTimeout((function(){o(),t()}),n),i=()=>{clearTimeout(e),o(),r(Pt(s))};function o(){s?.removeEventListener("abort",i)}s?.addEventListener("abort",i,{once:!0})}))).then((()=>"poll"))];var n,s;t.wakeups&&e.push(t.wakeups.wait());try{const r=await Promise.race(e);return It(t.signal),"poll"===r?"wakeup":r}finally{r.abort()}}function Bt(t){const r=new AbortController;if(!t)return r;if(t.aborted)return r.abort(t.reason),r;const e=()=>{r.abort(t.reason)};return t.addEventListener("abort",e,{once:!0}),r.signal.addEventListener("abort",(()=>{t.removeEventListener("abort",e)}),{once:!0}),r}function It(t){if(t?.aborted)throw Pt(t)}function Pt(t){const r=t?.reason;return r instanceof Error?r:new Error("Run event stream aborted")}var bt=i("./src/agent/run-interaction-accumulator.ts"),Rt=i("./src/agent/store/local-agent-store.ts");const vt="Default local agent storage requires the built-in node:sqlite module (Node >= 22.13, or another runtime that implements node:sqlite). Upgrade Node, or configure a custom store: Cursor.configure({ local: { store: new JsonlLocalAgentStore(rootDir) } }) or pass local.store / store on Agent.create and Agent.resume.";function xt(t){if("NoSqliteDriverError"===function(t){if("object"==typeof t&&null!==t&&"name"in t)return"string"==typeof t.name?t.name:void 0}(t))return!0;if("ERR_UNKNOWN_BUILTIN_MODULE"===function(t){if("object"==typeof t&&null!==t&&"code"in t)return"string"==typeof t.code?t.code:void 0}(t))return!0;const r=function(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:void 0}(t)?.toLowerCase();return r?.includes("node:sqlite")??!1}function kt(t){return new a.j1(vt,{isRetryable:!1,cause:t})}var Et=i("./src/agent/store/sdk-local-defaults.ts"),Ct=i("./src/agent/store/sdk-state-root.ts"),Tt=i("./src/agent/subagent-conversion.ts"),Ut=i("./src/agent/team-id.ts"),At=i("./src/agent/tool-call-utils.ts"),$t=i("./src/agent/tools-option.ts"),Mt=i("./src/agent/filesystem/local-fs.ts");const Ot={read_tool_call:"fs",edit_tool_call:"fs",delete_tool_call:"fs",ls_tool_call:"fs",grep_tool_call:"fs",glob_tool_call:"fs",task_tool_call:"fs",await_tool_call:"fs",generate_image_tool_call:"fs",update_todos_tool_call:"file-free",read_todos_tool_call:"file-free",ask_question_tool_call:"file-free",create_plan_tool_call:"file-free",switch_mode_tool_call:"file-free",web_search_tool_call:"file-free",web_fetch_tool_call:"file-free",fetch_tool_call:"file-free",mcp_tool_call:"file-free",get_mcp_tools_tool_call:"file-free",list_mcp_resources_tool_call:"file-free",read_mcp_resource_tool_call:"file-free",mcp_auth_tool_call:"file-free"},Dt={shell_tool_call:"it runs host processes",write_shell_stdin_tool_call:"it drives host shells",read_lints_tool_call:"it reads host diagnostics",sem_search_tool_call:"semantic search is not available to local agents",apply_agent_diff_tool_call:"it applies a subagent's changes to the host working tree",record_screen_tool_call:"it records the host display",computer_use_tool_call:"it drives the host display and input devices"};let Nt;var Gt=i("./src/agent/usage-types.ts");class Lt{constructor(){this.queue=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const r=this.waiters.shift();if(!r)return this.queue.length>=8192?(this.overflow=new a.LF("Live run event buffer overflow; consumer is too slow",{code:"stream_buffer_overflow",errorName:"CursorSdkError"}),void(this.closed=!0)):void this.queue.push(t);r({value:t,done:!1})}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const t=this.waiters.shift();t?.({value:void 0,done:!0})}}async*stream(){for(;;){const t=this.queue.shift();if(t){yield t;continue}if(this.overflow)throw this.overflow;if(this.closed)return;const r=await new Promise((t=>{this.waiters.push(t)}));if(r.done)return;yield r.value}}}class Ft{constructor(t,r,e,n,s,i,o={}){this.id=t,this.agentId=r,this.controller=e,this.eventBuffer=n,this.store=s,this.emitStatus=i,this.git=void 0,this.terminalMetadataHydrated=!1,this.listeners=new Set,this.requestId=o.requestId??void 0,this.model=o.model,this.currentStatus=o.initialStatus??"running",this.createdAt=o.createdAt?.getTime(),this._result=void 0,this._error=void 0,this._durationMs=void 0,this.liveTerminal=o.liveTerminal??{},this.cancellationState=o.cancellationState??{cancelled:!1},this.waitForTerminalStatus=o.waitForTerminalStatus,this.conversationPromise=o.conversation??Promise.resolve([]),this.waitForTerminalStatus?this.waitForTerminalStatus.then((async t=>{this.setStatus(t),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).catch((async t=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||(this._error=(0,a.D7)(t),this.setStatus("error")),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).finally((()=>this.eventBuffer.close())):o.trackController??1?this.controller.done.then((async()=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||this.setStatus("finished"),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).catch((async t=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||(this._error=(0,a.D7)(t),this.setStatus("error")),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).finally((()=>this.eventBuffer.close())):"running"!==this.currentStatus&&this.eventBuffer.close()}supports(t){return"stream"===t||"wait"===t||"conversation"===t||"cancel"===t}unsupportedReason(t){if(!this.supports(t))return`Unknown run operation "${t}"`}stream(){try{return this.eventBuffer.stream()}catch(t){throw(0,a.Nt)(t,{operation:"run.stream"})}}async conversation(){try{return await this.conversationPromise}catch(t){throw(0,a.Nt)(t,{operation:"run.conversation"})}}async wait(){try{const t=t=>(this.captureLiveUsage(),{id:this.id,...void 0!==this.requestId?{requestId:this.requestId}:{},status:t,...void 0!==this._result?{result:this._result}:{},..."error"===t&&void 0!==this._error?{error:this._error}:{},...void 0!==this.model?{model:this.model}:{},...void 0!==this._durationMs?{durationMs:this._durationMs}:{},...void 0!==this._usage?{usage:this._usage}:{}});if("running"!==this.currentStatus)return await this.controller.done.catch((()=>{})),await this.refreshTerminalMetadataFromStore(),t(this.currentStatus);if(this.waitForTerminalStatus){const r=await this.waitForTerminalStatus;return await this.refreshTerminalMetadataFromStore(),t(r)}try{return await this.controller.done,await this.refreshTerminalMetadataFromStore(),void 0===this._result&&await this.refreshTerminalMetadataFromStore(),t("running"!==this.currentStatus?this.currentStatus:"finished")}catch(r){return this.cancellationState.cancelled?(await this.refreshTerminalMetadataFromStore(),this._error=void 0,t("cancelled")):(this._error??=(0,a.D7)(r),await this.refreshTerminalMetadataFromStore(),t("error"))}}catch(t){throw(0,a.Nt)(t,{operation:"run.wait"})}}async steer(t){try{return await(this.controller.steer?.(t))??"revert_to_followup"}catch(t){throw(0,a.Nt)(t,{operation:"run.steer"})}}async cancel(){try{if("running"!==this.currentStatus)return;this.cancellationState.cancelled=!0,this.setStatus("cancelled"),await this.emitStatus("CANCELLED"),this.controller.abort(),await this.store.cancelRun(this.agentId,this.id),await this.refreshTerminalMetadataFromStore()}catch(t){throw(0,a.Nt)(t,{operation:"run.cancel"})}}get status(){return this.currentStatus}get result(){return this._result}get error(){return"error"===this.currentStatus?this._error:void 0}get durationMs(){return this._durationMs}get usage(){return this.captureLiveUsage(),this._usage}onDidChangeStatus(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t){this.currentStatus!==t&&(this.currentStatus=t,this.listeners.forEach((r=>{r(t)})))}captureLiveUsage(){void 0===this._usage&&void 0!==this.liveTerminal.usage&&(this._usage=this.liveTerminal.usage)}async refreshTerminalMetadataFromStore(){if(!this.terminalMetadataHydrated)try{const t=await this.store.getRun(this.agentId,this.id),r=t?.result??null;null!=r&&(this._result=r),void 0===this._error&&t?.errorCode&&(this._error=(0,a.vg)(t.errorCode));const e=t?Rr(t):void 0;if(void 0!==e&&(this._durationMs=e),void 0===this._usage){const r=t?.usage??null;null!=r&&(this._usage=r)}const n=t?.status;"FINISHED"===n&&null==r||"FINISHED"!==n&&"ERROR"!==n&&"CANCELLED"!==n&&"EXPIRED"!==n||(this.terminalMetadataHydrated=!0)}catch(t){Jt.v.log(`Failed to hydrate terminal metadata for run ${this.id}: ${t instanceof Error?t.message:String(t)}`)}}}class Kt{constructor(t,r,e,n,s,i,o,a,u,c,l,m){this.id=t,this.agentId=e,this.currentStatus=n,this.result=o,this.error=a,this.durationMs=u,this.store=l,this.streamFactory=m,this.git=void 0,this.requestId=r??void 0,this.createdAt=s?.getTime(),this.model=i,this.usage=c??void 0}supports(t){return"stream"===t?void 0!==this.streamFactory:"wait"===t?"running"!==this.currentStatus:"conversation"===t?void 0!==this.streamFactory:"cancel"===t&&"running"===this.currentStatus}unsupportedReason(t){if(!this.supports(t))return"stream"===t?"Cannot stream this run because no run event store is configured":"wait"===t?"Cannot wait on a detached running run":"cancel"===t?"Cannot cancel a detached run that is already terminal":"conversation"===t?"Cannot reconstruct this run conversation because no run event store is configured":"Unknown run operation"}stream(){try{if(!this.streamFactory)throw new _t("stream",this.unsupportedReason("stream"));return this.streamFactory()}catch(t){throw(0,a.Nt)(t,{operation:"run.stream"})}}async conversation(){try{if(!this.streamFactory)throw new _t("conversation",this.unsupportedReason("conversation"));return(0,bt.KG)(this.streamFactory())}catch(t){throw(0,a.Nt)(t,{operation:"run.conversation"})}}async wait(){try{if("running"===this.currentStatus)throw new _t("wait",this.unsupportedReason("wait"));return{id:this.id,...void 0!==this.requestId?{requestId:this.requestId}:{},status:this.currentStatus,...void 0!==this.result?{result:this.result}:{},...void 0!==this.error?{error:this.error}:{},...void 0!==this.model?{model:this.model}:{},...void 0!==this.durationMs?{durationMs:this.durationMs}:{},...void 0!==this.usage?{usage:this.usage}:{}}}catch(t){throw(0,a.Nt)(t,{operation:"run.wait"})}}async steer(t){return"revert_to_followup"}async cancel(){try{if("running"!==this.currentStatus)return;await this.store.cancelRun(this.agentId,this.id),this.currentStatus="cancelled"}catch(t){throw(0,a.Nt)(t,{operation:"run.cancel"})}}get status(){return this.currentStatus}onDidChangeStatus(t){return()=>{}}}function zt(t){const r=Ir(t)??process.cwd(),e=Pr(t,r),n=(0,Ut.E)(t.teamId);return{workingDirectory:r,...void 0!==e?{dirs:e}:{},apiKey:t.apiKey,...void 0!==n?{teamId:n}:{},settingSources:t.local?.settingSources,sandboxOptions:t.local?.sandboxOptions,autoReview:t.local?.autoReview,enableAgentRetries:t.local?.enableAgentRetries,...void 0!==t.local?.hostMcpBridgeUrls?{hostMcpBridgeUrls:t.local.hostMcpBridgeUrls}:{},devForceNextSmartModeClassifierBlockToken:process.env.CURSOR_SDK_DEV_FORCE_NEXT_SMART_MODE_CLASSIFIER_BLOCK_TOKEN,mcpServers:t.mcpServers,customSubagents:t.customSubagents??(0,Tt.DB)(t.agents)}}function jt(t,r){const e=r?.resourceProviderOptions??t?.resourceProviderOptions,n=r?.reportedWorkspacePath??t?.reportedWorkspacePath;return void 0===e&&void 0===n?{}:{sessionResources:{...void 0!==e?{resourceProviderOptions:e}:{},...void 0!==n?{reportedWorkspacePath:n}:{}}}}function Ht(t,r){const e=r?.reportedWorkspacePath??t?.reportedWorkspacePath;return void 0===e?{}:{fileSystemWorkspace:(0,Mt.xh)(e)}}function Wt(t){const r=void 0===t.fileSystem?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools}:function(t){if(void 0===t.allowedTools){const r=new Set(t.disallowedTools??[]);return{allowedTools:Object.keys(Ot).filter((t=>!r.has(t))),disallowedTools:t.disallowedTools}}const r=t.allowedTools.filter((t=>!(void 0!==Ot[t])));if(r.length>0){const t=r.map((t=>{const r=Dt[t]??"it is not backed by local.fs";return`${function(t){if(void 0===Nt){Nt=new Map;for(const t of Z.Dm_.fields.list())"tool"===t.oneof?.localName&&Nt.set(t.name,t.localName.replace(/ToolCall$/,""))}return Nt.get(t)??t}(t)} (${r})`}));throw new a.j1(`\`tools\` names tools a local.fs agent cannot run: ${t.join(", ")}. Remove them from \`tools\` or omit local.fs.`,{isRetryable:!1})}return{allowedTools:[...t.allowedTools],disallowedTools:t.disallowedTools}}({allowedTools:t.allowedTools,disallowedTools:t.disallowedTools});return{...void 0!==r.allowedTools?{allowedTools:r.allowedTools}:{},...void 0!==r.disallowedTools?{disallowedTools:r.disallowedTools}:{}}}const Qt=new Map,Vt="CURSOR_SDK_LOCAL_MODEL_CATALOG_JSON";function Xt(t){return Array.isArray(t)?t.map(Xt):(0,At.u)(t)?Object.fromEntries(Object.keys(t).sort().map((r=>[r,Xt(t[r])]))):t}function Yt(t){if(!Array.isArray(t))return;const r=[];for(const e of t){if(!(0,At.u)(e)||"string"!=typeof e.displayName||!Array.isArray(e.params))continue;const t=[];for(const r of e.params)(0,At.u)(r)&&"string"==typeof r.id&&"string"==typeof r.value&&t.push({id:r.id,value:r.value});r.push({params:t,displayName:e.displayName,..."string"==typeof e.description?{description:e.description}:{},...!0===e.isDefault?{isDefault:!0}:{},...!0===e.isMaxMode?{isMaxMode:!0}:{}})}return r.length>0?r:void 0}async function Zt(t){(0,ot.configureVendoredTreeSitterWorkspaceDir)(t.workingDirectory);for(const r of t.dirs??[])(0,ot.configureVendoredTreeSitterWorkspaceDir)(r);const r=function(t){return(0,Q.createHash)("sha256").update((r={workingDirectory:t.workingDirectory,dirs:t.dirs,apiKeyHash:void 0===t.apiKey?void 0:(0,Q.createHash)("sha256").update(t.apiKey).digest("hex"),teamId:(0,Ut.E)(t.teamId),settingSources:t.settingSources,mcpServers:t.mcpServers,sandboxOptions:t.sandboxOptions,autoReview:t.autoReview,devForceNextSmartModeClassifierBlockTokenHash:void 0===t.devForceNextSmartModeClassifierBlockToken?void 0:(0,Q.createHash)("sha256").update(t.devForceNextSmartModeClassifierBlockToken).digest("hex"),customSubagents:t.customSubagents,enableAgentRetries:t.enableAgentRetries,hostMcpBridgeUrls:t.hostMcpBridgeUrls},JSON.stringify(Xt(r)))).digest("hex");var r}(t);let e=Qt.get(r),n=!1;if(!e){n=!0;const s={refs:0,promise:Promise.all([i.e(82),i.e(977)]).then(i.bind(i,"./src/agent/local-executor.ts")).then((({createLocalExecutor:r})=>r(t))).catch((t=>{throw Qt.get(r)===s&&Qt.delete(r),t}))};e=s,Qt.set(r,e)}e.refs+=1;let s=!1;try{return{handle:await e.promise,cacheMiss:n,release:async()=>{s||(s=!0,await async function(t,r){if(r.refs-=1,!(r.refs>0||Qt.get(t)!==r)){Qt.delete(t);try{const t=await r.promise;await(t.dispose?.())}catch{}}}(r,e))}}}catch(t){throw e.refs-=1,e.refs<=0&&Qt.get(r)===e&&Qt.delete(r),t}}function tr(t){if("string"!=typeof t)return t.images?.map((t=>{if("url"in t)throw new a.j1("URL images are only supported for cloud SDK agents",{isRetryable:!1});return{type:"base64",data:t.data}}))}const rr="customSubagents",er="initialMode",nr="blobEncryptionKey";function sr(t){const r=t?.[nr];if((0,V.TU)(r))return r;const e=(0,V.sh)("").blobEncryptionKey;if(void 0===e)throw new Error("Failed to generate a blob encryption key");return e}class ir{constructor(t,r,e,n,s){this.agentId=t,this.platform=r,this.options=e,this.firstSendCompletedAfterResume=!1,this._pendingPrAttributions=new Set,this.checkpointPersistChain=Promise.resolve(),this.pendingInitialRunId=n,this._model=e.model,this.catalogResolvedModel=s?.catalogResolvedModel,this.resumedAgent=s?.resumedAgent??!1}get model(){return this._model}async send(t,r={}){let e=!1;try{return await this.sendImpl({text:"string"==typeof t?t:t.text,images:tr(t)},r,(()=>{e=!0}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.send"});throw e||(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.send",runtime:"local",error:r}),r}}async resume(__t3o={}){try{const t=await this.platform.store.getAgent(this.agentId);if(null===t)throw new a.XB(`Agent ${this.agentId} not found`,{isRetryable:!1});if(null===t.latestCheckpointRef)throw new a.j1(`Agent ${this.agentId} has no saved conversation to resume yet.`,{isRetryable:!1});return await this.sendImpl({text:"",resume:!0},__t3o,(()=>{}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.resume"});throw(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.resume",runtime:"local",error:r}),r}}async summarize(){try{const t=await this.platform.store.getAgent(this.agentId);if(null===t)throw new a.XB(`Agent ${this.agentId} not found`,{isRetryable:!1});if(null===t.latestCheckpointRef)throw new a.j1(`Agent ${this.agentId} has no saved conversation to summarize yet.`,{isRetryable:!1});return await this.sendImpl({summarize:!0},{},(()=>{}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.summarize"});throw(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.summarize",runtime:"local",error:r}),r}}async sendImpl(t,r,e){if(void 0!==r.cloud)throw new a.j1("Cloud send options are only supported for cloud SDK agents. Create the agent with cloud options or use local.* send options.",{isRetryable:!1});const n=performance.now(),s=!0===t.summarize,i=r.model??this._model;if(void 0===i)throw new a.j1('Local SDK agents require an explicit `model`. Pass `model: { id: "" }` to Agent.create() or to send(), or run this agent in cloud mode.',{isRetryable:!1});let o;try{o=await this.platform.resolveLocalModelSelection(i,this.options.apiKey,this.options.teamId),this.catalogResolvedModel=it({requested:i,resolved:o})}catch(t){const e=function(t){const r=t.resolved;if(void 0!==r&&r.ids.includes(t.requested.id)&&function(t,r){const e=t.params??[],n=r.params??[];return e.length===n.length&&e.every((t=>n.some((r=>r.id.trim()===t.id.trim()&&r.value.trim()===t.value.trim()))))}(r.selection,t.requested))return r.selection}({requested:i,resolved:this.catalogResolvedModel});if(void 0!==e)o=e;else{if(void 0!==r.model||t instanceof a.j1)throw t;if((i.params?.length??0)>0&&!0!==i.maxMode)throw new a.j1(`The model catalog is unavailable, so ${i.id} could not be checked for max mode. Try again.`,{isRetryable:!0,cause:t});o=i}}const u=this.resumedAgent&&!this.firstSendCompletedAfterResume,c=null===this.pendingInitialRunId,l=!c||u,m=r.mode??(l?this.options.mode:void 0),f=r.local?.fs??this.options.local?.fs;(0,Mt.I2)({fs:f,subagentInherit:r.local?.subagentInherit??this.options.local?.subagentInherit,resourceProviderOptions:r.local?.resourceProviderOptions??this.options.local?.resourceProviderOptions,reportedWorkspacePath:r.local?.reportedWorkspacePath??this.options.local?.reportedWorkspacePath});const d=Wt({fileSystem:f,allowedTools:this.options.allowedProtoTools,disallowedTools:this.options.disallowedProtoTools}),p=(0,tt.C)(),h=await this.getRunForSend(r,o,p),g=r.mcpServers,_=g??this.options.mcpServers,J=(0,et.o)(this.options.name),w=s?void 0:(0,nt.E)(t.text);s||(0,rt.Zn)(this.options.apiKey,{agent_id:this.agentId,run_id:h.runId,...void 0!==J?{agent_name:J}:{},request_id:p,runtime:"local",model:o.id,...o.params&&o.params.length>0?{model_params:JSON.stringify(o.params)}:{},prompt_length:t.text.length,...void 0!==w?{prompt_hash:w}:{},has_images:(t.images?.length??0)>0,is_resume:c,mcp_server_count:Object.keys(_??{}).length}),e();const y={executor_acquire_ms:0,load_latest_ms:0,get_blob_store_ms:0,pre_send_ms:0,time_to_first_message_ms:void 0,cold_executor:!1,turn_count:0};let S=!1;const q=t=>{if(S)return;S=!0;const r={agent_id:this.agentId,run_id:h.runId,request_id:p,runtime:"local",is_resume:this.resumedAgent,is_first_send_after_resume:u,cold_executor:y.cold_executor,executor_acquire_ms:y.executor_acquire_ms,load_latest_ms:y.load_latest_ms,get_blob_store_ms:y.get_blob_store_ms,pre_send_ms:y.pre_send_ms,terminated_reason:t,turn_count:y.turn_count};void 0!==y.time_to_first_message_ms&&(r.time_to_first_message_ms=y.time_to_first_message_ms),(0,rt.pL)(this.options.apiKey,r),u&&(this.firstSendCompletedAfterResume=!0)};let B=!1;const I=(t,r)=>{s||B||(B=!0,(0,rt.G5)(this.options.apiKey,{agent_id:this.agentId,run_id:h.runId,...void 0!==J?{agent_name:J}:{},request_id:p,runtime:"local",end_reason:t,error_code:r,...void 0!==w?{prompt_hash:w}:{}}),q(t))};await this.platform.store.markRunStarting(this.agentId,h.runId,{requestId:p});const P=new Lt,b=new bt.e4({onDelta:r.onDelta,onStep:r.onStep}),R={};let v;const x=async(t,r)=>{!1!==r?.emitLive&&P.push(t);try{await this.platform.appendRunMessage(t)}catch(r){Jt.v.log(`Failed to persist stream event ${t.type} for run ${h.runId}: ${r instanceof Error?r.message:String(r)}`)}},k=async(t,r)=>{const e={type:"status",agent_id:this.agentId,run_id:h.runId,status:t,...void 0!==r?{message:r.message}:{}};await x(e)};let E;await(async()=>{const t={type:"request",agent_id:this.agentId,run_id:h.runId,request_id:p};await x(t,{emitLive:!1})})(),await k("RUNNING");let C,T=()=>{};try{const e=performance.now(),i=await this.platform.checkpointStore.loadLatest(this.agentId),u=i instanceof Z.Y9z?i:new Z.Y9z({});y.load_latest_ms=performance.now()-e;const c=performance.now(),l=await this.platform.checkpointStore.getBlobStore(this.agentId);if("object"!=typeof(U=l)||null===U||!("getBlob"in U)||"function"!=typeof U.getBlob||!("setBlob"in U)||"function"!=typeof U.setBlob)throw new a.j1("Local checkpoint store did not return a blob store",{isRetryable:!1});const _=l;T=(0,X.B_)(_,(t=>{void 0===E&&(E=t,Jt.v.log(t),x({type:"status",agent_id:this.agentId,run_id:h.runId,status:"RUNNING",message:t}))})),y.get_blob_store_ms=performance.now()-c,y.turn_count=u.turns.length;const J=performance.now(),w=void 0!==this.executorLease,S=await this.getExecutor();y.executor_acquire_ms=performance.now()-J,y.cold_executor=!w&&(this.executorLease?.cacheMiss??!1),y.pre_send_ms=performance.now()-n,C=await S.run(t,{apiKey:this.options.apiKey??"",model:o,sessionId:this.agentId,requestId:p,initialState:u,blobStore:_,blobEncryptionKey:this.options.blobEncryptionKey,mcpServersOverride:g,customTools:r.local?.customTools??this.options.local?.customTools,...void 0!==(r.local?.onMcpAuthRequest??this.options.local?.onMcpAuthRequest)?{onMcpAuthRequest:r.local?.onMcpAuthRequest??this.options.local?.onMcpAuthRequest}:{},onConnectionStateChange:r.local?.onConnectionStateChange??this.options.local?.onConnectionStateChange,...void 0!==(r.local?.subagentInherit??this.options.local?.subagentInherit)?{subagentInherit:r.local?.subagentInherit??this.options.local?.subagentInherit}:{},...void 0===f?jt(this.options.local,r.local):{fileSystem:f,...Ht(this.options.local,r.local)},...d,...void 0!==this.options.systemPrompt?{systemPrompt:this.options.systemPrompt}:{},...void 0!==m?{mode:m}:{},onMcpAdminToolLimitCounts:t=>{(0,rt.GY)(this.options.apiKey,{run_id:h.runId,runtime:"local",...t})},onCheckpoint:async t=>{const r=async()=>{try{const r=await this.platform.checkpointStore.saveCheckpoint(this.agentId,t);await this.platform.store.patchCheckpoint(this.agentId,h.runId,r)}catch(t){Jt.v.log(`Failed to persist checkpoint for run ${h.runId}: ${t instanceof Error?t.message:String(t)}`)}},e=this.checkpointPersistChain.then((()=>r()),(()=>r()));this.checkpointPersistChain=e,await e}},{sendUpdate:async t=>{void 0===y.time_to_first_message_ms&&(y.time_to_first_message_ms=performance.now()-n),await b.apply(t),s&&"summary"===t.type&&(v=t.summary);const r=function(t,r,e){switch(t.type){case"user-message-appended":return{type:"user",agent_id:r,run_id:e,message:{role:"user",content:[{type:"text",text:t.userMessage.text}]}};case"text-delta":return{type:"assistant",agent_id:r,run_id:e,message:{role:"assistant",content:[{type:"text",text:t.text}]}};case"thinking-delta":return{type:"thinking",agent_id:r,run_id:e,text:t.text};case"thinking-completed":return{type:"thinking",agent_id:r,run_id:e,text:"",thinking_duration_ms:t.thinkingDurationMs};case"tool-call-started":case"partial-tool-call":case"tool-call-completed":{const n=function(t){const r=(0,At.u)(t)?t:{},e="string"==typeof r.name?r.name:"string"==typeof r.type?r.type:"unknown",n=(0,At.D)(r.truncated)?r.truncated:void 0;return{name:e,..."args"in r?{args:r.args}:{},..."result"in r?{result:r.result}:{},...n?{truncated:n}:{}}}(t.toolCall);return{type:"tool_call",agent_id:r,run_id:e,call_id:t.callId,name:n.name,status:Br(t),...void 0!==n.args?{args:n.args}:{},...void 0!==n.result?{result:n.result}:{},...void 0!==n.truncated?{truncated:n.truncated}:{}}}case"summary-started":case"summary-completed":return(0,W.cD)(t,r,e);case"turn-ended":{const n=(0,Gt.qI)(t.usage);if(!n)return;return{type:"usage",agent_id:r,run_id:e,usage:n}}default:return}}(t,this.agentId,h.runId);r&&await x(r)}})}catch(t){T();const r=(0,a.D7)(t);try{await k("ERROR",r);try{await this.platform.store.markRunTerminal(this.agentId,h.runId,{status:"ERROR",errorCode:(0,a.W_)(r)})}catch{}}finally{P.close(),I("error",r.code)}throw t}var U;const A={cancelled:!1},$=async(t,r={})=>{await(async()=>{await b.flushPendingStep(),R.usage=b.usage()})();try{await this.platform.store.markRunTerminal(this.agentId,h.runId,{status:t,...r,...void 0!==R.usage?{usage:R.usage}:{}})}catch(r){"CANCELLED"===t&&(e=r,Jt.v.log(`Failed to persist cancellation for run ${h.runId}: ${e instanceof Error?e.message:String(e)}`))}var e};let M,O;const D=C.done.then((async()=>{if(A.cancelled)return O="cancelled",void await $("CANCELLED");O="finished",await this.checkpointPersistChain,await k("FINISHED",void 0===E?void 0:{message:E});const t=v??b.finalAssistantText();await $("FINISHED",{result:t})}),(async t=>{if(A.cancelled)return O="cancelled",void await $("CANCELLED");const r=function(t,r){if(void 0!==r&&0!==r.trim().length&&(0,X.hI)(t))return{result:r,warning:X.rZ}}(t,v??b.finalAssistantText());if(void 0!==r)return O="finished",await this.checkpointPersistChain,await k("FINISHED",{message:E??r.warning}),void await $("FINISHED",{result:r.result});O="error";const e=(0,a.D7)(t);throw M=e.code,await this.checkpointPersistChain,await k("ERROR",e),await $("ERROR",{errorCode:(0,a.W_)(e)}),t}));D.then((()=>{T()}),(()=>{T()}));const N=async()=>(await b.flushPendingStep(),b.conversation()),G=D.then(N,N);G.catch((()=>{})),D.then((()=>I("cancelled"===O?"abort":"success")),(t=>I("cancelled"===O?"abort":"error","cancelled"===O?void 0:M??(0,a.D7)(t).code)));const L=()=>{if(s||"finished"!==O&&"error"!==O)return;const t=this._attributePrOpened({runId:h.runId,requestId:p});this._pendingPrAttributions.add(t),t.finally((()=>{this._pendingPrAttributions.delete(t)}))};return D.then(L,L),void 0===r.model&&!0!==o.maxMode||(this._model=o),new Ft(h.runId,this.agentId,{abort:()=>{C.abort()},done:D,steer:s?void 0:C.steer?.bind(C)},P,this.platform.store,k,{cancellationState:A,createdAt:h.createdAt,requestId:p,model:o,conversation:G,liveTerminal:R})}async _attributePrOpened(t){const r=function(t){const r=Ir(t)??process.cwd(),e=Pr(t,r);return void 0!==e?[...e]:[r]}(this.options);await gt({apiKey:this.options.apiKey,agentId:this.agentId,runId:t.runId,requestId:t.requestId,runtime:"local",cwds:r.length>0?r:[process.cwd()]})}async awaitPendingPrAttributions(){for(;this._pendingPrAttributions.size>0;)await Promise.allSettled([...this._pendingPrAttributions])}close(){this.awaitPendingPrAttributions().finally((()=>{(0,rt.rd)()})),this.releaseExecutorLease()}async reload(){try{await(this.executorLease?.handle.reload?.())}catch(t){throw(0,a.Nt)(t,{operation:"agent.reload"})}}async[Symbol.asyncDispose](){try{await this.awaitPendingPrAttributions(),await(0,rt.rd)(),await this.releaseExecutorLease()}catch(t){throw(0,a.Nt)(t,{operation:"agent.[Symbol.asyncDispose]"})}}async listArtifacts(){return[]}async downloadArtifact(t){try{throw new a.j1("Artifacts are not implemented for local SDK agents yet",{isRetryable:!1})}catch(t){throw(0,a.Nt)(t,{operation:"agent.downloadArtifact"})}}async getUsage(t){try{if(gr(t?.runId))throw new a.j1(hr,{isRetryable:!1});return await _r(this.agentId,{apiKey:this.options.apiKey,teamId:this.options.teamId,runId:t?.runId})}catch(t){throw(0,a.Nt)(t,{operation:"agent.getUsage"})}}async getExecutor(){if(this.executorLeasePromise||(this.executorLeasePromise=this.platform.acquireLocalExecutor(zt(this.options))),!this.executorLease)try{this.executorLease=await this.executorLeasePromise}catch(t){throw this.executorLeasePromise=void 0,t}return this.executorLease.handle}async releaseExecutorLease(){const t=this.executorLease,r=this.executorLeasePromise;this.executorLease=void 0,this.executorLeasePromise=void 0;let e=t;if(!e&&void 0!==r)try{e=await r}catch{return}e&&await e.release()}async getRunForSend(t,r,e){if(this.pendingInitialRunId){const t=await this.platform.store.getRun(this.agentId,this.pendingInitialRunId);if(this.pendingInitialRunId=null,t&&"QUEUED"===t.status)return t}return t.local?.force&&await this.expireActiveRunForForceSend(),this.platform.store.createFollowUpRun(this.agentId,{requestId:e,model:r,metadata:{[nr]:this.options.blobEncryptionKey}})}async expireActiveRunForForceSend(){const t=await this.platform.store.getAgent(this.agentId),r=t?.activeRunId;if(!r)return;const e=await this.platform.store.getRun(this.agentId,r);if(e&&!(0,Y.Qb)(e.status)){await this.platform.store.markRunTerminal(this.agentId,r,{status:"EXPIRED",errorCode:"force_send"});try{await this.platform.appendRunMessage({type:"status",agent_id:this.agentId,run_id:r,status:"EXPIRED"})}catch(t){Jt.v.log(`Failed to persist force-expire status event for run ${r}: ${t instanceof Error?t.message:String(t)}`)}}}}class or{constructor(t,r,e,n,s){this.store=t,this.checkpointStore=r,this.eventStore=e,this.eventNotifier=n,this.workspaceRef=s,this.localModelListCache=new Map}acquireLocalExecutor(t){return Zt(t)}async prewarmLocalWorkspace(t){const r=await Zt(zt(t));return()=>r.release()}async resolveLocalModelSelection(t,r,e){const n=(0,J.Lc)(r)?.trim();return async function(t,r={}){if(void 0===r.listModels)return t;const e=await r.listModels(),n=function(t,r){return r.find((r=>r.id===t.id||!0===r.aliases?.includes(t.id)))}(t,e);if(void 0===n)throw new a.j1(`Cannot use this model: ${t.id}. Available models: ${e.map((t=>t.id)).join(", ")}. Use Cursor.models.list() to discover valid selections.`,{isRetryable:!1});const s=!0===t.maxMode||function(t,r){const e=r.params??[];if(0===e.length)return!1;const n=(t.variants??[]).filter((t=>e.every((r=>t.params.some((t=>t.id.trim()===r.id.trim()&&t.value.trim()===r.value.trim()))))));return n.length>0&&n.every((t=>!0===t.isMaxMode))}(n,t);return{...t,id:n.id,...s?{maxMode:!0}:{}}}(t,{listModels:void 0!==n&&n.length>0?()=>this.listModelsForLocalValidation(n,e,t.id):void 0})}async listModelsForLocalValidation(t,r,__t3id){const e=function(){const t=process.env[Vt]?.trim();if(!t)return;let r;try{r=JSON.parse(t)}catch(t){throw new a.j1(`${Vt} must be valid JSON`,{isRetryable:!1,cause:t})}const e=Array.isArray(r)?r:(0,At.u)(r)&&Array.isArray(r.items)?r.items:void 0;if(void 0===e)throw new a.j1(`${Vt} must be a model array or an object with an items array`,{isRetryable:!1});const n=[];for(const t of e){if(!(0,At.u)(t)||"string"!=typeof t.id)throw new a.j1(`${Vt} contains an invalid model entry`,{isRetryable:!1});const r=Array.isArray(t.aliases)?t.aliases.filter((t=>"string"==typeof t)):void 0,e=Yt(t.variants);n.push({id:t.id,displayName:"string"==typeof t.displayName?t.displayName:t.id,..."string"==typeof t.description?{description:t.description}:{},...void 0!==r&&r.length>0?{aliases:r}:{},...void 0!==e?{variants:e}:{}})}return n}();if(void 0!==e)return e;const n=JSON.stringify([t,(0,Ut.E)(r)??null]);let s=this.localModelListCache.get(n);const __t3miss=s===void 0;void 0===s&&(s=new st.N_(t,void 0,r).listModels().then((t=>t.items)),this.localModelListCache.set(n,s));let __t3models;try{__t3models=await s}catch(t){throw this.localModelListCache.delete(n),t}if(__t3miss||__t3id===void 0||__t3models.some((__t3m)=>__t3m.id===__t3id||__t3m.aliases?.includes(__t3id)===!0))return __t3models;if(this.localModelListCache.get(n)===s)this.localModelListCache.delete(n);return this.listModelsForLocalValidation(t,r);}async createAgent(t){const r=void 0!==t.model?await this.resolveLocalModelSelection(t.model,t.apiKey,t.teamId):void 0,e=(0,Tt.DB)(t.agents),n=(0,$t.TX)(t.tools),s=(0,$t.db)(t.disallowedTools);dr(t.systemPrompt),(0,Mt.I2)(t.local??{}),void 0!==t.local?.fs&&Wt({fileSystem:t.local.fs,allowedTools:n,disallowedTools:s});const i=sr(void 0),o={...r!==t.model?{...t,model:r}:t,...void 0!==e?{agents:void 0,customSubagents:e}:{},...void 0!==n?{allowedProtoTools:n}:{},...void 0!==s?{disallowedProtoTools:s}:{},blobEncryptionKey:i},a={[nr]:i};void 0!==e&&(a[rr]=e),void 0!==t.mode&&(a[er]=t.mode),void 0!==t.local?.fs&&(a[Mt.rK]=!0);const{agent:u,run:c}=await this.store.createAgent({agentId:t.agentId,workspaceRef:this.workspaceRef,model:r,name:t.name?.trim()||"New Agent",metadata:a});return new ir(u.agentId,this,o,c.runId,{catalogResolvedModel:void 0!==t.model&&void 0!==r&&r!==t.model?it({requested:t.model,resolved:r}):void 0})}async resumeAgent(t,r){const e=await this.store.getAgent(t);if(!e)throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});const n=function(t){return{...t}}(r),s=void 0!==n.model?await this.resolveLocalModelSelection(n.model,n.apiKey,n.teamId):void 0,i=(0,Tt.DB)(n.agents)??function(t){const r=t[rr];if(!Array.isArray(r))return;const e=[];for(const t of r){if("object"!=typeof t||null===t)return;if(!("name"in t&&"string"==typeof t.name&&"description"in t&&"string"==typeof t.description&&"prompt"in t&&"string"==typeof t.prompt&&"model"in t&&"string"==typeof t.model))return;e.push({name:t.name,description:t.description,prompt:t.prompt,model:t.model})}return e.length>0?e:void 0}(e.metadata),o=(0,$t.TX)(n.tools),u=(0,$t.db)(n.disallowedTools);if(dr(n.systemPrompt),(0,Mt.I2)(n.local??{}),!0===e.metadata[Mt.rK]&&void 0===n.local?.fs)throw new a.j1(`Agent ${t} was created with local.fs. Pass local.fs to Agent.resume() so it does not run on the host disk.`,{isRetryable:!1});void 0!==n.local?.fs&&Wt({fileSystem:n.local.fs,allowedTools:o,disallowedTools:u});const c=null!==e.latestCheckpointRef,l=n.mode??(c?void 0:function(t){const r=t[er];return function(t){return"agent"===t||"plan"===t}(r)?r:void 0}(e.metadata)),m={...s!==n.model?{...n,model:s}:n,...void 0!==i?{agents:void 0,customSubagents:i}:{},...void 0!==o?{allowedProtoTools:o}:{},...void 0!==u?{disallowedProtoTools:u}:{},...void 0!==l?{mode:l}:{},blobEncryptionKey:sr(e.metadata)};return new ir(e.agentId,this,m,null,{resumedAgent:!0,catalogResolvedModel:void 0!==n.model&&void 0!==s&&s!==n.model?it({requested:n.model,resolved:s}):void 0})}async listAgents(t){const r=await this.store.listAgents(t);return{items:r.items.map(br),nextCursor:r.nextCursor}}async getAgent(t){const r=await this.store.getAgent(t);if(!r)throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});return br(r)}async archiveAgent(t){await this.store.archiveAgent(t)}async unarchiveAgent(t){await this.store.unarchiveAgent(t)}async deleteAgent(t){const r=await async function(t,r){const e=[];let n;do{const s=await t.listRuns(r,{cursor:n});for(const t of s.items)e.push(t.runId);n=s.nextCursor}while(n);return e}(this.store,t);if(await this.store.deleteAgent(t),this.eventStore?.deleteRunEvents)for(const e of r)try{await this.eventStore.deleteRunEvents({runId:e})}catch(r){Jt.v.log(`Run-event cleanup failed for run ${e} (agent ${t}): ${r instanceof Error?r.message:String(r)}`)}if(this.checkpointStore!==this.store)try{await(this.checkpointStore.deleteAgent?.(t))}catch(r){Jt.v.log(`Checkpoint cleanup failed for deleted agent ${t}: ${r instanceof Error?r.message:String(r)}`)}}async listRuns(t,r){if(!await this.store.getAgent(t))throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});const e=await this.store.listRuns(t,r);return{items:e.items.map((t=>this.toDetachedStoreRun(t))),nextCursor:e.nextCursor}}async getRun(t){const r=await this.findRunById(t);return this.toDetachedStoreRun(r)}async cancelRun(t){const r=await this.findRunById(t);await this.store.cancelRun(r.agentId,r.runId)}async getAgentMessages(t,r){const e=await this.checkpointStore.getFullConversation(t),n="object"==typeof e&&null!==e&&"turns"in e&&Array.isArray(e.turns)?e.turns:void 0;if(!n||0===n.length)return[];const s=r?.offset??0,i=r?.limit?s+r.limit:void 0;return n.slice(s,i).map(((r,e)=>({type:vr(r),uuid:`${t}:${s+e}`,agent_id:t,message:r})))}async appendRunMessage(t){if(!this.eventStore)return;const r=await this.eventStore.appendRunEvent({runId:t.run_id,eventType:W.do,payload:(0,W.Nk)(t)}),e=this.eventNotifier;if(e)try{e.publishRunEventAppended({runId:r.runId,offset:r.offset}).catch((t=>{Jt.v.log(`Failed to publish run event notification for run ${r.runId} at offset ${r.offset}: ${t instanceof Error?t.message:String(t)}`)}))}catch(t){Jt.v.log(`Failed to publish run event notification for run ${r.runId} at offset ${r.offset}: ${t instanceof Error?t.message:String(t)}`)}}toDetachedStoreRun(t){const r=this.createRunEventTailer(t.agentId),e=function(t){switch(t){case"QUEUED":case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"ERROR":case"EXPIRED":return"error";case"CANCELLED":return"cancelled";default:throw new Error("unexpected run lifecycle status")}}(t.status);return new Kt(t.runId,t.requestId,t.agentId,e,t.createdAt,t.model??void 0,t.result??void 0,"error"===e&&t.errorCode?(0,a.vg)(t.errorCode):void 0,Rr(t),(0,Gt.g8)(t.usage),this.store,r?()=>r.streamRunEvents(t.runId,{mode:"running"===e?"replay-and-tail":"replay"}):void 0)}createRunEventTailer(t){var r;if(this.eventStore)return new wt({eventStore:this.eventStore,eventStreamStore:(r=this.eventStore,"attachRunEvents"in r&&"function"==typeof r.attachRunEvents?this.eventStore:void 0),eventNotifier:this.eventNotifier,loadRunStatus:async r=>{const e=await this.store.getRun(t,r);return e?.status}})}async findRunById(t){let r;do{const e=await this.store.listAgents({cursor:r});for(const r of e.items){const e=await this.store.getRun(r.agentId,t);if(e)return e}r=e.nextCursor}while(r);throw new a.j1(`Run ${t} not found`,{isRetryable:!1})}}const ar=new Map;async function ur(){const{createDefaultLocalRunEventNotifier:t}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return t()}function cr(t={}){if(t.localStore){const{workspaceRef:r,scopedWorkspaceRef:e}=wr({localStore:t.localStore,workspaceRef:t.workspaceRef,scopedWorkspaceRef:t.scopedWorkspaceRef}),n=(0,Rt.oc)({localStore:t.localStore,workspaceRef:r,scopedWorkspaceRef:e});return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((t=>new or(n.store,n.checkpointStore,n.eventStore,t,r)))}if(t.store&&t.checkpointStore){const r=t.store,e=t.checkpointStore;return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((n=>new or(r,e,t.eventStore,n,t.workspaceRef??process.cwd())))}const r=t.workspaceRef??process.cwd(),{scopedWorkspaceRef:e}=wr({workspaceRef:r,scopedWorkspaceRef:t.scopedWorkspaceRef}),n=t.stateRoot??(0,Ct.V)(r);if(t.store||t.checkpointStore){const e=t.store?void 0:async function(t){try{const{createDefaultLocalAgentRunStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n,workspaceRef:r}),s=t.checkpointStore?Promise.resolve(t.checkpointStore):async function(t){try{const{createDefaultLocalAgentCheckpointStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n}),o=t.eventStore?Promise.resolve(t.eventStore):async function(t){try{const{createDefaultLocalRunEventStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n}),u=t.eventNotifier?Promise.resolve(t.eventNotifier):ur();return Promise.all([e,s,o,u]).then((([e,n,s,i])=>{const o=t.store??e;if(!o)throw new a.j1("Agent run store is required",{isRetryable:!1});return new or(o,n,s,i,r)}))}const s=`${r}:${e}:${n}`,o=ar.get(s);if(o)return o;const u=async function(t){try{const{SqliteLocalAgentStore:r}=await i.e(52).then(i.bind(i,"./src/agent/store/sqlite-local-agent-store.ts"));return await r.open(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n,workspaceRef:r}).then((n=>{const s=(0,Rt.oc)({localStore:n,workspaceRef:r,scopedWorkspaceRef:e});return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((e=>new or(s.store,t.checkpointStore??s.checkpointStore,t.eventStore??s.eventStore,e,r)))})).catch((t=>{throw ar.delete(s),t}));return ar.set(s,u),u}function lr(t){const r=(0,J.Lc)(t.apiKey);return r===t.apiKey?t:{...t,apiKey:r}}async function mr(t){const r=lr(t);if(r.cloud){fr(r);const{createCloudAgent:t,validateCloudModelAvailability:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return void 0!==r.model&&await e({apiKey:r.apiKey,model:r.model,teamId:r.teamId}),t(r)}return(await cr(Jr(r))).createAgent(r)}function fr(t){(0,Mt.VP)(t.local);for(const r of["tools","disallowedTools","systemPrompt"])if(void 0!==t[r])throw new a.j1(`\`${r}\` is not supported for cloud agents yet; it currently applies to local agents only.`,{isRetryable:!1})}function dr(t){if(void 0!==t&&""===t.trim())throw new a.j1("`systemPrompt` must be non-empty; omit it to keep the default system prompt.",{isRetryable:!1})}function pr(t){return t.startsWith("bc-")}const hr="Local agent usage cannot be filtered by a client-minted `run-` run ID because the backend never receives it. Pass a usage UUID from `getUsage().runs[].runId` instead.";function gr(t){return!0===t?.startsWith("run-")}async function _r(t,r){if(""===r.apiKey)throw new a.j1("API key is required for cloud operations. Caller passed an empty apiKey explicitly; refusing to fall back to CURSOR_API_KEY.",{isRetryable:!1,code:"unauthenticated"});const e=(0,J.Lc)(r.apiKey);if(void 0===e||0===e.length)throw new a.j1("API key is required for cloud operations. Set CURSOR_API_KEY, pass apiKey, or run Cursor.auth.login().",{isRetryable:!1,code:"unauthenticated"});const n=new st.N_(e,void 0,r.teamId),s=await n.getAgentUsage(t,{runId:r.runId});return(0,st.nu)(s)}function Jr(t){const r=(0,Et.kP)(t),{workspaceRef:e,scopedWorkspaceRef:n}=r?wr({...t,localStore:r}):{workspaceRef:qr(t),scopedWorkspaceRef:Sr(t)};return{workspaceRef:e,localStore:r,scopedWorkspaceRef:n}}function wr(t){const r=t.workspaceRef??t.scopedWorkspaceRef??qr(t),e=t.scopedWorkspaceRef;if(void 0!==e&&void 0!==t.workspaceRef&&e!==t.workspaceRef)throw new a.j1(`workspaceRef "${t.workspaceRef}" does not match scopedWorkspaceRef "${e}"`,{isRetryable:!1});return{workspaceRef:r,scopedWorkspaceRef:e??r}}function yr(t){if(Array.isArray(t))throw new a.j1("local.cwd must be a single path; use local.dirs for multi-root workspaces",{isRetryable:!1});return t}function Sr(t){return yr(t?.cwd??t?.local?.cwd)}function qr(t){return Sr(t)??process.cwd()}function Br(t){const r="status"in t?t.status:void 0;return"running"===r||"completed"===r||"error"===r?r:"tool-call-completed"===t.type?"completed":"running"}function Ir(t){return yr(t.local?.cwd)}function Pr(t,r){const e=[],n=new Set;for(const s of[r,...t.local?.dirs??[]]){const t=(0,g.resolve)(s);n.has(t)||(n.add(t),e.push(s))}return e.length>1?e:void 0}function br(t){const r="ARCHIVED"===t.status?void 0:"RUNNING"===t.status?"running":"ERROR"===t.status?"error":"finished";return{agentId:t.agentId,name:t.name??t.agentId,summary:"",lastModified:t.updatedAt.getTime(),createdAt:t.createdAt.getTime(),...r?{status:r}:{},archived:"ARCHIVED"===t.status,runtime:"local",cwd:t.workspaceRef}}function Rr(t){if(!(0,Y.Qb)(t.status))return;if(null===t.startedAt)return;const r=t.finishedAt??t.cancelledAt??t.expiredAt??t.updatedAt;return Math.max(0,r.getTime()-t.startedAt.getTime())}function vr(t){const r=function(t){if(t&&"object"==typeof t){if("turn"in t&&"object"==typeof t.turn&&null!==t.turn&&"case"in t.turn){const r=t.turn.case;if("agentConversationTurn"===r||"shellConversationTurn"===r)return r}return"agentConversationTurn"in t?"agentConversationTurn":"shellConversationTurn"in t?"shellConversationTurn":void 0}}(t);if("agentConversationTurn"===r){const r=function(t){if(t&&"object"==typeof t)return"turn"in t&&"object"==typeof t.turn&&null!==t.turn&&"value"in t.turn?t.turn.value:"agentConversationTurn"in t?t.agentConversationTurn:"shellConversationTurn"in t?t.shellConversationTurn:void 0}(t);if(e=r,Boolean(e&&"object"==typeof e&&("userMessage"in e||"user_message"in e)))return"user"}var e;return"assistant"}var xr=i("../cursor-sdk-local-runtime/dist/run-store/index.js");class kr{constructor(t){this.impl=new xr.tY(t)}async publishRunEventAppended(t){return this.impl.publishRunEventAppended(t)}subscribeRunEvents(t){return this.impl.subscribeRunEvents(t)}}class Er{constructor(t){this.impl=t}static async listen(t){const r=await xr.w.listen(t);return new Er(r)}async close(){return this.impl.close()}}class Cr{constructor(){this.impl=new xr.U1}async publishRunEventAppended(t){return this.impl.publishRunEventAppended(t)}subscribeRunEvents(t){return this.impl.subscribeRunEvents(t)}}function Tr(t){return new kr(t)}function Ur(t){return Er.listen(t)}function Ar(){return new Cr}var $r=i("./src/agent/sdk-config.ts"),Mr=i("node:fs/promises"),Or=i("node:fs"),Dr=i("node:util");const Nr={"target-link":"a symbolic link at the target path","parent-link":"a symbolic link at the parent path","not-a-file":"a non-regular file at the target path"};class Gr extends Error{constructor(t,r){super(`refused ${Nr[t]} ${r}`),this.name="NoFollowRefusedError",this.reason=t,this.path=r}}const Lr="function"==typeof process.getBuiltinModule?process.getBuiltinModule("node:fs"):Or,{O_RDONLY:Fr,O_WRONLY:Kr,O_CREAT:zr,O_EXCL:jr,O_DIRECTORY:Hr=0,O_NOFOLLOW:Wr=0,O_NONBLOCK:Qr=0}=Lr.constants,Vr=Kr|zr|jr|Wr,Xr=Fr|Hr|Wr,Yr=(new Set(["ENXIO","ENODEV","EOPNOTSUPP"]),2**32),Zr=new Map;async function te(t,r,e={}){const{noFollow:n}=e;void 0===n&&function(t){Lr.mkdirSync((0,g.dirname)(t),{recursive:!0})}(t);const s=function(t){const r=Zr.get(t)??[];Zr.set(t,r);const e=new Promise((t=>{r.push(t)}));return 1===r.length&&r[0]?.(),{ready:e,leave:()=>{r.shift(),0===r.length?Zr.delete(t):r[0]?.()}}}((0,g.resolve)(t));await s.ready;try{void 0===n?await re(await async function(t,r){const e=await async function(t){try{return await(0,Dr.promisify)(Lr.realpath)(t)}catch(r){if(le(r))return t;throw r}}(t),n=r??await async function(t){try{return(await(0,Dr.promisify)(Lr.stat)(t)).mode}catch(t){if(le(t))return;throw t}}(e);return{temp:ue(e),target:e,mode:n}}(t,e.mode),r):await async function(t,r,e){try{await re(function(t,r){const e=t.entry(t.name);return ee(t),{temp:ue(e),target:e,mode:r??384,checkTarget:()=>ee(t)}}(t,e),r)}finally{t.close()}}(function(t,r,e){const n=(0,g.resolve)(r),s=(0,g.resolve)(t),i=(0,g.relative)(n,s);if(""===i||".."===i||i.startsWith(`..${g.sep}`)||(0,g.isAbsolute)(i))throw new RangeError(`${s} is not below the no-follow root ${n}`);e&&Lr.mkdirSync(n,{recursive:!0});const o="."===(0,g.dirname)(i)?[]:(0,g.dirname)(i).split(g.sep);return{...("linux"===process.platform?ne:oe)(n,o,e),name:(0,g.basename)(i),shown:s}}(t,n.root,!0),r,e.mode)}finally{s.leave()}}async function re({temp:t,target:r,mode:e,checkTarget:n},s){const i=await(0,Dr.promisify)(Lr.open)(t,Vr,e??438);try{try{await(0,Dr.promisify)(Lr.writeFile)(i,s),void 0!==e&&await(0,Dr.promisify)(Lr.fchmod)(i,e).catch(me),await(0,Dr.promisify)(Lr.fsync)(i)}finally{await(0,Dr.promisify)(Lr.close)(i)}n?.(),await(0,Dr.promisify)(Lr.rename)(t,r)}catch(r){throw await(0,Dr.promisify)(Lr.rm)(t,{force:!0}),r}}function ee(t){const r=Lr.lstatSync(t.entry(t.name),{throwIfNoEntry:!1});if(!0===r?.isSymbolicLink())throw new Gr("target-link",t.shown)}function ne(t,r,e){let n=Lr.openSync(t,Fr|Hr),s=t;try{for(const t of r){s=(0,g.join)(s,t);const r=ie(se(n,t),s,e);Lr.closeSync(n),n=r}}catch(t){throw Lr.closeSync(n),t}const i=n;return{entry:t=>se(i,t),close:()=>Lr.closeSync(i)}}function se(t,r){return`/proc/self/fd/${t}/${r}`}function ie(t,r,e){e&&ae(t);try{return Lr.openSync(t,Xr)}catch(e){throw function(t,r,e){const n=ce(t),s="ELOOP"===n||"ENOTDIR"===n&&!function(t){const r=Lr.lstatSync(t,{throwIfNoEntry:!1});return void 0!==r&&!r.isSymbolicLink()&&!r.isDirectory()}(r);return s?new Gr("parent-link",e):t}(e,t,r)}}function oe(t,r,e){const n=r.reduce(((t,r)=>{const n=(0,g.join)(t,r);if(e&&ae(n),!0===Lr.lstatSync(n,{throwIfNoEntry:!1})?.isSymbolicLink())throw new Gr("parent-link",n);return n}),t);return{entry:t=>(0,g.join)(n,t),close:()=>{}}}function ae(t){try{Lr.mkdirSync(t)}catch(t){if("EEXIST"!==ce(t))throw t}}function ue(t){return`${t}.${(0,Q.randomInt)(Yr)}`}function ce(t){return t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:void 0}function le(t){return"ENOENT"===ce(t)}function me(t){const r=ce(t);if("ENOSYS"!==r&&(void 0!==process.getuid&&0===process.getuid()||"EINVAL"!==r&&"EPERM"!==r))throw t}Error,"function"==typeof process.getBuiltinModule&&process.getBuiltinModule("node:fs");const fe="agents.ndjson",de="runs.ndjson",pe="run_events.ndjson",he="checkpoints.ndjson",ge={agents:fe,runs:de,runEvents:pe,checkpoints:he};let _e=Promise.resolve();function Je(t){const r=_e.then(t,t);return _e=r.then((()=>{}),(()=>{})),r}class we{constructor(t){this.rootDir=t,this.agents=new ye(t),this.checkpoints=new Be(t),this.runEvents=new qe(t),this.runs=new Se(t,this.runEvents)}}class ye{constructor(t){this.rootDir=t}agentsPath(){return(0,g.join)(this.rootDir,fe)}async get(t){return(await be(this.agentsPath(),ve)).find((r=>r.agentId===t.agentId))??null}async create(t){const{agent:r}=t;return Je((async()=>{const t=await be(this.agentsPath(),ve);if(t.some((t=>t.agentId===r.agentId)))throw new Error(`Agent ${r.agentId} already exists`);const e=structuredClone(r);return t.push(e),await Te(this.agentsPath(),t),structuredClone(e)}))}async update(t){const{agent:r}=t;return Je((async()=>{const t=await be(this.agentsPath(),ve),e=t.findIndex((t=>t.agentId===r.agentId));if(e<0)throw new Error(`Agent ${r.agentId} not found`);const n=structuredClone(r);return t[e]=n,await Te(this.agentsPath(),t),structuredClone(n)}))}async delete(t){return Je((async()=>{const r=await be(this.agentsPath(),ve),e=r.filter((r=>!function(t,r){return!(r.agentIds?.length&&!r.agentIds.includes(t.agentId))&&(void 0===r.cwd||t.cwd===r.cwd)}(r,t.filter)));if(e.length===r.length)throw new Error("No agents matched delete filter");await Te(this.agentsPath(),e)}))}async list(t){const r=t?.filter,e=await be(this.agentsPath(),ve);return(0,Rt.tg)(e,r)}}class Se{constructor(t,r){this.rootDir=t,this.runEvents=r}runsPath(){return(0,g.join)(this.rootDir,de)}async get(t){return(await be(this.runsPath(),xe)).find((r=>r.agentId===t.agentId&&r.runId===t.runId))??null}async create(t){const{run:r}=t;return Je((async()=>{const t=await be(this.runsPath(),xe);if(t.some((t=>t.agentId===r.agentId&&t.runId===r.runId)))throw new Error(`Run ${r.runId} already exists for agent ${r.agentId}`);const e=structuredClone(r);return t.push(e),await Te(this.runsPath(),t),structuredClone(e)}))}async update(t){const{run:r}=t;return Je((async()=>{const t=await be(this.runsPath(),xe),e=t.findIndex((t=>t.agentId===r.agentId&&t.runId===r.runId));if(e<0)throw new Error(`Run ${r.runId} not found for agent ${r.agentId}`);const n=structuredClone(r);return t[e]=n,await Te(this.runsPath(),t),structuredClone(n)}))}async delete(t){const r=t.filter,e=await Je((async()=>{const t=await be(this.runsPath(),xe),e=t.filter((t=>Pe(t,r)));if(0===e.length)return[];const n=t.filter((t=>!Pe(t,r)));return await Te(this.runsPath(),n),e}));for(const t of e)await this.runEvents.delete({filter:{runIds:[t.runId]}})}async list(t){const r=t?.filter,e=(await be(this.runsPath(),xe)).filter((t=>Pe(t,r)));return(0,Rt.f1)(e,r)}}class qe{constructor(t){this.rootDir=t}eventsPath(){return(0,g.join)(this.rootDir,pe)}async append(t){return Je((async()=>{const r=await be(this.eventsPath(),ke),e=t.idempotencyKey?r.find((r=>r.runId===t.runId&&r.idempotencyKey===t.idempotencyKey)):void 0;if(e)return Ue(e);const n=r.filter((r=>r.runId===t.runId)).reduce(((t,r)=>Math.max(t,r.seq)),0)+1,s={runId:t.runId,seq:n,offset:String(n),eventType:t.eventType,payload:t.payload??null,payloadRef:t.payloadRef??null,idempotencyKey:t.idempotencyKey??null,createdAt:(new Date).toISOString()};return r.push(s),await Te(this.eventsPath(),r),Ue(s)}))}async list(t){const r=await be(this.eventsPath(),ke),e=Number.parseInt(t.afterOffset??"0",10),n=t.limit??100,s=r.filter((r=>r.runId===t.runId&&r.seq>e)).sort(((t,r)=>t.seq-r.seq)),i=s.slice(0,n).map(Ue);return{items:i,...s.length>i.length&&i.length>0?{nextOffset:i.at(-1)?.offset}:{}}}async delete(t){return Je((async()=>{const r=await be(this.eventsPath(),ke),e=t.filter.runIds&&t.filter.runIds.length>0?new Set(t.filter.runIds):null,n=e?r.filter((t=>!e.has(t.runId))):[];await Te(this.eventsPath(),n)}))}}class Be{constructor(t){this.rootDir=t}checkpointsPath(){return(0,g.join)(this.rootDir,he)}async get(t){const r=(await be(this.checkpointsPath(),Ee)).find((r=>r.agentId===t.agentId&&r.blobId===t.blobId));return r?Buffer.from(r.dataBase64,"base64"):null}async create(t){const{agentId:r,blobId:e,data:n}=t;return Je((async()=>{const t=await be(this.checkpointsPath(),Ee);if(t.some((t=>t.agentId===r&&t.blobId===e)))throw new Error(`Checkpoint blob ${e} already exists for agent ${r}`);t.push({agentId:r,blobId:e,dataBase64:Buffer.from(n).toString("base64")}),await Te(this.checkpointsPath(),t)}))}async update(t){const{agentId:r,blobId:e,data:n}=t;return Je((async()=>{const t=await be(this.checkpointsPath(),Ee),s=t.findIndex((t=>t.agentId===r&&t.blobId===e));if(s<0)throw new Error(`Checkpoint blob ${e} not found for agent ${r}`);t[s]={agentId:r,blobId:e,dataBase64:Buffer.from(n).toString("base64")},await Te(this.checkpointsPath(),t)}))}async list(t){const r=t?.filter,e=(await be(this.checkpointsPath(),Ee)).filter((t=>Ie(t,r))).map((t=>t.blobId));return(0,Rt.Jg)(e,r)}async delete(t){const r=t.filter;return Je((async()=>{const t=(await be(this.checkpointsPath(),Ee)).filter((t=>!Ie(t,r)));await Te(this.checkpointsPath(),t)}))}}function Ie(t,r){return!((r?.agentIds?.length||r?.blobIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.blobIds?.length&&!r.blobIds.includes(t.blobId)))}function Pe(t,r){return!(r?.agentIds&&r.agentIds.length>0&&!r.agentIds.includes(t.agentId)||r?.runIds&&r.runIds.length>0&&!r.runIds.includes(t.runId))}async function be(t,r){let e;try{e=await(0,Mr.readFile)(t,"utf8")}catch(t){if(function(t){return"object"==typeof t&&null!==t&&"code"in t&&"ENOENT"===t.code}(t))return[];throw t}const n=e.split("\n").filter((t=>t.trim().length>0)),s=[];for(const[e,i]of n.entries()){let o;try{o=JSON.parse(i)}catch{if(e===n.length-1)break;throw Ce(t,e+1)}if(!r(o)){if(e===n.length-1)break;throw Ce(t,e+1)}s.push(o)}return s}function Re(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function ve(t){return Re(t)&&"string"==typeof t.agentId&&"string"==typeof t.cwd&&function(t){return"idle"===t||"running"===t||"error"===t||"archived"===t}(t.status)&&"number"==typeof t.createdAt&&"number"==typeof t.updatedAt}function xe(t){return Re(t)&&"string"==typeof t.runId&&"string"==typeof t.agentId&&"number"==typeof t.turnNumber&&function(t){return"queued"===t||"running"===t||"finished"===t||"error"===t||"cancelled"===t||"expired"===t}(t.status)&&"number"==typeof t.createdAt&&"number"==typeof t.updatedAt}function ke(t){return Re(t)&&"string"==typeof t.runId&&"number"==typeof t.seq&&"string"==typeof t.offset&&"string"==typeof t.eventType&&"string"==typeof t.createdAt&&(null===t.payloadRef||"string"==typeof t.payloadRef)&&(null===t.idempotencyKey||"string"==typeof t.idempotencyKey)}function Ee(t){return Re(t)&&"string"==typeof t.agentId&&"string"==typeof t.blobId&&"string"==typeof t.dataBase64}function Ce(t,r){return new Error(`Corrupt local agent store: failed to parse record ${r} of ${t}`)}async function Te(t,r){const e=r.map((t=>JSON.stringify(t))).join("\n");await te(t,e.length>0?`${e}\n`:"")}function Ue(t){return{...t,createdAt:new Date(t.createdAt).getTime()}}async function Ae(t,r){try{return await r()}catch(r){throw(0,a.Nt)(r,{operation:t})}}Symbol.asyncDispose;class $e{constructor(){}static async create(t){return Ae("Agent.create",(async()=>{if(void 0===t.agentId&&void 0!==t.cloud?.envVars)return mr(t);const r=t.agentId??(t.cloud?(0,xr.M2)():(0,xr.WQ)());return mr({...t,agentId:r})}))}static async resume(t,r){return Ae("Agent.resume",(()=>async function(t,r){const e=lr(r??{});if(e.cloud||t.startsWith("bc-")){fr(e);const{resumeCloudAgent:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t,e)}return(await cr(Jr(e))).resumeAgent(t,e)}(t,r)))}static async prompt(t,r){return Ae("Agent.prompt",(async()=>{const e=await $e.create(r??{});try{const r=await e.send(t);return await r.wait()}finally{await e[Symbol.asyncDispose]()}}))}static async list(t){return Ae("Agent.list",(()=>async function(t){if("cloud"===t?.runtime){const{listCloudAgents:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t)}return(await cr(Jr(t))).listAgents(t)}(t)))}static async listRuns(t,r){return Ae("Agent.listRuns",(()=>async function(t,r){if("cloud"===r?.runtime){const{listCloudRuns:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).listRuns(t,r)}(t,r)))}static async getRun(t,r){return Ae("Agent.getRun",(()=>async function(t,r){if("cloud"===r?.runtime){const{getCloudRun:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).getRun(t)}(t,r)))}static async cancelRun(t,r){return Ae("Agent.cancelRun",(()=>async function(t,r){if("cloud"===r?.runtime){const{cancelCloudRun:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).cancelRun(t)}(t,r)))}static async get(t,r){return Ae("Agent.get",(()=>async function(t,r){if(pr(t)){const{getCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).getAgent(t)}(t,r)))}static async archive(t,r){return Ae("Agent.archive",(()=>async function(t,r){if(pr(t)){const{archiveCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).archiveAgent(t)}(t,r)))}static async unarchive(t,r){return Ae("Agent.unarchive",(()=>async function(t,r){if(pr(t)){const{unarchiveCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).unarchiveAgent(t)}(t,r)))}static async delete(t,r){return Ae("Agent.delete",(()=>async function(t,r){if(pr(t)){const{deleteCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).deleteAgent(t)}(t,r)))}static async getUsage(t,r){return Ae("Agent.getUsage",(()=>async function(t,r){if(!pr(t)&&gr(r?.runId))throw(0,a.Nt)(new a.j1(hr,{isRetryable:!1}),{operation:"Agent.getUsage"});return _r(t,r??{})}(t,r)))}}$e.messages={list:(t,r)=>Ae("Agent.messages.list",(()=>async function(t,r){return(await cr(Jr(r))).getAgentMessages(t,r)}(t,r)))};class Me{constructor(){}static configure(t){(0,$r.xP)(t)}static async me(t){return Ae("Cursor.me",(()=>async function(t){const{getCloudMe:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))}}Me.models={list:t=>Ae("Cursor.models.list",(()=>async function(t){const{listCloudModels:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))},Me.repositories={list:t=>Ae("Cursor.repositories.list",(()=>async function(t){const{listCloudRepositories:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))},Me.auth={login:t=>Ae("Cursor.auth.login",(()=>async function(t={}){const r=(0,l.pi)(t.backendUrl),e=(0,l.Fw)(t.websiteUrl),n=(0,l.bi)(e);t.onLoginUrl?.(n.loginUrl);let s=void 0!==t.onLoginUrl;const i=t.openBrowser??!0;if("function"==typeof i)await i(n.loginUrl),s=!0;else if(i&&(o=n.loginUrl,!process.env.NO_OPEN_BROWSER&&!Boolean(process.env.SSH_CONNECTION??process.env.SSH_CLIENT??process.env.SSH_TTY)&&_(o)))try{await function(t){return _(t)?new Promise(((r,e)=>{const{cmd:n,args:s}=function(t){const r=process.platform;return"darwin"===r?{cmd:"open",args:[t]}:"win32"===r?{cmd:g.join(process.env.SYSTEMROOT??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),args:["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`]}:{cmd:"xdg-open",args:[t]}}(t),i=(0,h.spawn)(n,s,{stdio:"ignore",windowsHide:!0});i.once("error",(t=>{e(new Error(`Failed to open browser: ${t.message}`))})),i.once("spawn",(()=>r())),i.unref()})):Promise.reject(new Error(`Invalid URL: only http:// and https:// links can be opened. Received: ${t}`))}(n.loginUrl),s=!0}catch{}var o;s||process.stderr.write(`Could not open a browser. Open this URL to sign in to Cursor:\n\n ${n.loginUrl}\n\n`);const u=await(0,l.er)({apiUrl:r,uuid:n.uuid,verifier:n.verifier,signal:t.signal,onWarning:t=>{process.stderr.write(`warning: ${t}\n`)}});if(null===u)throw new a.v3(t.signal?.aborted?"Login was cancelled.":"Login failed or timed out. Please try again.",{code:"unauthenticated",isRetryable:!0});const c=t.apiKeyTtlMs??w;if(!Number.isFinite(c)||c<=0)throw new a.v3(`apiKeyTtlMs must be a positive number of milliseconds, got ${c}`,{code:"invalid_argument",isRetryable:!1});const q=Date.now()+c,B=await async function(t,r){const e=r??function({backendUrl:t,accessToken:r}){const e=(0,p.cf)({baseUrl:t,httpVersion:"1.1",interceptors:[t=>async e=>(e.header.set("authorization",`Bearer ${r}`),t(e))]});return(0,d.createClient)(m.I,e)}({backendUrl:t.backendUrl,accessToken:t.accessToken});let n,s;try{n=(await e.createUserApiKey(new f.cEg({name:t.name,expiresAt:void 0!==t.expiresAtMs?BigInt(Math.floor(t.expiresAtMs)):void 0}))).apiKey}catch(t){if(t instanceof d.ConnectError){const r=(0,a.e_)(t);throw new a.v3(`Login succeeded, but creating an SDK API key failed: ${r.message} (your team's settings may restrict user API keys — ask a team admin, or pass an existing API key directly)`,{code:r.code,isRetryable:r.isRetryable,cause:t})}throw t}if(""===n)throw new a.v3("Login succeeded, but the server returned an empty API key.",{code:"internal",isRetryable:!0});try{const t=await e.getMe(new f.Ewt({}));s=""!==t.email?t.email:void 0}catch{s=void 0}return{apiKey:n,email:s}}({backendUrl:r,accessToken:u.accessToken,name:t.apiKeyName??S(),expiresAtMs:q});if(null!==t.store){const e=t.store??y(),n={version:1,backendUrl:r,apiKey:B.apiKey,apiKeyExpiresAtMs:q,email:B.email,createdAtMs:Date.now()};await e.save(n),(0,J.s1)()}return{apiKey:B.apiKey,email:B.email,apiKeyExpiresAtMs:q}}(t))),logout:t=>Ae("Cursor.auth.logout",(()=>async function(t={}){const r=t.store??y();await r.clear(),(0,J.s1)()}(t))),status:t=>Ae("Cursor.auth.status",(()=>async function(t={}){const r=t.store??y(),e=await r.load();return void 0===e||void 0!==e.apiKeyExpiresAtMs&&e.apiKeyExpiresAtMs<=Date.now()?{status:"logged-out"}:{status:"logged-in",backendUrl:e.backendUrl,email:e.email,apiKeyExpiresAtMs:e.apiKeyExpiresAtMs}}(t)))};var Oe=i("zod/v3"),De=i("../cursor-sdk-shared/dist/tool-call-types.js");const Ne=Oe.object({text:Oe.string()}),Ge=Oe.object({text:Oe.string(),thinkingDurationMs:Oe.number().optional()}),Le=Oe.object({text:Oe.string()}),Fe=Oe.object({command:Oe.string(),workingDirectory:Oe.string().optional()}),Ke=Oe.object({stdout:Oe.string(),stderr:Oe.string(),exitCode:Oe.number()}),ze=Oe.discriminatedUnion("type",[Oe.object({type:Oe.literal("assistantMessage"),message:Ne}),Oe.object({type:Oe.literal("toolCall"),message:De.C6}),Oe.object({type:Oe.literal("thinkingMessage"),message:Ge})]),je=Oe.object({userMessage:Le.optional(),steps:Oe.array(ze)}),He=Oe.object({shellCommand:Fe.optional(),shellOutput:Ke.optional()}),We=Oe.discriminatedUnion("type",[Oe.object({type:Oe.literal("agentConversationTurn"),turn:je}),Oe.object({type:Oe.literal("shellConversationTurn"),turn:He})]);var Qe=i("./src/agent/types/delta-types.ts");function Ve(t){return t.type}var Xe=i("../cursor-sdk-shared/dist/message-schemas.js");module.exports=o})(); \ No newline at end of file diff --git a/dist/esm/977.js b/dist/esm/977.js -index 3bc50aaa257cda261cef797a5026b00dc5b977a7..09035ac75b4b90c0fe7250105d3c64431da5d43c 100644 +index 3bc50aaa257cda261cef797a5026b00dc5b977a7..0bc348e6ee229979047b61c06c5eaaf82d9a011d 100644 --- a/dist/esm/977.js +++ b/dist/esm/977.js @@ -1,4 +1,4 @@ -import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` -+import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({attributionConfigProvider:kB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new i.QFf({action:{case:"resumeAction",value:new i.qKo}}):!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` ++import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,(e.plugins||e.pluginBootstrap)&&__p("plugins"),n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,e.mcp&&__p("mcp"),n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,e.hooks&&__p("hooks"),n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility&&__p("skills"),e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return __p("connecting"),n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({attributionConfigProvider:kB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new i.QFf({action:{case:"resumeAction",value:new i.qKo}}):!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` function global:__cursorUtf8FromLatin1 { param([string]$Text) Set-StrictMode -Off @@ -107,7 +107,7 @@ index e027f4cfecdfb2be8aefcd7a2de7f97bd6ecd3b0..dd13515bda95ced477222c6cdac9bb27 export interface GetUsageOptions { /** diff --git a/dist/esm/index.js b/dist/esm/index.js -index 2aba0a2689fb610e1a5311893aa65f93b4752be1..50d3e5e7b3dfc762c558d4a8bd6f81e2615e9e81 100644 +index 2aba0a2689fb610e1a5311893aa65f93b4752be1..62ccc7a4f9674c0573d3102909537fa09d7ca460 100644 --- a/dist/esm/index.js +++ b/dist/esm/index.js @@ -1 +1 @@ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e53019e0f39bd..36619d824d225 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -364,7 +364,7 @@ pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e '@clerk/expo-native-components@0.4.4': 7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4 - '@cursor/sdk@1.4.2': d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a + '@cursor/sdk@1.4.2': caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918 '@effect/platform-node-shared@4.1.5': 06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14 '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f @@ -858,7 +858,7 @@ importers: version: 0.3.321(@anthropic-ai/sdk@0.93.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.2(supports-color@8.1.1)(zod@4.6.7))(zod@4.6.7) '@cursor/sdk': specifier: 1.4.2 - version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) + version: 1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) @@ -1766,7 +1766,7 @@ importers: dependencies: '@cursor/sdk': specifier: 1.4.2 - version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) + version: 1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -14253,7 +14253,7 @@ snapshots: '@cursor/sdk-win32-x64@1.4.2': optional: true - '@cursor/sdk@1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7)': + '@cursor/sdk@1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7)': dependencies: '@bufbuild/protobuf': 1.10.0 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) From 3e3bb765d12464c0b15e914e954b579746ed747d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:28:20 -0800 Subject: [PATCH 021/288] fix(server): Claude turns no longer stay in memory for 10 minutes after each request (#41238) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 83 ++++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 23 ++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 3d017de3925fa..f753075022d0d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -62,6 +62,8 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; @@ -116,7 +118,10 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve import { AGENT_FEEDBACK_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; -import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import { + makeProviderFailure, + PROVIDER_RETRY_BUDGET_MS, +} from "@t3tools/provider-core/server/failure"; import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; @@ -16758,6 +16763,82 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("releases the silence watch once Claude answers each request", () => + Effect.gen(function* () { + // Counts pending sleeps of the silence budget: each one holds the whole turn context. + const clock = yield* Clock.Clock; + let pendingWatches = 0; + const countingClock: Clock.Clock = { + currentTimeMillisUnsafe: () => clock.currentTimeMillisUnsafe(), + currentTimeMillis: clock.currentTimeMillis, + currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), + currentTimeNanos: clock.currentTimeNanos, + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), + monotonicTimeNanos: clock.monotonicTimeNanos, + sleep: (duration) => + Duration.toMillis(duration) === PROVIDER_RETRY_BUDGET_MS + ? Effect.suspend(() => { + pendingWatches += 1; + return clock.sleep(duration); + }).pipe(Effect.ensuring(Effect.sync(() => (pendingWatches -= 1)))) + : clock.sleep(duration), + }; + yield* Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-silence-watch-released"), + text: "start again", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state: "started", + uuid: "00000000-0000-4000-8000-0000000007a0", + session_id: WAKE_NATIVE_SESSION, + }), + ); + for (let index = 1; index <= 5; index++) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid: `00000000-0000-4000-8000-0000000007a${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "stream_event", + event: { type: "message_start", message: { id: `msg_watch_${index}` } }, + parent_tool_use_id: null, + session_id: WAKE_NATIVE_SESSION, + uuid: `00000000-0000-4000-8000-0000000007b${index}`, + }), + ); + } + assert.strictEqual(pendingWatches, 0, "answered requests left silence watches running"); + }).pipe(Effect.provideService(Clock.Clock, countingClock)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it it.effect.each([ { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9ff0c8fc16511..ad34325d04191 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5272,6 +5272,8 @@ interface ActiveClaudeTurnContext { retryBudgetFailure?: OrchestrationV2ProviderFailure; // Set when the prompt starts or a request goes out; cleared by the turn's next frame. unansweredRequestSince?: DateTime.Utc | undefined; + // Interrupted once the silence clears, so the session scope stops holding this context. + unansweredRequestWatch?: Fiber.Fiber | undefined; readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly autoCompactWindow: string; @@ -6775,6 +6777,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); + const clearUnansweredRequestWatch = (context: ActiveClaudeTurnContext) => { + const watch = context.unansweredRequestWatch; + context.unansweredRequestWatch = undefined; + return watch === undefined ? Effect.void : Fiber.interrupt(watch); + }; + const failStalledTurn = Effect.fn("ClaudeAdapterV2.failStalledTurn")(function* ( context: ActiveClaudeTurnContext, failure: OrchestrationV2ProviderFailure, @@ -10088,6 +10096,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.update(activeTurn, (current) => current?.providerTurnId === input.context.providerTurnId ? null : current, ); + yield* clearUnansweredRequestWatch(input.context); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -11139,10 +11148,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { const since = yield* DateTime.now; context.unansweredRequestSince = since; - yield* failUnansweredRequest(context, since).pipe( - Effect.delay(PROVIDER_RETRY_BUDGET_MS), + const previousWatch = context.unansweredRequestWatch; + // Only the wait is interruptible: a fired failure runs on its own fiber. + context.unansweredRequestWatch = yield* Effect.sleep(PROVIDER_RETRY_BUDGET_MS).pipe( + Effect.andThen( + failUnansweredRequest(context, since).pipe(Effect.forkIn(sessionScope)), + ), Effect.forkIn(sessionScope), ); + if (previousWatch !== undefined) yield* Fiber.interrupt(previousWatch); + // A turn that settled meanwhile already cleared its watch, so drop the new one too. + if ((yield* Ref.get(activeTurn)) !== context) { + yield* clearUnansweredRequestWatch(context); + } } else if ( // Background tasks from earlier turns keep streaming while the root request hangs. // Only the root starts depth-1 tasks, so such a start (a forked skill) is this turn's. @@ -11154,6 +11172,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) ) { context.unansweredRequestSince = undefined; + yield* clearUnansweredRequestWatch(context); } } const focusedPlugin = claudeFocusRequestedPanePlugin(message); From 0356d68835b7b579bb7151abf2f7919d9cce84f3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:30:07 -0800 Subject: [PATCH 022/288] fix(server): Claude plan ids live with the turn, not the session (#41244) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/Adapters/ClaudeAdapterV2.ts | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index ad34325d04191..c93b840f44e4d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5284,6 +5284,7 @@ interface ActiveClaudeTurnContext { readonly providerTurnOrdinal: number; readonly startedAt: DateTime.Utc; readonly itemOrdinals: Map; + readonly planIds: Map; readonly assistant: { fallbackText: string; // Result-only replies of steered segments that ended before the current one. @@ -6236,9 +6237,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const taskListsByNativeThread = yield* Ref.make( new Map(), ); - const planIdsByNativeItem = yield* Ref.make( - new Map(), - ); const providerRetries = yield* Ref.make( new Map(), ); @@ -8673,8 +8671,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }) { const updatedAt = yield* DateTime.now; const projectionNativeItemId = `${input.kind}:${input.nativeItemId}`; - const planKey = `${input.context.input.threadId}:${projectionNativeItemId}`; - const existingPlanId = (yield* Ref.get(planIdsByNativeItem)).get(planKey); + const existingPlanId = input.context.planIds.get(projectionNativeItemId); const planId = existingPlanId ?? (yield* idAllocator.allocate.plan({ @@ -8682,13 +8679,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runId: input.context.input.runId, driver: CLAUDE_PROVIDER, })); - if (existingPlanId === undefined) { - yield* Ref.update(planIdsByNativeItem, (current) => { - const updated = new Map(current); - updated.set(planKey, planId); - return updated; - }); - } + input.context.planIds.set(projectionNativeItemId, planId); const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CLAUDE_PROVIDER, nativeItemId: projectionNativeItemId, @@ -13850,6 +13841,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( providerTurnOrdinal, startedAt, itemOrdinals: new Map(), + planIds: new Map(), assistant: { fallbackText: "", earlierFallbackText: "", From c061593db2ba6ba4289d0ff39390444afe73bbe9 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:53:33 -0600 Subject: [PATCH 023/288] fix(server): pass explicit null payloads to workflows (#41245) Co-authored-by: Julius Marminge --- .../mcp/toolkits/workflow/handlers.test.ts | 59 +++++++++++++++++++ .../src/mcp/toolkits/workflow/handlers.ts | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/toolkits/workflow/handlers.test.ts diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts new file mode 100644 index 0000000000000..c036cb8d7e649 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -0,0 +1,59 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import * as Workflows from "../../../workflows/Workflows.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; +import * as WorkflowHandlers from "./handlers.ts"; +import { WorkflowToolkit } from "./tools.ts"; + +it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => + Effect.gen(function* () { + const payloads: Array = []; + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), + ); + yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + for (const input of [{ input: null }, {}]) { + yield* toolkit + .handle("t3_workflow", { + action: "start", + workflow: "echo", + idempotencyKey: "trial", + ...input, + }) + .pipe(Stream.unwrap, Stream.runCollect); + } + }).pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge(layerDependencies), + ), + ), + ); + expect(payloads).toEqual([null, {}]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index fe19b06108480..b3ccb35f28151 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -52,7 +52,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { const name = yield* required(input.workflow, "workflow"); const idempotencyKey = yield* required(input.idempotencyKey, "idempotencyKey"); const { runId } = yield* workflows - .start(name, input.input ?? {}, { idempotencyKey }) + .start(name, input.input === undefined ? {} : input.input, { idempotencyKey }) .pipe(Effect.mapError(refused)); return yield* workflows.get(runId).pipe(Effect.mapError(refused)); } From 1f13db585d6af6b5be82e50c7510a57a81eb5ccf Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:54:18 -0600 Subject: [PATCH 024/288] fix(server): accept unquoted HTML favicon attributes (#41239) Co-authored-by: Julius Marminge --- .../project/ProjectFaviconResolver.test.ts | 24 +++++++++++++++ .../src/project/ProjectFaviconResolver.ts | 30 +++++++++++++++---- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index d4cc22efd220a..7c0207eed557d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -231,6 +231,30 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(yield* resolver.resolvePath(tokenListCwd)).toBe( (yield* Path.Path).join(tokenListCwd, "brand.svg"), ); + + const unquotedCwd = yield* makeTempDir; + yield* writeTextFile( + unquotedCwd, + "index.html", + ``, + ); + yield* writeTextFile(unquotedCwd, "app.css", "body {}"); + yield* writeTextFile(unquotedCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(unquotedCwd)).toBe( + (yield* Path.Path).join(unquotedCwd, "brand.svg"), + ); + + const quotedValueCwd = yield* makeTempDir; + yield* writeTextFile( + quotedValueCwd, + "index.html", + ``, + ); + yield* writeTextFile(quotedValueCwd, "app.css", "body {}"); + yield* writeTextFile(quotedValueCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(quotedValueCwd)).toBe( + (yield* Path.Path).join(quotedValueCwd, "brand.svg"), + ); }), ); diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 497538634ae73..12c8e2fc63ea2 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -79,8 +79,9 @@ const ICON_SOURCE_FILES = [ const HTML_LINK_RE = /]*>/gi; // `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link. const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`; -const HTML_ICON_REL_RE = new RegExp(String.raw`\brel=${ICON_REL_VALUE}`, "i"); -const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; +// HTML attribute syntax: a name, then an optional double-quoted, single-quoted, or unquoted value. +const HTML_ATTRIBUTE_RE = + /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; @@ -123,9 +124,28 @@ export class ProjectFaviconResolver extends Context.Service< function extractIconHref(source: string): string | null { for (const [tag] of source.matchAll(HTML_LINK_RE)) { - if (!HTML_ICON_REL_RE.test(tag)) continue; - const hrefMatch = tag.match(HTML_ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + const attributes = new Map(); + for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag + .slice(" Date: Sun, 22 Nov 2026 21:58:46 -0800 Subject: [PATCH 025/288] docs(user): explain how settling differs from archiving a thread (#41253) --- docs/user/project-settings.md | 3 +++ docs/user/thread-sidebar.md | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 775adeb67d900..fe367c7b45b3a 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -103,6 +103,9 @@ project starts a new thread there on its next run. Deleting a thread also deletes tasks that post into that thread. Tasks that start a new thread on each run survive deletion of their previous threads. +An archived thread refuses messages, so a task that posts into one stays on and fails +each run until you unarchive the thread or pick another destination. To set a task's thread +aside without breaking it, settle the thread; see [Settle or archive](thread-sidebar.md#settle-or-archive). You can edit, pause, resume, run immediately, or delete a task from the list. Webhook tasks only run when their URL is called, so they can't be run diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 9bbf3194a9d59..6c63f1b9c342d 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -213,6 +213,19 @@ rules to connected environments that support shared settings. Offline environmen and older servers keep their previous values. Changing a rule does not reopen already settled threads. +### Settle or archive + +Settle is for work that is done for now. A settled thread stays in the sidebar's Settled +section and in search, and a message to it, from you, an agent, or a scheduled task, makes it +active again. Archive is for work you want out of the way. An archived thread leaves the +sidebar and search and shows only in **Settings → Archive**, where you can unarchive or +delete it. It refuses new messages, including ones from agents and scheduled tasks, until you +unarchive it. Removing a project deletes its threads either way. + +A scheduled task that posts into one thread keeps running after you archive that thread, and +each run fails. Settle the thread instead, or move or pause the task in **Settings → Scheduled +tasks**. + ## Link a pull request The server finds the PR for each unsettled thread's saved branch, even when your From f1c13177d8a55237897d4de840372c50d3304f03 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 00:04:41 -0600 Subject: [PATCH 026/288] fix(web): spreadsheet text and fills no longer vanish when their cell scrolls out (#41263) Co-authored-by: Claude Opus 5.5 Co-authored-by: Cursor --- ...achmentFilePreview.office.browser.test.tsx | 2 + .../components/files/office/sheet-frame.ts | 181 +++++++++++------- .../files/office/sheet-resize.browser.test.ts | 63 ++++++ 3 files changed, 181 insertions(+), 65 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx index 516ea535fd9b6..6826d3369c76a 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx @@ -286,6 +286,8 @@ it("preserves merged text across tile clears", async () => { context, { viewport: { x: 0, y: 0, width: 400, height: 80 }, + behind: { x: 0, y: 0 }, + panes: { width: 0, height: 0 }, list: { width: 400, height: 80, commands: [] }, tiles: [ { diff --git a/apps/web/src/components/files/office/sheet-frame.ts b/apps/web/src/components/files/office/sheet-frame.ts index 3b7868bf2d3fe..80723af7256cd 100644 --- a/apps/web/src/components/files/office/sheet-frame.ts +++ b/apps/web/src/components/files/office/sheet-frame.ts @@ -1,10 +1,5 @@ // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. -import { - paintDisplayList, - type DisplayList, - type GridMeta, - type WorkbookHandle, -} from "@betteroffice/xlsx"; +import { paintDisplayList, type DisplayList, type WorkbookHandle } from "@betteroffice/xlsx"; import { attempt } from "./sheet-cells"; import { frozenSize } from "./sheet-paint"; import type { SheetViewport } from "./sheet-protocol"; @@ -21,6 +16,12 @@ const maxSplit = 8; */ const seamOverlap = 8; +/** + * How far before a frame its cells are drawn from, in CSS pixels. The engine draws only the cells from a viewport's + * first track on, so the text of a cell before it, overflowing or merged into the frame, would vanish with that cell. + */ +const reach = { x: 1024, y: 512 }; + /** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */ type Tile = { readonly list: DisplayList; @@ -32,12 +33,14 @@ type Tile = { /** * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the - * viewport it shows. + * viewport it shows. The tiles' cells past the frozen panes start `behind` the viewport's. */ export type Frame = { readonly list: DisplayList; readonly tiles: readonly Tile[]; readonly viewport: SheetViewport; + readonly behind: { readonly x: number; readonly y: number }; + readonly panes: { readonly width: number; readonly height: number }; }; /** @@ -50,22 +53,20 @@ export function drawFrame( frozen: { readonly rows: number; readonly cols: number }, wider?: SheetViewport, ): Frame | undefined { - const around = wider && untruncated(workbook, wider); - - if (wider && around) - return { - list: around, - tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }], - viewport: wider, - }; - - const whole = untruncated(workbook, viewport); - - if (whole) - return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport }; + return ( + (wider && reaching(workbook, wider, frozen, false)) || + reaching(workbook, viewport, frozen, true) + ); +} - // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of - // the frame give its tracks, and so where its frozen panes end. +/** A frame of `viewport` drawn from up to `reach` before it, split into tiles when `split` and the engine needs it. */ +function reaching( + workbook: WorkbookHandle, + viewport: SheetViewport, + frozen: { readonly rows: number; readonly cols: number }, + split: boolean, +): Frame | undefined { + // One row and one column of the viewport give its tracks, and so where its frozen panes end. const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid; const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid; @@ -79,8 +80,33 @@ export function drawFrame( ...(columns.colIndices ? { colIndices: columns.colIndices } : {}), colOffsets: columns.colOffsets, }; + const panes = frozenSize(grid, frozen); + const behind = { x: Math.min(reach.x, viewport.x), y: Math.min(reach.y, viewport.y) }; + const area = { + x: viewport.x - behind.x, + y: viewport.y - behind.y, + width: viewport.width + behind.x, + height: viewport.height + behind.y, + }; + const whole = untruncated(workbook, area); + // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. + const tiles = whole + ? [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }] + : split + ? tiled(workbook, area, panes, 2) + : undefined; - return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2); + if (!tiles) return undefined; + + const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); + + return { + list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, + tiles, + viewport, + behind, + panes, + }; } /** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */ @@ -133,7 +159,7 @@ export function chartFonts( /** * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a - * tile covers the panes it repeats. + * tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put. */ export function paintFrame( context: OffscreenCanvasRenderingContext2D, @@ -148,58 +174,92 @@ export function paintFrame( const tiled = frame.tiles.length > 1; const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined; const textContext = text?.getContext("2d"); - - frame.tiles.forEach((tile) => { - const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }; - const list = tiled - ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } - : tile.list; - - if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at); + const columns = bands(frame.panes.width, frame.behind.x); + const rows = bands(frame.panes.height, frame.behind.y); + const parts = frame.tiles.flatMap((tile) => + rows.flatMap((row) => + columns.flatMap((column) => { + const left = Math.max(column.start, tile.clipX - column.shift); + const top = Math.max(row.start, tile.clipY - row.shift); + + if (left >= column.end || top >= row.end) return []; + + const clip = { + left: Math.round(origin.x + left * ratio), + top: Math.round(origin.y + top * ratio), + right: Math.round(origin.x + column.end * ratio), + bottom: Math.round(origin.y + row.end * ratio), + }; + + return [ + { + tile, + at: { + x: origin.x + (tile.x - column.shift) * ratio, + y: origin.y + (tile.y - row.shift) * ratio, + }, + clip: + left === 0 && top === 0 && column.end === Infinity && row.end === Infinity + ? undefined + : clip, + }, + ]; + }), + ), + ); + const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => { + if (!clip) return paint(); context.save(); context.setTransform(1, 0, 0, 1, 0, 0); context.beginPath(); context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + clip.left, + clip.top, + Math.min(clip.right, context.canvas.width) - clip.left, + Math.min(clip.bottom, context.canvas.height) - clip.top, ); context.clip(); - paintDisplayList(painter, list, ratio, at); + paint(); context.restore(); + }; + + parts.forEach(({ tile, at, clip }) => { + const list = tiled + ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } + : tile.list; + + clipped(clip, () => paintDisplayList(painter, list, ratio, at)); }); // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds. if (text && textContext) - frame.tiles.forEach((tile) => { + parts.forEach(({ tile, at, clip }) => { textContext.reset(); paintDisplayList( textContext as unknown as CanvasRenderingContext2D, { ...tile.list, - width: frame.viewport.width - tile.x, - height: frame.viewport.height - tile.y, + width: frame.viewport.width + frame.behind.x - tile.x, + height: frame.viewport.height + frame.behind.y - tile.y, commands: tile.list.commands.filter((command) => command.op === "text"), }, ratio, - { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }, - ); - context.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.beginPath(); - context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + at, ); - context.clip(); - context.drawImage(text, 0, 0); - context.restore(); + clipped(clip, () => context.drawImage(text, 0, 0)); }); } +/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */ +function bands(panes: number, behind: number) { + return panes > 0 && behind > 0 + ? [ + { start: 0, end: panes, shift: 0 }, + { start: panes, end: Infinity, shift: behind }, + ] + : [{ start: 0, end: Infinity, shift: behind }]; +} + /** * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for * the frozen panes too, as every viewport has them, so the cells past them start just before its seam. @@ -208,9 +268,8 @@ function tiled( workbook: WorkbookHandle, viewport: SheetViewport, panes: { readonly width: number; readonly height: number }, - grid: GridMeta, split: number, -): Frame | undefined { +): Tile[] | undefined { const columns = segments(viewport.width, panes.width, split); const rows = segments(viewport.height, panes.height, split); const tiles: Tile[] = []; @@ -236,19 +295,11 @@ function tiled( }), ); - if (complete) { - const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); - - return { - list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, - tiles, - viewport, - }; - } + if (complete) return tiles; if (split >= maxSplit) return undefined; - return tiled(workbook, viewport, panes, grid, split + 1); + return tiled(workbook, viewport, panes, split + 1); } /** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */ diff --git a/apps/web/src/components/files/office/sheet-resize.browser.test.ts b/apps/web/src/components/files/office/sheet-resize.browser.test.ts index 6029e888e1c20..fc2c6845d7530 100644 --- a/apps/web/src/components/files/office/sheet-resize.browser.test.ts +++ b/apps/web/src/components/files/office/sheet-resize.browser.test.ts @@ -145,6 +145,69 @@ it.each([false, true])( }, ); +it.each([false, true])( + "draws text from cells scrolled out before the frame, frozen: %s", + async (frozen) => { + const archive = new JSZip(); + archive.file( + "xl/workbook.xml", + '', + ); + archive.file( + "xl/_rels/workbook.xml.rels", + '', + ); + archive.file( + "xl/styles.xml", + '', + ); + archive.file( + "xl/worksheets/sheet1.xml", + `${frozen ? '' : ""}${"M".repeat(60)}MMMM`, + ); + const bytes = await archive.generateAsync({ type: "arraybuffer" }); + const client = createWorkerClient( + new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" }), + ); + const inked = async ( + at: { x: number; y: number }, + area: { x: number; y: number; width: number; height: number }, + ) => { + const frame = await client.call("frame", { + sheet: 0, + ...at, + width: 400, + height: 300, + ratio: 1, + offset: { x: 0, y: 0 }, + wider: undefined, + }); + const canvas = new OffscreenCanvas(frame!.bitmap.width, frame!.bitmap.height); + const context = canvas.getContext("2d")!; + context.drawImage(frame!.bitmap, 0, 0); + frame!.bitmap.close(); + const pixels = context.getImageData(area.x, area.y, area.width, area.height).data; + return pixels.some( + (value, index) => index % 4 === 0 && value < 128 && pixels[index + 3]! > 0, + ); + }; + try { + await client.call("open", { + bytes, + view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } }, + }); + // B2's text overflows to the right well past B, and the merge centres C4's text far below row 4. + const panes = frozen ? { x: 64, y: 20 } : { x: 0, y: 0 }; + expect( + await inked({ x: 160, y: 0 }, { x: panes.x + 40, y: 20, width: 200, height: 20 }), + ).toBe(true); + expect(await inked({ x: 0, y: 200 }, { x: 128, y: 200, width: 64, height: 80 })).toBe(true); + } finally { + client.close(); + } + }, +); + it("requests current dimensions after resizing and scrolling away and back before a frame arrives", async () => { const archive = new JSZip(); archive.file( From c5095e7708922e4c036846be13b339e377c68dda Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 23 Nov 2026 03:07:22 -0300 Subject: [PATCH 027/288] fix(provider): leave MacPorts-owned agent updates to MacPorts (#25208) Co-authored-by: Yukun Shan <92423096+nateEc@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/maintenanceResolver.test.ts | 55 +++++++++++++++++++ .../src/server/maintenanceResolver.ts | 41 +++++++++----- 2 files changed, 82 insertions(+), 14 deletions(-) diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index dc5be98f3c52d..f392f4b546963 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -830,6 +830,61 @@ it.layer( isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"), }, }; + for (const fixture of [ + { name: "a launcher outside the prefix's bin", npm: false, alias: true, owner: "claude-code" }, + { name: "an unreadable registry", npm: true, alias: false, owner: null }, + { name: "files MacPorts does not own", npm: true, alias: false, owner: "" }, + ]) { + it.effect.skipIf(windowsHost)(`checks MacPorts ownership for ${fixture.name}`, () => + Effect.gen(function* () { + const prefix = yield* makeTempDir("t3-macports-owner"); + const port = NodePath.join(prefix, "bin", "port"); + writeExecutable(port); + const real = fixture.npm + ? NodePath.join(prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + : NodePath.join(prefix, "share", "claude-code", "claude"); + const resolved = fixture.alias + ? NodePath.join(prefix, ".local", "bin", "claude") + : NodePath.join(prefix, "bin", "claude"); + writeExecutable(real); + writeExecutable(resolved); + const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, { + binaryPath: resolved, + resolvedCommandPath: resolved, + realCommandPath: real, + env: { PATH: "" }, + platform: "darwin", + }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner( + (command, args) => { + expect(command).toBe(port); + expect(args).toEqual(["provides", resolved, real]); + return [resolved, real] + .map((file) => + fixture.owner + ? `${file} is provided by: ${fixture.owner}\n` + : `${file} is not provided by a MacPorts port.\n`, + ) + .join(""); + }, + () => (fixture.owner === null ? 1 : 0), + ), + ), + ); + if (fixture.owner === "") { + expect(capabilities.update?.lockKey).toBe(`npm-global:${normalizeCommandPath(prefix)}`); + } else { + expect(capabilities.update).toBeNull(); + expect(capabilities.manualCommand).toBe( + fixture.owner ? `sudo port upgrade ${fixture.owner}` : undefined, + ); + } + }), + ); + } const resolveInstall = (input: { readonly definition: PackageManagedProviderMaintenanceDefinition; readonly resolved: string; diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 0db49cd3abaee..583bb1e02111c 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -1182,9 +1182,10 @@ const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* ( }); /** - * The port that installed the executable, "" when MacPorts owns it under an unusable name, - * or null when it does not. MacPorts prefixes are root-owned and its Claude port disables - * `claude update`, so neither npm nor the native updater can upgrade these installs. + * The port that installed the launcher or its target, "" when MacPorts owns it under an + * unusable name or its registry cannot be read, or null when it does not. MacPorts prefixes + * are root-owned and its Claude port disables `claude update`, so neither npm nor the native + * updater can upgrade these installs. */ export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* ( context: ProviderMaintenanceResolutionContext, @@ -1192,17 +1193,29 @@ export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* if (context.platform === "win32") return null; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const siblingPort = path.join(path.dirname(context.resolvedCommandPath), "port"); - const portPath = (yield* fileSystem.exists(siblingPort).pipe(Effect.orElseSucceed(() => false))) - ? siblingPort - : yield* resolveCommandPath("port", { env: context.env }); - if (!portPath) return null; - const prefix = `${normalizeCommandPath(path.dirname(path.dirname(portPath)))}/`; - if (!normalizeCommandPath(context.realCommandPath).startsWith(prefix)) return null; - const output = yield* runProbe(portPath, ["provides", context.realCommandPath], context.env); - const name = output ? /\bis provided by: (\S+)/.exec(output)?.[1] : undefined; - if (name === undefined) return null; - return /^[\w.+-]+$/.test(name) ? name : ""; + const commandPaths = [...new Set([context.resolvedCommandPath, context.realCommandPath])]; + // A MacPorts prefix holds `bin/port`, so every prefix containing a command path is an ancestor. + const portPaths = new Set(); + for (const commandPath of commandPaths) { + for (let dir = path.dirname(commandPath); ; dir = path.dirname(dir)) { + portPaths.add(path.join(dir, "bin", "port")); + if (path.dirname(dir) === dir) break; + } + } + for (const portPath of portPaths) { + if (!(yield* fileSystem.exists(portPath).pipe(Effect.orElseSucceed(() => false)))) continue; + const prefix = `${normalizeCommandPath(path.dirname(path.dirname(portPath)))}/`; + const owned = commandPaths.filter((commandPath) => + normalizeCommandPath(commandPath).startsWith(prefix), + ); + if (owned.length === 0) continue; + const output = yield* runProbe(portPath, ["provides", ...owned], context.env); + // A failed registry lookup is no proof that the files are free to update. + if (output === null) return ""; + const name = /\bis provided by: (\S+)/.exec(output)?.[1]; + if (name !== undefined) return /^[\w.+-]+$/.test(name) ? name : ""; + } + return null; }); // Volta bin entries only identify its shim; the package image proves ownership. From 9c571f3c1a6f6364f05eab7d7723f5de76528620 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:10:46 -0800 Subject: [PATCH 028/288] fix(acp): sessions no longer keep a record of every turn they ran (#41256) Co-authored-by: Claude Opus 5.5 --- .../Adapters/AcpAdapterV2.test.ts | 2 ++ packages/provider-acp/src/server/adapter.ts | 15 ++------------- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 43db1b82b63a2..a62977eb17fb2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7293,6 +7293,8 @@ describe("AcpAdapterV2", () => { if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) break; } const snapshotBeforeRollback = yield* runtime.readThreadSnapshot({ providerThread }); + // Turns reach orchestration as events; the session keeps no record of them. + assert.deepEqual(snapshotBeforeRollback.providerTurns, []); const rolledBack = yield* runtime.rollbackThread({ providerThread: { ...providerThread, appThreadId: rollbackThreadId }, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8905317d20f5f..9fb64218c5b29 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2399,7 +2399,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const emitNativeResponseLifecycle = options.testHooks?.onNativeResponseLifecycle ?? (() => Effect.void); const nextElicitationOrdinal = yield* Ref.make(0); - const providerTurns = yield* Ref.make(new Map()); const snapshot = yield* Ref.make(emptySnapshotState()); const awaitRuntimeTeardown = Effect.fnUntraced(function* () { @@ -8006,7 +8005,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(promptRuntimeInstructions, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); - yield* Ref.set(providerTurns, new Map()); yield* Ref.set(snapshot, emptySnapshotState()); yield* continuationPermit.withPermit( Effect.gen(function* () { @@ -8718,11 +8716,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); - yield* Ref.update(providerTurns, (current) => { - const updated = new Map(current); - updated.set(String(turn.id), turn); - return updated; - }); yield* emitProviderEvent({ type: "provider_turn.updated", driver, @@ -9622,11 +9615,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); const runningTurn = providerTurnPayload(context, "running", null); - yield* Ref.update(providerTurns, (current) => { - const updated = new Map(current); - updated.set(String(runningTurn.id), runningTurn); - return updated; - }); yield* emitProviderEvent({ type: "provider_turn.updated", driver, @@ -10707,7 +10695,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [...(yield* Ref.get(providerTurns)).values()], + // Imports read only the transcript; turns reach orchestration as events. + providerTurns: [], messages, reasoningMessageIds: [...state.reasoningIds], runtimeRequests: [], From cbf4ea7ddc715414155d06588a9250529a4128fd Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 00:12:59 -0600 Subject: [PATCH 029/288] fix(web): shift-scroll and horizontal scrollers no longer navigate history (#41264) Co-authored-by: Cursor --- .../HistorySwipeNavigation.browser.test.tsx | 45 ++++++++++++++++++- .../src/components/HistorySwipeNavigation.tsx | 26 +++++++---- .../RightPanelTabs.browser.test.tsx | 4 +- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index d2a15729b0df2..d36efc1d535d7 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -24,7 +24,19 @@ describe("HistorySwipeNavigation", () => { false, ], ["scrolling left inside a scroller keeps the thread", "light", 100, -130, false], - ["swiping back at a shadow-root scroller's left edge navigates", "shadow", 0, -130, true], + ["scrolling at a shadow-root scroller's left edge keeps the thread", "shadow", 0, -130, false], + [ + "scrolling at a shadow-root scroller's right edge keeps the thread", + "shadow", + 800, + 130, + false, + ], + ["scrolling at a scroller's left edge keeps the thread", "light", 0, -130, false], + ["scrolling at a scroller's right edge keeps the thread", "light", 800, 130, false], + ["scrolling over a preview panel keeps the thread", "preview-panel", 0, -130, false], + ["scrolling over a desktop preview keeps the thread", "preview-viewport", 0, 130, false], + ["scrolling over a streamed preview keeps the thread", "server-browser", 0, -130, false], ["swiping back over a panel without overflow navigates", "none", 0, -130, true], ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { @@ -34,7 +46,10 @@ describe("HistorySwipeNavigation", () => { const panel = screen.container.appendChild(document.createElement("div")); const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; const viewport = root.appendChild(document.createElement("div")); - const noOverflow = scroller === "none" || scroller === "closed-dialog"; + const noOverflow = !scroller.startsWith("shadow") && scroller !== "light"; + if (scroller === "preview-panel") panel.setAttribute("data-preview-panel-mode", "inline"); + if (scroller === "preview-viewport") panel.setAttribute("data-preview-viewport", "tab"); + if (scroller === "server-browser") panel.setAttribute("data-server-browser-surface", "tab"); viewport.style.cssText = `width: 200px; overflow-x: ${noOverflow ? "visible" : "auto"}`; const content = viewport.appendChild(document.createElement("div")); content.style.cssText = `height: 20px; width: ${noOverflow ? 100 : 1000}px`; @@ -72,6 +87,32 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).not.toHaveBeenCalled(); }); + it.each([ + ["Shift-scroll keeps the thread", [[-130, true]]], + [ + "pressing Shift during a swipe cancels navigation", + [ + [-130, false], + [-1, true], + ], + ], + [ + "releasing Shift during a scroll keeps the thread", + [ + [-1, true], + [-130, false], + ], + ], + ] as const)("%s", async (_name, events) => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await render(); + for (const [deltaX, shiftKey] of [...events, [0, false] as const]) { + screen.container.dispatchEvent(new WheelEvent("wheel", { deltaX, shiftKey, bubbles: true })); + } + expect(navigateHistory).not.toHaveBeenCalled(); + }); + // A vertical scroll 15° off vertical. const drift = Array.from({ length: 30 }, () => [-4, 15] as const); it.each([ diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 2924f82cd3136..09b363c2d1f7e 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -44,16 +44,12 @@ function readMainContentBounds(): SwipeBounds { } // `event.target` stops at a shadow host; the composed path also reaches scrollers inside it. -function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean { +function hasHorizontalScroller(path: readonly EventTarget[]): boolean { for (const element of path) { if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue; const { overflowX } = getComputedStyle(element); if (overflowX !== "auto" && overflowX !== "scroll") continue; - const canScroll = - deltaX < 0 - ? element.scrollLeft > 0 - : element.scrollLeft + element.clientWidth < element.scrollWidth - 1; - if (canScroll) return true; + return true; } return false; } @@ -71,10 +67,19 @@ function lockSwipeAxis( if (Math.abs(sumX) <= Math.abs(sumY) || isVerticalScroll(Math.abs(sumX), Math.abs(sumY))) { return { kind: "ignored" }; } - if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { + // Preview contents can scroll in another document or on the server, outside this DOM. + if ( + path.some( + (node) => + node instanceof Element && + node.matches( + '[role="dialog"], [data-preview-panel-mode], [data-preview-viewport], [data-server-browser-surface]', + ), + ) + ) { return { kind: "ignored" }; } - if (canScrollHorizontally(path, sumX)) return { kind: "ignored" }; + if (hasHorizontalScroller(path)) return { kind: "ignored" }; const direction = sumX < 0 ? "back" : "forward"; if (!canNavigateHistory(direction)) return { kind: "ignored" }; return { @@ -134,6 +139,11 @@ export function HistorySwipeNavigation() { gesture = null; }); const onWheel = (event: WheelEvent) => { + if (event.shiftKey) { + if (gesture?.kind === "tracking") hideIndicator(); + gesture = { kind: "ignored" }; + return; + } if (gesture === null) { gesture = event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 515d5cdbfb32b..347971993c7c3 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -68,7 +68,7 @@ const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ( })); describe("RightPanelTabs", () => { - it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => { + it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => { navigateHistory.mockReset(); const { bridge, scroll } = trackpad(); using _bridge = stubGlobal("desktopBridge", bridge); @@ -139,7 +139,7 @@ describe("RightPanelTabs", () => { viewport.scrollLeft = 0; scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); - expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back"); + expect(navigateHistory).not.toHaveBeenCalled(); }); }); From 597c8de32b2692cf18caa9ee50748e42acc7b1d3 Mon Sep 17 00:00:00 2001 From: Jui-Chen Chien Date: Mon, 23 Nov 2026 14:14:16 +0800 Subject: [PATCH 030/288] fix(web): hidden preview tabs larger than the window capture whole (#26965) Co-authored-by: jason chien <3936511+jason5545@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/browser/HostedBrowserWebview.tsx | 22 +++++++-------- .../src/browser/browserViewportLayout.test.ts | 27 +++++++++++++++++++ apps/web/src/browser/browserViewportLayout.ts | 24 +++++++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index b20d737095116..766f94b597903 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -13,6 +13,7 @@ import { } from "~/components/preview/thumbButtons"; import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; +import { useViewportSize } from "~/hooks/useViewportSize"; import { cn, isMacPlatform } from "~/lib/utils"; import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore"; @@ -22,6 +23,7 @@ import { resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar"; import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles"; @@ -243,18 +245,14 @@ export function HostedBrowserWebview(props: { setAspectRatioLocked(aspectRatio !== null); }; const content = presentation.content; - const hiddenWidth = - viewport._tag !== "fill" - ? viewport.width * layoutZoomFactor - : content - ? content.width / content.scale - : (lastRect?.width ?? 1280); - const hiddenHeight = - viewport._tag !== "fill" - ? viewport.height * layoutZoomFactor - : content - ? content.height / content.scale - : (lastRect?.height ?? 800); + const windowSize = useViewportSize(); + const { width: hiddenWidth, height: hiddenHeight } = resolveHiddenBrowserViewportSize({ + setting: viewport, + zoomFactor: layoutZoomFactor, + content, + lastRect, + windowSize, + }); // Build from primitives on each side of the resize hook to keep both objects cached. const containerSize = active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight }; diff --git a/apps/web/src/browser/browserViewportLayout.test.ts b/apps/web/src/browser/browserViewportLayout.test.ts index c72f68e1e20da..54a6258edb97a 100644 --- a/apps/web/src/browser/browserViewportLayout.test.ts +++ b/apps/web/src/browser/browserViewportLayout.test.ts @@ -2,8 +2,10 @@ import { describe, expect, it } from "vite-plus/test"; import { resizeBrowserViewportFromRail, + resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; describe("resolveBrowserViewportLayout", () => { @@ -43,6 +45,31 @@ describe("resolveBrowserViewportLayout", () => { ), ).toEqual({ width: 460, height: 409 }); }); + + it("fits a hidden fixed viewport larger than the window inside the window", () => { + const setting = { _tag: "freeform", width: 1440, height: 1700 } as const; + const windowSize = { width: 1400, height: 1000 }; + const hidden = resolveHiddenBrowserViewportSize({ + setting, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }); + expect(hidden).toEqual({ width: 1400, height: 1000 }); + const layout = resolveBrowserViewportLayout(hidden, setting); + expect(layout.viewportHeight).toBeLessThanOrEqual(windowSize.height); + expect(layout.viewportScale).toBeCloseTo(1000 / 1700); + expect( + resolveHiddenBrowserViewportSize({ + setting: { _tag: "freeform", width: 1280, height: 800 }, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }), + ).toEqual({ width: 1280, height: 800 }); + }); }); describe("resolveBrowserViewportTransform", () => { diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index 7fe6b170c671d..4b1fc5e41b08e 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -71,6 +71,30 @@ export function resolveFittedBrowserViewport( return { _tag: "freeform", width: 1280, height: 800 }; } +export function resolveHiddenBrowserViewportSize(input: { + readonly setting: PreviewViewportSetting; + readonly zoomFactor: number; + readonly content: { + readonly width: number; + readonly height: number; + readonly scale: number; + } | null; + readonly lastRect: { readonly width: number; readonly height: number } | null; + readonly windowSize: { readonly width: number; readonly height: number }; +}): { readonly width: number; readonly height: number } { + const { content, lastRect, setting, windowSize, zoomFactor } = input; + if (setting._tag !== "fill") { + // Chromium paints a guest only near the window, so a capture of a larger one loses its far edge. + return { + width: Math.min(windowSize.width, setting.width * zoomFactor), + height: Math.min(windowSize.height, setting.height * zoomFactor), + }; + } + if (content) + return { width: content.width / content.scale, height: content.height / content.scale }; + return { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 }; +} + export function resolveBrowserDeviceViewportArea(container: { readonly width: number; readonly height: number; From 5812320a6a6714ef05ada591ffbafc4580d5ee8e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:21:51 -0800 Subject: [PATCH 031/288] fix(web): quick clicks on different sidebar threads open each one (#41258) --- .../src/components/Sidebar.browser.test.tsx | 51 +++++++++++++++++++ apps/web/src/components/Sidebar.tsx | 3 +- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1a0b4c588d64c..1fb930f55fabc 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -329,6 +329,57 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread click", () => { + // regression: #40715 macOS counts quick clicks on different rows, so the next row got detail 2 and was ignored + it("opens another thread when the click arrives with a double-click count", async () => { + const activeProject = project("active"); + const threads = [threadShell(activeProject.id, 0), threadShell(activeProject.id, 1)]; + const routeThreadRef: ScopedThreadRef = { + environmentId: activeProject.environmentId, + threadId: threads[0]!.id, + }; + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef, + }); + await using screen = await render( + + + , + { router: "/local/thread-0" }, + ); + const navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + const openRow = screen.getByText("Thread 0").first().element(); + await act(() => { + openRow.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }), + ); + }); + expect(navigate).not.toHaveBeenCalled(); + + const row = screen.getByText("Thread 1").first().element(); + await act(() => { + row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 })); + }); + + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ params: expect.objectContaining({ threadId: "thread-1" }) }), + ); + }); +}); + describe("sidebar thread menu", () => { it("tells the menu whether the keyboard opened it", async () => { const activeProject = project("active"); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e9d45a5c1fd84..2a8dcdff50d86 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1612,7 +1612,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve rangeSelectTo(threadKey, orderedThreadKeysRef.current); return; } - if (isTrailingDoubleClick(event.detail)) { + // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. + if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { return; } navigateToThread(threadRef); From ba588ef663edb350aa333f9ce008b3bd7cbcfe3d Mon Sep 17 00:00:00 2001 From: Yukun Shan <92423096+nateEc@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:22:35 +0800 Subject: [PATCH 032/288] fix(web): match macOS Option shortcuts to the active keyboard layout (#24034) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../settings/KeybindingsSettings.logic.ts | 7 +- apps/web/src/keybindings.test.ts | 71 ++++++++++++++++ apps/web/src/keybindings.ts | 24 +++++- apps/web/src/keyboardLayout.test.ts | 81 +++++++++++++++++++ apps/web/src/keyboardLayout.ts | 44 ++++++++++ apps/web/src/main.tsx | 4 + packages/shared/src/keybindingMatching.ts | 21 ++++- packages/shared/src/keybindings.ts | 1 + 8 files changed, 246 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/keyboardLayout.test.ts create mode 100644 apps/web/src/keyboardLayout.ts diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 55d4278b0fe16..9d03b7ab72e48 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -557,8 +557,9 @@ function titleCaseCommandSegment(segment: string): string { function recordedLayoutShortcutKey( event: Pick, + platform: string, ): string { - const physicalKey = shortcutKeyFromEvent(event); + const physicalKey = shortcutKeyFromEvent(event, platform); const layoutKey = event.key.toLowerCase(); if (event.altKey || layoutKey.length !== 1) return physicalKey; // Normalize only US shifted glyphs at their US position. Other layouts can @@ -605,7 +606,9 @@ export function keybindingFromKeyboardEvent( }, ): string | null { const keyToken = normalizeShortcutKeyToken( - options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event), + options?.layoutCharacter + ? recordedLayoutShortcutKey(event, platform) + : shortcutKeyFromEvent(event, platform), ); if (!keyToken) return null; diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..84463efc3abfd 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -758,6 +758,77 @@ describe("resolveShortcutCommand", () => { ); }); + it("matches Option symbols against the active Latin layout rather than the US position", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true, shiftKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true, shiftKey: true }), command: "sidebar.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true, shiftKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }, + ), + "appearance.cycle", + ); + }); + + it("preserves physical punctuation alongside an Option-modified mapped letter", () => { + for (const key of [";", "m"]) { + const keybindings = compile([ + { shortcut: modShortcut(key, { altKey: true }), command: "diff.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "µ", code: "Semicolon", metaKey: true, altKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["Semicolon", "m"]]) }, + ), + "diff.toggle", + ); + } + }); + + it("keeps Latin event keys and unsupported layout fallbacks", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true }), command: "sidebar.toggle" }, + ]); + const options = { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }; + assert.strictEqual( + resolveShortcutCommand( + event({ key: "q", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + options, + ), + "sidebar.toggle", + ); + for (const keyboardLayoutMap of [new Map(), new Map([["KeyQ", "й"]])]) { + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + { ...options, keyboardLayoutMap }, + ), + "sidebar.toggle", + ); + } + assert.strictEqual( + resolveShortcutCommand( + event({ + key: "Æ", + code: "KeyQ", + ctrlKey: true, + altKey: true, + getModifierState: () => true, + }), + keybindings, + { ...options, platform: "Win32" }, + ), + null, + ); + }); + it("matches non-Latin layout letters using the physical key code", () => { const keybindings = compile([{ shortcut: modShortcut("d"), command: "diff.toggle" }]); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index f05067a2e53bc..117847faa95bb 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -17,13 +17,24 @@ import { resolveEventKeys, type ShortcutEventLike as SharedShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, + shortcutKeyFromEvent as sharedShortcutKeyFromEvent, } from "@t3tools/shared/keybindings"; import { isElectron } from "./env"; import { isEditableFocused } from "./lib/editableFocus"; import { projectScriptIdFromCommand } from "./projectScripts"; +import { getKeyboardLayoutMap } from "./keyboardLayout"; export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings"; -export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings"; +export function shortcutKeyFromEvent( + event: Pick, + platform: string, +) { + return sharedShortcutKeyFromEvent( + event, + isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined, + ); +} export interface ShortcutEventLike extends SharedShortcutEventLike { target?: EventTarget | null; @@ -42,6 +53,7 @@ export interface ShortcutMatchContext { interface ShortcutMatchOptions { platform?: string; + keyboardLayoutMap?: ShortcutKeyboardLayoutMap; context?: Partial; } @@ -194,7 +206,15 @@ export function resolveShortcutCommand( const binding = keybindings[index]; if (!binding) continue; if (!matchesWhenClause(binding.whenAst, context)) continue; - if (!matchesKeybindingShortcut(event, shortcutForContext(binding, context), platform)) continue; + if ( + !matchesKeybindingShortcut( + event, + shortcutForContext(binding, context), + platform, + options?.keyboardLayoutMap ?? getKeyboardLayoutMap(), + ) + ) + continue; return binding.command; } return null; diff --git a/apps/web/src/keyboardLayout.test.ts b/apps/web/src/keyboardLayout.test.ts new file mode 100644 index 0000000000000..b33ef3218041d --- /dev/null +++ b/apps/web/src/keyboardLayout.test.ts @@ -0,0 +1,81 @@ +import { afterEach, assert, it } from "vite-plus/test"; +import { getKeyboardLayoutMap, trackKeyboardLayout } from "./keyboardLayout"; +import { keybindingFromKeyboardEvent } from "./components/settings/KeybindingsSettings.logic"; + +let stop: (() => void) | undefined; +afterEach(() => stop?.()); + +function pendingLayout() { + let resolve!: (layout: Map) => void; + const promise = new Promise>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +it.each([true, false])( + "records Option symbols and refreshes the current layout (keyboard events: %s)", + async (supportsEvents) => { + let layout = Promise.resolve(new Map([["KeyQ", "a"]])); + const keyboard = Object.assign(supportsEvents ? new EventTarget() : {}, { + getLayoutMap: () => layout, + }); + const focusTarget = new EventTarget(); + stop = trackKeyboardLayout(keyboard, focusTarget); + await keyboard.getLayoutMap(); + const event = { + key: "Æ", + code: "KeyQ", + metaKey: true, + ctrlKey: false, + altKey: true, + shiftKey: true, + }; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + assert.strictEqual( + keybindingFromKeyboardEvent(event, "MacIntel", { layoutCharacter: true }), + "mod+alt+shift+a", + ); + const pending = pendingLayout(); + layout = pending.promise; + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + pending.resolve(new Map([["KeyQ", "q"]])); + await layout; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+q"); + layout = Promise.reject(new Error("Permission denied")); + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); + await layout.catch(() => undefined); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + layout = Promise.resolve(new Map([["KeyQ", "a"]])); + stop(); + focusTarget.dispatchEvent(new Event("focus")); + await keyboard.getLayoutMap(); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + }, +); + +it("ignores an obsolete layout result", async () => { + const pending = pendingLayout(); + let result = pending.promise; + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => result }); + stop = trackKeyboardLayout(keyboard); + result = Promise.resolve(new Map([["KeyQ", "q"]])); + keyboard.dispatchEvent(new Event("layoutchange")); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + await result; + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); +}); + +it("does not publish a pending result after disposal", async () => { + const pending = pendingLayout(); + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => pending.promise }); + stop = trackKeyboardLayout(keyboard); + stop(); + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap(), undefined); +}); diff --git a/apps/web/src/keyboardLayout.ts b/apps/web/src/keyboardLayout.ts new file mode 100644 index 0000000000000..61fd6e24a1b57 --- /dev/null +++ b/apps/web/src/keyboardLayout.ts @@ -0,0 +1,44 @@ +import type { ShortcutKeyboardLayoutMap } from "@t3tools/shared/keybindings"; + +interface KeyboardLayoutSource extends Partial< + Pick +> { + getLayoutMap(): Promise; +} + +let keyboardLayoutMap: ShortcutKeyboardLayoutMap | undefined; + +export function getKeyboardLayoutMap() { + return keyboardLayoutMap; +} + +// Option changes event.key to a symbol on macOS; the layout map recovers the +// letter printed on that key without assuming a US physical layout. +export function trackKeyboardLayout( + keyboard = (navigator as Navigator & { keyboard?: KeyboardLayoutSource }).keyboard, + focusTarget: EventTarget | undefined = typeof window === "undefined" ? undefined : window, +) { + let revision = 0; + const refresh = async (clearMap: boolean) => { + const request = ++revision; + if (clearMap) keyboardLayoutMap = undefined; + try { + const layout = await keyboard?.getLayoutMap(); + if (request === revision) keyboardLayoutMap = layout; + } catch { + // Unsupported or permission-blocked browsers keep the existing fallback. + if (request === revision) keyboardLayoutMap = undefined; + } + }; + const onLayoutChange = () => void refresh(true); + const onFocus = () => void refresh(false); + void refresh(true); + keyboard?.addEventListener?.("layoutchange", onLayoutChange); + focusTarget?.addEventListener("focus", onFocus); + return () => { + revision++; + keyboardLayoutMap = undefined; + keyboard?.removeEventListener?.("layoutchange", onLayoutChange); + focusTarget?.removeEventListener("focus", onFocus); + }; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 51aeeade6863d..2640ca1e167d0 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -4,6 +4,7 @@ import ReactDOM from "react-dom/client"; import "@fontsource-variable/inter"; import "./index.css"; +import { trackKeyboardLayout } from "./keyboardLayout"; import { hasCloudPublicConfig } from "./cloud/publicConfig"; import { isElectron } from "./env"; import { startAppServices } from "./appInit"; @@ -11,6 +12,9 @@ import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; import { chunkLoadState } from "./lib/chunkReloadGuard"; +const stopTrackingKeyboardLayout = trackKeyboardLayout(); +import.meta.hot?.dispose(stopTrackingKeyboardLayout); + const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; diff --git a/packages/shared/src/keybindingMatching.ts b/packages/shared/src/keybindingMatching.ts index 75e6786cd1429..f02e5d47e2aa2 100644 --- a/packages/shared/src/keybindingMatching.ts +++ b/packages/shared/src/keybindingMatching.ts @@ -82,11 +82,16 @@ export function normalizeEventKey(key: string): string { return normalized; } +export type ShortcutKeyboardLayoutMap = Pick, "get">; + export function shortcutKeyFromEvent( event: Pick, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, ): string { const layoutKey = normalizeEventKey(event.key); if (/^[a-z]$/.test(layoutKey)) return layoutKey; + const mappedKey = event.code ? keyboardLayoutMap?.get(event.code)?.toLowerCase() : undefined; + if (mappedKey && /^[a-z]$/.test(mappedKey)) return mappedKey; // Only the US layout's glyph at its own key: other layouts and AltGr keep their character. const usOptionLetter = event.altKey ? US_MAC_OPTION_GLYPH_LETTERS.get(event.key) : undefined; if (usOptionLetter && event.code === `Key${usOptionLetter.toUpperCase()}`) return usOptionLetter; @@ -97,13 +102,19 @@ export function shortcutKeyFromEvent( return physicalKey ?? layoutKey; } -export function resolveEventKeys(event: ShortcutEventLike): Set { +export function resolveEventKeys( + event: ShortcutEventLike, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, +): Set { const layoutKey = normalizeEventKey(event.key); const keys = new Set([layoutKey]); const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1]; - if (letterCode && !/^[a-z]$/.test(layoutKey)) { + const shortcutKey = shortcutKeyFromEvent(event, keyboardLayoutMap); + if (letterCode && !/^[a-z]$/.test(shortcutKey)) { keys.add(letterCode.toLowerCase()); } + keys.add(shortcutKey); + // Layout letters supplement, rather than replace, physical punctuation shortcuts. keys.add(shortcutKeyFromEvent(event)); return keys; } @@ -128,6 +139,7 @@ export function matchesKeybindingShortcut( event: ShortcutEventLike, shortcut: KeybindingShortcut, platform: string, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, ): boolean { if ( !isMacPlatform(platform) && @@ -136,5 +148,8 @@ export function matchesKeybindingShortcut( ) return false; if (!matchesKeybindingShortcutModifiers(event, shortcut, platform)) return false; - return resolveEventKeys(event).has(shortcut.key); + return resolveEventKeys( + event, + isMacPlatform(platform) && event.altKey ? keyboardLayoutMap : undefined, + ).has(shortcut.key); } diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 29bb71d5f6f1a..3d9fcc0727d3d 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -20,6 +20,7 @@ export { shortcutKeyFromEvent, type ShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, } from "./keybindingMatching.ts"; export const US_SHIFTED_TO_UNSHIFTED_KEYS: ReadonlyMap = new Map([ From 52b9b77e3fd74bba9d2d9199517e65c40aa0672c Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 00:28:54 -0600 Subject: [PATCH 033/288] fix(server): let the CLI answer workflow questions by their exact name (#41260) Co-authored-by: Julius Marminge --- apps/server/src/mcp/toolkits/workflow/tools.test.ts | 10 ++++++++++ apps/server/src/mcp/toolkits/workflow/tools.ts | 9 ++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/toolkits/workflow/tools.test.ts diff --git a/apps/server/src/mcp/toolkits/workflow/tools.test.ts b/apps/server/src/mcp/toolkits/workflow/tools.test.ts new file mode 100644 index 0000000000000..996802992338f --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/tools.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { WorkflowToolkit } from "./tools.ts"; + +it("signal keeps a wait's exact name", () => { + const decode = Schema.decodeUnknownSync(WorkflowToolkit.tools.t3_workflow.parametersSchema); + expect(decode({ action: "signal", runId: "run-1", wait: "review " }).wait).toBe("review "); + expect(() => decode({ action: "signal", runId: "run-1", wait: " " })).toThrow(); +}); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts index fa01dfb7c5712..70289badab205 100644 --- a/apps/server/src/mcp/toolkits/workflow/tools.ts +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -29,7 +29,14 @@ const WorkflowTool = Tool.make("t3_workflow", { idempotencyKey: Schema.optional(TrimmedNonEmptyString), runId: Schema.optional(TrimmedNonEmptyString), status: Schema.optional(WorkflowRunStatus), - wait: Schema.optional(TrimmedNonEmptyString), + // Waits match by exact name, so a name keeps its spaces. + wait: Schema.optional( + Schema.String.check( + Schema.makeFilter((name: string) => name.trim().length > 0, { + expected: "a non-blank string", + }), + ), + ), key: Schema.optional(TrimmedNonEmptyString), channel: Schema.optional(TrimmedNonEmptyString), value: Schema.optional(Schema.Json), From 10765a4e47a208a04b94055dd71967a2921f4ac7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:29:33 -0800 Subject: [PATCH 034/288] fix(web): a refused desktop install shows as failed instead of downloaded (#41262) --- .../components/desktopUpdate.logic.test.ts | 56 +++++++++++++++++++ .../web/src/components/desktopUpdate.logic.ts | 39 ++++++++++++- .../components/settings/SettingsPanels.tsx | 16 +++++- .../components/sidebar/SidebarUpdatePill.tsx | 3 +- 4 files changed, 110 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.ts index 29494789b6cff..601527e51a201 100644 --- a/apps/web/src/components/desktopUpdate.logic.test.ts +++ b/apps/web/src/components/desktopUpdate.logic.test.ts @@ -5,7 +5,9 @@ import { canCheckForUpdate, getDesktopUpdateButtonTooltip, getDesktopUpdateReleaseHistoryUrl, + getDesktopUpdateActionError, getDesktopUpdateReleaseUrl, + installDesktopUpdate, resolveDesktopUpdateButtonAction, } from "./desktopUpdate.logic"; @@ -58,6 +60,60 @@ describe("desktop update button state", () => { ); }); + it("shows the install failure after the desktop returns to downloaded", () => { + // reduceDesktopUpdateStateOnInstallFailure: a refused macOS install prompt lands here. + const state: DesktopUpdateState = { + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + message: "Desktop updater install operation reported an error.", + errorContext: "install", + canRetry: true, + }; + expect(resolveDesktopUpdateButtonAction(state)).toBe("install"); + expect(getDesktopUpdateButtonTooltip(state)).toBe("Install failed for 1.1.0. Click to retry."); + }); + + it("reports an install the desktop refuses after accepting it", async () => { + const downloaded: DesktopUpdateState = { + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + }; + const failed: DesktopUpdateState = { + ...downloaded, + message: "OSStatus error -60006.", + errorContext: "install", + canRetry: true, + }; + const listeners = new Set<(state: DesktopUpdateState) => void>(); + const emit = (state: DesktopUpdateState) => listeners.forEach((listener) => listener(state)); + const install = installDesktopUpdate({ + onUpdateState: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + installUpdate: async () => { + // A retry's pre-install check can restore the previous failure before the restart starts. + emit(failed); + return { accepted: true, completed: false, state: downloaded }; + }, + }); + let settled = false; + void install.then(() => { + settled = true; + }); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + emit(failed); + const result = await install; + expect(getDesktopUpdateActionError(result)).toBe("OSStatus error -60006."); + expect(listeners.size).toBe(0); + }); + it("never calls a build on the other track up to date", () => { // A Stable build whose switch to Nightly did not finish; the updater discards every release. const state: DesktopUpdateState = { diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index d3d4f618c8268..4922ee3b524b7 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -1,5 +1,9 @@ import { desktopTrackMismatchText } from "@t3tools/client-runtime/state/server"; -import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts"; +import type { + DesktopBridge, + DesktopUpdateActionResult, + DesktopUpdateState, +} from "@t3tools/contracts"; import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { msg } from "gt-react"; @@ -142,6 +146,11 @@ export function getDesktopUpdateButtonTooltip( : resolve(msg("Downloading update")); } if (state.status === "downloaded") { + if (state.errorContext === "install" && state.downloadedVersion) { + return resolve( + msg("Install failed for {version}. Click to retry.", { version: state.downloadedVersion }), + ); + } const version = state.downloadedVersion ?? state.availableVersion; return version === null ? resolve(msg("Update ready downloaded. Click to restart and install.")) @@ -212,6 +221,34 @@ export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): return message.length > 0 ? message : null; } +/** + * macOS can refuse the restart after installUpdate resolves; the desktop then reports it as a + * later state with errorContext "install". Success quits the app, so this never resolves then. + */ +export async function installDesktopUpdate( + bridge: Pick, + expectedVersion?: string, +): Promise { + let awaitingFailure = false; + let reportFailure: (state: DesktopUpdateState) => void = () => {}; + const failure = new Promise((resolve) => { + reportFailure = resolve; + }); + const unsubscribe = bridge.onUpdateState((state) => { + if (awaitingFailure && state.errorContext === "install") reportFailure(state); + }); + try { + const result = await bridge.installUpdate(expectedVersion); + if (!result.accepted || result.completed || getDesktopUpdateActionError(result) !== null) { + return result; + } + awaitingFailure = true; + return { ...result, state: await failure }; + } finally { + unsubscribe(); + } +} + export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean { return getDesktopUpdateActionError(result) !== null; } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 493d8a1e79565..97b278a463e9e 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -42,9 +42,11 @@ import { CliCommandSettingsRow } from "./CliCommandSettingsRow"; import { MobileAppSettingsRow } from "./MobileAppSettingsRow"; import { canCheckForUpdate, + getDesktopUpdateActionError, getDesktopUpdateButtonTooltip, getDesktopUpdateDisabledReason, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, } from "../../components/desktopUpdate.logic"; @@ -255,8 +257,18 @@ function AboutVersionSection() { setIsUpdateActionPending(false); return; } - void bridge - .installUpdate() + void installDesktopUpdate(bridge) + .then((result) => { + const actionError = getDesktopUpdateActionError(result); + if (!actionError) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not install update"), + description: actionError, + }), + ); + }) .catch((error: unknown) => { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index 71fce36f3ed43..156e89364670c 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -22,6 +22,7 @@ import { getDesktopUpdateDownloadedVersion, getDesktopUpdateIdleTooltip, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, shouldShowArm64IntelBuildWarning, @@ -176,7 +177,7 @@ export async function installLocalUpdate( expectedVersion?: string, ): Promise { try { - const result = await bridge.installUpdate(expectedVersion); + const result = await installDesktopUpdate(bridge, expectedVersion); if (!result.accepted) { showDesktopUpdateDownloadedToast(bridge, result.state); return false; From 21b52875ea5621174638436b6074edfe2fd10590 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:31:07 -0800 Subject: [PATCH 035/288] refactor(server): adapter snapshots stop carrying provider turns nothing reads (#41276) Co-authored-by: Claude Opus 5.5 --- .../Adapters/AcpAdapterV2.test.ts | 8 +- .../Adapters/ClaudeAdapterV2.ts | 2 - .../Adapters/CodexAdapterV2.ts | 3 - .../Adapters/OpenCode2AdapterV2.test.ts | 35 +-- packages/provider-acp/src/server/adapter.ts | 2 - .../src/server/ProviderAdapter.ts | 1 - .../provider-cursor/src/server/adapter.ts | 3 - packages/provider-muse/src/server/adapter.ts | 1 - .../src/server/adapter.test.ts | 245 ++++++++---------- .../provider-opencode/src/server/adapter.ts | 1 - .../src/server/v2/adapter.ts | 37 +-- packages/provider-pi/src/server/adapter.ts | 3 +- 12 files changed, 126 insertions(+), 215 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index a62977eb17fb2..105565f79ef2f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7292,13 +7292,9 @@ describe("AcpAdapterV2", () => { const event = yield* Queue.take(events); if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) break; } - const snapshotBeforeRollback = yield* runtime.readThreadSnapshot({ providerThread }); - // Turns reach orchestration as events; the session keeps no record of them. - assert.deepEqual(snapshotBeforeRollback.providerTurns, []); - const rolledBack = yield* runtime.rollbackThread({ providerThread: { ...providerThread, appThreadId: rollbackThreadId }, - providerThreadTurns: snapshotBeforeRollback.providerTurns, + providerThreadTurns: [], target: { type: "thread_start", checkpointId: CheckpointId.make("checkpoint-acp-rollback-session"), @@ -7306,7 +7302,6 @@ describe("AcpAdapterV2", () => { }, }); assert.isString(rolledBack.providerThread.nativeThreadRef?.nativeId); - assert.deepEqual(rolledBack.providerTurns, []); assert.equal( runtimeInputs[1]?.processEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer rollback-target-token", @@ -7330,7 +7325,6 @@ describe("AcpAdapterV2", () => { const snapshotAfterRollback = yield* runtime.readThreadSnapshot({ providerThread: rolledBack.providerThread, }); - assert.deepEqual(snapshotAfterRollback.providerTurns, []); assert.deepEqual(snapshotAfterRollback.messages, []); const sessionEventsBeforeSecondTurn = sessionEventCount; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c93b840f44e4d..d3c017a54679a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -15145,7 +15145,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), handoffIds: rollbackInput.providerThread.handoffIds, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -15167,7 +15166,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( lastRunOrdinal: rollbackInput.target.appRunOrdinal, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1c38aaebffc80..a35767f62eecf 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -9179,7 +9179,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, @@ -9212,7 +9211,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef, status: "idle" as const, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -9255,7 +9253,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( status: "idle" as const, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 0e4bc5d088048..91a00fd60742f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -6873,7 +6873,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect("drops the turns a rollback cut from the snapshot it returns", () => + it.effect("reverts OpenCode at the prompt of the first turn a rollback cuts", () => Effect.gen(function* () { const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`; const dropped = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter:2`; @@ -6925,7 +6925,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(secondTurn(thread)); yield* Deferred.await(bothEnded); const [first, second] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -6935,10 +6935,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, second!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); @@ -6994,10 +6990,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ); it.effect.each([ - [ - "keeps the recorded turns before the target when rolling back a session not loaded yet", - false, - ], + ["reverts a session not loaded yet at the first recorded turn after the target", false], ] as const)("%s", ([, running]) => Effect.gen(function* () { const first = `msg_t3_turn_${SESSION}:attempt:first`; @@ -7069,10 +7062,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ); } else { assert.isTrue(Exit.isSuccess(rollback)); - assert.deepEqual( - Exit.isSuccess(rollback) ? rollback.value.providerTurns.map((turn) => turn.id) : [], - [kept.id], - ); } }), ); @@ -7360,7 +7349,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ], "msg_external", ); - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -7370,10 +7359,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first, second], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first.id], - ); }), ); @@ -7872,7 +7857,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(continuationTurn(thread, offers[1]!)); yield* Deferred.await(bothEnded); const [first, continuation] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -7882,10 +7867,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, continuation!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); @@ -7994,7 +7975,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(continuationTurn(thread, yield* Deferred.await(offered))); yield* Deferred.await(bothEnded); const [first, continuation] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -8004,10 +7985,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, continuation!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 9fb64218c5b29..d9410e4754f35 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10696,7 +10696,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updatedAt: now, }, // Imports read only the transcript; turns reach orchestration as events. - providerTurns: [], messages, reasoningMessageIds: [...state.reasoningIds], runtimeRequests: [], @@ -10755,7 +10754,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 049198f9a6cb4..4d008a7233900 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -648,7 +648,6 @@ export interface ProviderAdapterV2RuntimeRequestResponseInput { export interface ProviderAdapterV2ThreadSnapshot { readonly providerThread: OrchestrationV2ProviderThread; - readonly providerTurns: ReadonlyArray; readonly messages: ReadonlyArray; /** Ids in `messages` that hold the agent's reasoning, not its reply. */ readonly reasoningMessageIds?: ReadonlyArray; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 426bc8b60a264..c758e46a7b3dc 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -3548,7 +3548,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: projectedMessages, runtimeRequests: [], providerPayload: { @@ -3629,7 +3628,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -3659,7 +3657,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 66c1fd1a505ff..825e793876571 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2245,7 +2245,6 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const now = yield* DateTime.now; return { providerThread: current, - providerTurns: [], messages: items.flatMap((item): OrchestrationV2ConversationMessage[] => item.kind === "agentMessage" || item.kind === "userMessage" ? [ diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 3cd83ac152f8c..5e0b34c029111 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -151,6 +151,41 @@ function providerTurn(input: { }; } +// Turns reach orchestration only as `provider_turn.updated` events, so tests read them there. +function trackProviderTurns( + runtime: Pick, +) { + const turns = new Map(); + const events = runtime.events.pipe( + Stream.tap((event) => + Effect.sync(() => { + if (event.type === "provider_turn.updated") { + turns.set(event.providerTurn.id, event.providerTurn); + } + }), + ), + ); + const awaitTurns = Effect.fnUntraced(function* ( + predicate: (turns: ReadonlyArray) => boolean, + ) { + const seen = () => [...turns.values()]; + if (!predicate(seen())) { + yield* events.pipe( + Stream.takeUntil(() => predicate(seen())), + Stream.runDrain, + ); + } + return seen(); + }); + const awaitLatestTurn = ( + predicate: (turn: OrchestrationV2ProviderTurn) => boolean = () => true, + ) => + awaitTurns((seen) => seen.length > 0 && predicate(seen.at(-1)!)).pipe( + Effect.map((seen) => seen.at(-1)!), + ); + return { events, awaitTurns, awaitLatestTurn }; +} + const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(function* ( suffix: string, nativeSessionId: string, @@ -260,6 +295,7 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct runtimePolicy: turnPolicy, }); return { + ...trackProviderTurns(runtime), nativeSessionId, now, policy, @@ -466,7 +502,7 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => nativeEvents.push({ type: "session.idle", properties: { sessionID: sessionId } }), ); - yield* harness.runtime.events.pipe( + yield* harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runDrain, @@ -538,10 +574,7 @@ describe("OpenCodeAdapterV2", () => { ); const start = yield* harness.startTurn().pipe(Effect.forkScoped); yield* Effect.promise(() => catalogStarted.promise); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const activeTurn = snapshot.providerTurns.at(-1)!; + const activeTurn = yield* harness.awaitLatestTurn(); const steer = (message: string) => harness.runtime .steerTurn({ @@ -616,7 +649,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -648,7 +681,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -864,7 +897,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -999,7 +1032,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1107,7 +1140,7 @@ describe("OpenCodeAdapterV2", () => { contextUsage: { usedTokens: 150_000, maxTokens: 160_000 }, }, }); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1194,7 +1227,7 @@ describe("OpenCodeAdapterV2", () => { }, }, }); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1236,7 +1269,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.filter( (event) => event.type === "runtime_request.updated" || @@ -1312,7 +1345,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -1723,7 +1756,7 @@ describe("OpenCodeAdapterV2", () => { }, }, }); - const awaitTerminal = harness.runtime.events.pipe( + const awaitTerminal = harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runDrain, @@ -1736,14 +1769,9 @@ describe("OpenCodeAdapterV2", () => { yield* awaitTerminal; } assert.equal(offers.length, 0, "foreground admission must not offer a continuation"); - const before = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(before.providerTurns.length, 1); - assert.equal( - before.providerTurns[0]?.status, - state === "settled" ? "completed" : "running", - ); + const before = yield* harness.awaitTurns((turns) => turns.length > 0); + assert.equal(before.length, 1); + assert.equal(before[0]?.status, state === "settled" ? "completed" : "running"); // Pinned task.ts injects a synthetic root prompt; prompt.ts saves it before starting its loop. yield* push(user("msg_background_result")); @@ -1906,10 +1934,7 @@ describe("OpenCodeAdapterV2", () => { yield* push(status("idle")); yield* Fiber.join(starting); assert.equal(promptIds.length, 1, "failed waiting foreground cannot submit"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "failed"); + yield* harness.awaitLatestTurn((turn) => turn.status === "failed"); return; } if (end === "catalog-live" || end === "catalog-replay") { @@ -1939,15 +1964,13 @@ describe("OpenCodeAdapterV2", () => { yield* TestClock.adjust("10 seconds"); if (idle !== null) yield* Fiber.join(idle); else yield* Fiber.join(starting); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "completed"); + const turn = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(turn.status, "completed"); return; } assert.equal(offers.length, state === "settled" ? 1 : 0, "only a settled root needs a run"); @@ -1955,10 +1978,8 @@ describe("OpenCodeAdapterV2", () => { yield* offers[0]!.onRunEndedWithoutStarting!(); yield* harness.startTurn("", undefined, undefined, false, "no-wake", {}); yield* awaitTerminal; - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "completed"); + const turn = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(turn.status, "completed"); assert.equal(promptIds.length, 1); return; } @@ -2122,7 +2143,7 @@ describe("OpenCodeAdapterV2", () => { }); assert.equal(beforeAdmission.runtimeRequests.length, 0); yield* harness.startTurn("", undefined, undefined, false, "held", {}); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "runtime_request.updated" && @@ -2215,7 +2236,7 @@ describe("OpenCodeAdapterV2", () => { assert.isTrue(Exit.isFailure(replacement), "uncertain native work requires reconnect"); assert.equal(promptIds.length, 1, "replacement cannot join the surviving native loop"); assert.deepEqual(aborted, [root, "ses_descendant"]); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "provider_session.updated" && @@ -2269,19 +2290,13 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => routeStarted.promise); yield* TestClock.adjust("10 seconds"); assert.isTrue(Exit.isFailure(yield* Fiber.join(starting))); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal( - snapshot.providerTurns.at(-1)?.status, - "failed", - "the installed turn must be finalized", - ); + // The installed turn must be finalized. + yield* harness.awaitLatestTurn((turn) => turn.status === "failed"); assert.deepEqual(aborted, [root, "ses_descendant"]); const replacement = yield* harness.startTurn("replacement").pipe(Effect.exit); assert.isTrue(Exit.isFailure(replacement), "incomplete replay requires reconnect"); assert.equal(promptIds.length, 1, "failed replay cannot submit a foreground prompt"); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2363,7 +2378,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "owned-exit" || end === "failed-stream") { if (end === "owned-exit") yield* Deferred.succeed(nativeExit, 1); else nativeEvents.close(); - yield* harness.runtime.events.pipe( + yield* harness.events.pipe( Stream.filter( (event) => event.type === "provider_session.updated" && @@ -2451,10 +2466,8 @@ describe("OpenCodeAdapterV2", () => { [], "old callbacks cannot abort the installed runtime", ); - const replacementSnapshot = yield* replacement.runtime.readThreadSnapshot({ - providerThread: resumed, - }); - assert.equal(replacementSnapshot.providerTurns.at(-1)?.status, "running"); + const replacementTurn = yield* replacement.awaitLatestTurn(); + assert.equal(replacementTurn.status, "running"); return; } const foreground = @@ -2487,12 +2500,10 @@ describe("OpenCodeAdapterV2", () => { if (end === "foreground-stop" || end === "foreground-eof") { if (end === "foreground-eof") nativeEvents.close(); else { - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turn = yield* harness.awaitLatestTurn((turn) => turn.status === "running"); yield* harness.runtime.interruptTurn({ providerThread: harness.providerThread, - providerTurnId: snapshot.providerTurns.at(-1)!.id, + providerTurnId: turn.id, requestRuntimeRestart: true, }); } @@ -2545,14 +2556,8 @@ describe("OpenCodeAdapterV2", () => { assert.equal(promptIds.length, 2); if (end === "foreground-second-saved") { yield* push({ type: "session.idle", properties: { sessionID: root } }); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal( - snapshot.providerTurns.at(-1)?.status, - "running", - "an earlier reply cannot admit the foreground prompt", - ); + // An earlier reply cannot admit the foreground prompt. + yield* harness.awaitLatestTurn((turn) => turn.status === "running"); } return; } @@ -2584,7 +2589,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "sequential") yield* secondResult; assert.equal(offers.length, 2, "completed sequential wakes each offer once"); yield* harness.startTurn("", undefined, undefined, false, "wake-two", {}); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2599,11 +2604,11 @@ describe("OpenCodeAdapterV2", () => { ), ); assert.equal(promptIds.length, 1, "continuations never submit another prompt"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turns = yield* harness.awaitTurns( + (turns) => turns.length === 3 && turns.every((turn) => turn.completedAt !== null), + ); assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.status), + turns.map((turn) => turn.status), ["completed", "completed", "completed"], ); return; @@ -2616,10 +2621,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "foreground-buffered" || end === "foreground-buffered-error") yield* harness.startTurn("follow up", undefined, undefined, false, "next"); assert.equal(promptIds.length, 2, "the foreground prompt is submitted"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "running"); + yield* harness.awaitLatestTurn((turn) => turn.status === "running"); yield* push(user(promptIds[1]!)); yield* push({ type: "message.part.updated", @@ -2656,7 +2658,7 @@ describe("OpenCodeAdapterV2", () => { end === "foreground-buffered" || end === "foreground-buffered-error" ) { - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2785,7 +2787,7 @@ describe("OpenCodeAdapterV2", () => { return yield* Effect.die("OpenCode runtime must expose hasPendingBackgroundWork."); } yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && @@ -2942,7 +2944,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const childTurns = yield* harness.runtime.events.pipe( + const childTurns = yield* harness.events.pipe( Stream.filter( (event) => event.type === "provider_turn.updated" && @@ -3055,7 +3057,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -3174,7 +3176,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "plan.updated"), Stream.runCollect, Effect.forkScoped, @@ -3241,7 +3243,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -3502,7 +3504,7 @@ describe("OpenCodeAdapterV2", () => { }), ); yield* Fiber.join(start); - const terminal = yield* harness.runtime.events.pipe( + const terminal = yield* harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runCollect, @@ -3564,7 +3566,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn("/compact"); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -3618,7 +3620,7 @@ describe("OpenCodeAdapterV2", () => { id: ProviderThreadId.make("provider-thread:opencode-test:forked-run-row"), }; yield* harness.startTurn("/compact", forkedRow); - const terminal = yield* harness.runtime.events.pipe( + const terminal = yield* harness.events.pipe( Stream.filter( (event): event is Extract => event.type === "turn.terminal", @@ -3739,14 +3741,12 @@ describe("OpenCodeAdapterV2", () => { { options: [{ id: "variant", value: "high" }], interactionMode: "plan" }, ); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turn = yield* harness.awaitLatestTurn(); yield* harness.runtime.steerTurn({ threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: snapshot.providerTurns.at(-1)!.id, + providerTurnId: turn.id, message: { messageId: MessageId.make("message-opencode-steer-agent"), text: "also cover the README", @@ -3865,6 +3865,7 @@ describe("OpenCodeAdapterV2", () => { modelSelection, runtimePolicy: policy, }); + const tracked = trackProviderTurns(runtime); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, @@ -3972,9 +3973,8 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => statusCalled.promise); - const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "running"); - const activeTurn = snapshot.providerTurns.at(-1)!; + const activeTurn = yield* tracked.awaitLatestTurn(); + assert.equal(activeTurn.status, "running"); const steer = yield* runtime .steerTurn({ threadId, @@ -4080,8 +4080,8 @@ describe("OpenCodeAdapterV2", () => { properties: { sessionID: "native-opencode-race", status: { type: "idle" } }, }), ); - const interrupted = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(interrupted.providerTurns.at(-1)?.status, "interrupted"); + const interrupted = yield* tracked.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(interrupted.status, "interrupted"); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); @@ -4125,10 +4125,7 @@ describe("OpenCodeAdapterV2", () => { }, ); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const turn = snapshot.providerTurns.at(-1)!; + const turn = yield* harness.awaitLatestTurn(); const steer = yield* harness.runtime .steerTurn({ threadId: harness.threadId, @@ -4166,10 +4163,8 @@ describe("OpenCodeAdapterV2", () => { properties: { sessionID: "root", status: { type: "idle" } }, }), ); - const stopped = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(stopped.providerTurns.at(-1)?.status, "interrupted"); + const stopped = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(stopped.status, "interrupted"); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); @@ -4252,10 +4247,8 @@ describe("OpenCodeAdapterV2", () => { }, }), ); - const running = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - yield* harness.runtime.events.pipe( + const running = yield* harness.awaitLatestTurn(); + yield* harness.events.pipe( Stream.tap((event) => event.type === "turn.terminal" ? Deferred.succeed(terminal, undefined) : Effect.void, ), @@ -4267,7 +4260,7 @@ describe("OpenCodeAdapterV2", () => { threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: running.providerTurns.at(-1)!.id, + providerTurnId: running.id, message: { messageId: MessageId.make(`message-steer-rejected-${idleTiming}`), text: "also cover the README", @@ -4285,17 +4278,13 @@ describe("OpenCodeAdapterV2", () => { Deferred.await(terminal).pipe(Effect.as("completed")), ); assert.equal(outcome, "rechecked"); - const active = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(active.providerTurns.at(-1)?.status, "running"); + const active = yield* harness.awaitLatestTurn(); + assert.equal(active.status, "running"); yield* Effect.promise(() => nativeEvents.push(idle)); } if (idleTiming === "after-refused-connection") { - const active = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(active.providerTurns.at(-1)?.status, "running"); + const active = yield* harness.awaitLatestTurn(); + assert.equal(active.status, "running"); yield* Effect.promise(() => nativeEvents.push(idle)); } yield* Deferred.await(terminal); @@ -4303,10 +4292,8 @@ describe("OpenCodeAdapterV2", () => { assert.equal(statusCalls, idleTiming === "idle-during-status" ? 2 : 1); } - const settled = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(settled.providerTurns.at(-1)?.status, "completed"); + const settled = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(settled.status, "completed"); }).pipe( Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)), Effect.scoped, @@ -4354,10 +4341,8 @@ describe("OpenCodeAdapterV2", () => { }), ); yield* userMessage(promptIds[0]); - const running = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const received = yield* harness.runtime.events.pipe( + const running = yield* harness.awaitLatestTurn(); + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -4366,7 +4351,7 @@ describe("OpenCodeAdapterV2", () => { threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: running.providerTurns.at(-1)!.id, + providerTurnId: running.id, message: { messageId: MessageId.make("message-steer-reply-lost"), text: "also cover the README", @@ -4510,12 +4495,13 @@ describe("OpenCodeAdapterV2", () => { modelSelection, runtimePolicy: policy, }); + const tracked = trackProviderTurns(runtime); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy: policy, }); - const terminalEvents = yield* runtime.events.pipe( + const terminalEvents = yield* tracked.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -4566,8 +4552,7 @@ describe("OpenCodeAdapterV2", () => { .pipe(Effect.forkScoped); yield* Effect.promise(() => promptStarted.promise); - const running = yield* runtime.readThreadSnapshot({ providerThread }); - const activeTurn = running.providerTurns.at(-1)!; + const activeTurn = yield* tracked.awaitLatestTurn(); const interrupt = yield* runtime .interruptTurn({ providerThread, providerTurnId: activeTurn.id }) .pipe(Effect.forkScoped); @@ -4635,10 +4620,7 @@ describe("OpenCodeAdapterV2", () => { mcp: { add: async () => ({ data: true }) }, }); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const turn = snapshot.providerTurns.at(-1)!; + const turn = yield* harness.awaitLatestTurn(); const interrupt = yield* harness.runtime .interruptTurn({ providerThread: harness.providerThread, providerTurnId: turn.id }) .pipe(Effect.flip, Effect.forkScoped); @@ -4679,10 +4661,7 @@ describe("OpenCodeAdapterV2", () => { }, ); yield* harness.startTurn(); - const terminalEvents = yield* harness.runtime.events.pipe( - Stream.runCollect, - Effect.forkScoped, - ); + const terminalEvents = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); nativeEvents.close(); const received = Array.from(yield* Fiber.join(terminalEvents)); @@ -4736,7 +4715,7 @@ describe("OpenCodeAdapterV2", () => { }, }, ).pipe(Effect.provideService(Clock.Clock, blockingClock)); - const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped); + const events = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); const start = yield* harness.startTurn("/compact").pipe(Effect.forkScoped); yield* Effect.promise(() => summarizeStarted.promise); blockNextClockRead = true; @@ -4809,7 +4788,7 @@ describe("OpenCodeAdapterV2", () => { .pipe(Effect.provideService(Clock.Clock, blockingClock), Effect.exit, Effect.forkScoped); yield* Deferred.await(startClockRead); - const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped); + const events = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); nativeEvents.close(); yield* Fiber.join(events); yield* Deferred.succeed(releaseStartClockRead, undefined); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 6398e8ec74800..39376b09c0b59 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -3496,7 +3496,6 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function status: "idle" as const, updatedAt: snapshotNow, }, - providerTurns: state === undefined ? [] : [...state.providerTurns.values()], messages, runtimeRequests: state === undefined ? [] : [...state.runtimeRequests.values()], providerPayload: nativeMessages, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9cee26a3fb20d..c1426bb234735 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -349,7 +349,6 @@ interface ThreadState { goalRevision: number; goalFresh: boolean; goalRefreshing: boolean; - readonly providerTurns: Map; active: ActiveTurn | undefined; model: ModelRef | undefined; /** Locally ended but possibly live; consume its next execution end without settling a new turn. */ @@ -934,7 +933,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr goalRevision: 0, goalFresh: false, goalRefreshing: false, - providerTurns: new Map(), active: undefined, model: undefined, unsettled: false, @@ -1635,20 +1633,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr return ids.length === 0 ? {} : { retainedRuntimeRequestIds: ids }; }; - const emitProviderTurn = ( - state: ThreadState, - turn: ActiveTurn, - providerTurn: OrchestrationV2ProviderTurn, - ) => { - state.providerTurns.set(String(providerTurn.id), providerTurn); - return emit({ + const emitProviderTurn = (turn: ActiveTurn, providerTurn: OrchestrationV2ProviderTurn) => + emit({ type: "provider_turn.updated", driver, threadId: turn.input.threadId, providerTurn, ...(providerTurn.completedAt === null ? {} : retainedRequestsOf(turn)), }); - }; const makeTurn = ( owner: TurnOwner, @@ -2289,7 +2281,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr completedAt: null, }, }); - yield* emitProviderTurn(child, turn, providerTurn); + yield* emitProviderTurn(turn, providerTurn); const prompt = subagent.prompt; subagent.prompt = undefined; if (prompt !== undefined && prompt.length > 0) { @@ -2401,7 +2393,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); const window = windowOf(turn.input.runtimePolicy.cwd, turn.input.modelSelection.model); const lastStep = turn.lastStep; - yield* emitProviderTurn(state, turn, { + yield* emitProviderTurn(turn, { ...turn.providerTurn, status: terminal.status, completedAt, @@ -4321,7 +4313,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ]; }); const lastUser = history.findLast((message) => message.type === "user")?.id; - const state = threads.get(sessionId); return { providerThread: { ...providerThread, @@ -4330,7 +4321,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr status: "idle" as const, updatedAt: snapshotAt, }, - providerTurns: state === undefined ? [] : [...state.providerTurns.values()], messages, runtimeRequests: [], }; @@ -4491,7 +4481,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } state.active = turn; state.sessionScopedBackground = false; - yield* emitProviderTurn(state, turn, providerTurn); + yield* emitProviderTurn(turn, providerTurn); state.providerThread = { ...state.providerThread, status: "active", @@ -5459,22 +5449,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (boundary !== null) { yield* rollBackTo(sessionId, SessionMessage.ID.make(boundary)); } - const keptOrdinal = target.type === "provider_turn" ? target.providerTurn.ordinal : 0; - const loaded = threads.get(sessionId); - for (const [id, turn] of loaded?.providerTurns ?? []) { - if (turn.ordinal > keptOrdinal) loaded?.providerTurns.delete(id); - } - const snapshot = yield* snapshotOf(providerThread, sessionId); - const kept = new Map( - rollbackInput.providerThreadTurns - .filter( - (turn) => - turn.providerThreadId === providerThread.id && turn.ordinal <= keptOrdinal, - ) - .map((turn) => [turn.id, turn] as const), - ); - for (const turn of snapshot.providerTurns) kept.set(turn.id, turn); - return { ...snapshot, providerTurns: [...kept.values()] }; + return yield* snapshotOf(providerThread, sessionId); }, (effect, rollbackInput) => effect.pipe( diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index e7803bbe9c5ee..ad1fce56f9da8 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3858,7 +3858,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ); return { providerThread: state.providerThread, - providerTurns: [], messages, runtimeRequests: [], }; @@ -4370,7 +4369,7 @@ function piExtensionDisplayName(extensionPath: string | undefined): string { function piThreadSnapshot( providerThread: OrchestrationV2ProviderThread, ): ProviderAdapter.ProviderAdapterV2ThreadSnapshot { - return { providerThread, providerTurns: [], messages: [], runtimeRequests: [] }; + return { providerThread, messages: [], runtimeRequests: [] }; } function piQuestion( From 58e309e75b8f2fb2ad824a6437bfa920ab5398e9 Mon Sep 17 00:00:00 2001 From: Jex Date: Mon, 23 Nov 2026 14:35:49 +0800 Subject: [PATCH 036/288] fix(acp): deliver appContext on startTurn and steerTurn (#41241) Co-authored-by: Julius Marminge --- .../Adapters/AcpAdapterV2.test.ts | 794 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 272 +++++- 2 files changed, 1048 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 105565f79ef2f..54c1137870e73 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -25,10 +25,12 @@ import { assert, beforeAll, describe, it } from "@effect/vitest"; import { CheckpointId, EnvironmentId, + MessageId, type ModelSelection, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + RunId, ThreadId, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, @@ -12614,6 +12616,798 @@ describe("AcpAdapterV2", () => { ]); }).pipe(Effect.provide(layerTest)), ); + + it.live( + "delivers MCP appContext once per session, skips slash commands, and resends after unsuccessful turns, compaction, or runtime restart", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let runtimeCount = 0; + let cancelCalled: Deferred.Deferred | undefined; + const prompts: Array = []; + const queuedResponses: Array< + | { readonly _tag: "immediate"; readonly response: EffectAcpSchema.PromptResponse } + | { + readonly _tag: "gated"; + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + } + > = []; + const instanceId = ProviderInstanceId.make("acp-test-app-context-lifecycle"); + const threadId = ThreadId.make("thread-acp-app-context-lifecycle"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + restartRuntimeAfterInterrupt: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => { + runtimeCount += 1; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + cancel: Effect.suspend(() => + cancelCalled === undefined + ? Effect.void + : Deferred.succeed(cancelCalled, undefined).pipe(Effect.asVoid), + ), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = queuedResponses.shift(); + if (next === undefined) { + return { stopReason: "end_turn" as const }; + } + if (next._tag === "immediate") { + return next.response; + } + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }; + }, + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-app-context-lifecycle"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + let ordinal = 0; + const runTurn = (input: { + readonly text: string; + readonly note: string; + readonly response?: EffectAcpSchema.PromptResponse; + }) => + Effect.gen(function* () { + ordinal += 1; + if (input.response !== undefined) { + queuedResponses.push({ _tag: "immediate", response: input.response }); + } + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + messageText: input.text, + }), + appContext: [{ key: "mcp_app_item-1", text: input.note }], + }); + const events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + return { + prompt: prompts.at(-1) ?? "", + status: terminal?.type === "turn.terminal" ? terminal.status : null, + }; + }); + + const tag = (note: string) => `${note}`; + + // An unsuccessful stop reason must not mark appContext delivered. + const refusedTurn = yield* runTurn({ + text: "Refused attempt", + note: "Created Jira issue PROJ-42", + response: { stopReason: "refusal" }, + }); + assert.include(refusedTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Interrupted turns must not mark appContext delivered even if the prompt answers end_turn. + const interruptedStarted = yield* Deferred.make(); + const interruptedGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: interruptedStarted, + gate: interruptedGate, + }); + ordinal += 1; + const interruptedOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: interruptedOrdinal, + messageText: "Interrupted attempt", + }), + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* Deferred.await(interruptedStarted); + assert.include(prompts.at(-1) ?? "", tag("Created Jira issue PROJ-42")); + const interruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + instanceId, + `${sessionId}:turn:${interruptedOrdinal}`, + ), + }), + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(interruptedGate, { stopReason: "end_turn" }); + yield* Fiber.join(interruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Native slash commands skip appContext injection; the next normal turn sends it. + const slashTurn = yield* runTurn({ + text: " /repro-skill", + note: "Created Jira issue PROJ-42", + }); + assert.equal(slashTurn.status, "completed"); + assert.notInclude(slashTurn.prompt, "external_mcp_app_item-1"); + + const deliveredTurn = yield* runTurn({ + text: "What did the app report?", + note: "Created Jira issue PROJ-42", + }); + assert.equal(deliveredTurn.status, "completed"); + assert.include(deliveredTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Unchanged note is not resent; changed note is sent once. + const unchangedTurn = yield* runTurn({ + text: "Follow up", + note: "Created Jira issue PROJ-42", + }); + assert.notInclude(unchangedTurn.prompt, "external_mcp_app_item-1"); + + const changedTurn = yield* runTurn({ + text: "Updated check", + note: "Updated Jira issue PROJ-43", + }); + assert.include(changedTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterChangeTurn = yield* runTurn({ + text: "Second follow up", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterChangeTurn.prompt, "external_mcp_app_item-1"); + + // Compaction clears delivered appContext so the next turn resends it. + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "compaction_update", + compactionId: "compact-app-context", + status: "completed", + }, + }); + const postCompactTurn = yield* runTurn({ + text: "After compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.include(postCompactTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterPostCompactTurn = yield* runTurn({ + text: "Already resent after compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterPostCompactTurn.prompt, "external_mcp_app_item-1"); + + // Runtime restart clears delivered appContext even when resuming the same session id. + const restartStarted = yield* Deferred.make(); + const restartGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: restartStarted, + gate: restartGate, + }); + ordinal += 1; + const restartOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: restartOrdinal, + messageText: "Trigger restart", + }), + appContext: [{ key: "mcp_app_item-1", text: "Updated Jira issue PROJ-43" }], + }); + yield* Deferred.await(restartStarted); + const restartInterruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${restartOrdinal}`), + }), + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(restartGate, { stopReason: "cancelled" }); + yield* Fiber.join(restartInterruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const postRestartTurn = yield* runTurn({ + text: "After runtime restart", + note: "Updated Jira issue PROJ-43", + }); + assert.isAbove(runtimeCount, 1); + assert.include(postRestartTurn.prompt, tag("Updated Jira issue PROJ-43")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const prompts: Array = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-steer-prompt"); + const threadId = ThreadId.make("thread-acp-app-context-steer-prompt"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-steer-prompt", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${ordinal}-${prompts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1Initial.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note does not repeat on steer. + const steer1 = yield* queueGate(); + yield* steer(1, "Keep going", "Note A"); + yield* Deferred.await(steer1.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(turn1Initial.gate, { stopReason: "end_turn" }); + + // Slash steer skips appContext so the next normal steer carries the changed note. + const steerSlash = yield* queueGate(); + yield* steer(1, "/status", "Note B"); + yield* Deferred.await(steerSlash.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steer1.gate, { stopReason: "end_turn" }); + + const steerChanged = yield* queueGate(); + yield* steer(1, "Use updated note", "Note B"); + yield* Deferred.await(steerChanged.started); + assert.include(prompts.at(-1) ?? "", tag("Note B")); + yield* Deferred.succeed(steerSlash.gate, { stopReason: "end_turn" }); + + // Second steer with the same note does not resend it. + const steerSame = yield* queueGate(); + yield* steer(1, "One more detail", "Note B"); + yield* Deferred.await(steerSame.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steerChanged.gate, { stopReason: "end_turn" }); + yield* Deferred.succeed(steerSame.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 2 inherits delivered Note B; a failed prompt steer with Note C does not mark Note C delivered. + const turn2Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2Initial.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + const steerFailed = yield* queueGate(); + yield* steer(2, "Try Note C", "Note C"); + yield* Deferred.await(steerFailed.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + yield* Deferred.succeed(turn2Initial.gate, { stopReason: "end_turn" }); + yield* Deferred.fail( + steerFailed.gate, + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steer prompt rejected", + method: "session/prompt", + }), + ); + const turn2Events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const turn2Terminal = turn2Events.at(-1); + assert.equal( + turn2Terminal?.type === "turn.terminal" ? turn2Terminal.status : null, + "failed", + ); + + // Turn 3 must resend Note C because the failed steer did not deliver it. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on native flavor.steering and preserves undelivered notes on failure", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const prompts: Array = []; + const steeredTexts: Array = []; + const steerOutcomes: Array< + | { readonly _tag: "accept" } + | { readonly _tag: "fail" } + | { + readonly _tag: "waitId"; + readonly steerId: string; + readonly sent: Deferred.Deferred; + } + > = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-native-steer"); + const threadId = ThreadId.make("thread-acp-app-context-native-steer"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: { + ...AcpProviderCapabilitiesV2, + turns: { + ...AcpProviderCapabilitiesV2.turns, + supportsActiveSteering: true, + }, + }, + steering: { + send: (_runtime, _sessionId, text) => + Effect.gen(function* () { + steeredTexts.push(text); + const outcome = steerOutcomes.shift() ?? { _tag: "accept" as const }; + if (outcome._tag === "fail") { + return yield* new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steering rejected", + method: "_test/steer", + }); + } + if (outcome._tag === "waitId") { + yield* Deferred.succeed(outcome.sent, undefined); + return outcome.steerId; + } + return undefined; + }), + injectedSteerId: (notification) => { + if (notification.update.sessionUpdate !== "session_info_update") return undefined; + const meta = notification.update._meta as + | { readonly injectedSteerId?: string } + | undefined; + return meta?.injectedSteerId; + }, + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-native-steer", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`native-steer-${ordinal}-${steeredTexts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start native turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note is omitted on native steer. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Keep working", "Note A"); + assert.equal(steeredTexts.at(-1), "Keep working"); + + // Slash steer skips appContext injection. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "/status", "Note B"); + assert.equal(steeredTexts.at(-1), "/status"); + + // Rejected steering.send must not mark Note B delivered. + steerOutcomes.push({ _tag: "fail" }); + const failedExit = yield* Effect.exit(steer(1, "Failed steer", "Note B")); + assert.isTrue(Exit.isFailure(failedExit)); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Next steer with Note B resends it and marks it delivered once accepted. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Retry Note B", "Note B"); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Repeated steer with Note B omits it. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "After Note B", "Note B"); + assert.equal(steeredTexts.at(-1), "After Note B"); + + // Completing turn 1 must not clobber Note B with Turn 1's earlier Note A. + yield* Deferred.succeed(turn1.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const turn2 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start native turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + // A queued steer whose turn settles before injection must not mark Note C delivered. + const droppedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-dropped-1", + sent: droppedSteerSent, + }); + const droppedSteerFiber = yield* Effect.forkScoped( + Effect.exit(steer(2, "Dropped steer", "Note C")), + ); + yield* Deferred.await(droppedSteerSent); + yield* Deferred.succeed(turn2.gate, { stopReason: "end_turn" }); + const droppedExit = yield* Fiber.join(droppedSteerFiber); + assert.isTrue(Exit.isFailure(droppedExit)); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 3 must resend Note C; also verify injected steerId delivery works when notified. + const turn3 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start native turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* Deferred.await(turn3.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + + const injectedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-injected-1", + sent: injectedSteerSent, + }); + const injectedSteerFiber = yield* Effect.forkScoped(steer(3, "Injected steer", "Note D")); + yield* Deferred.await(injectedSteerSent); + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "session_info_update", + _meta: { injectedSteerId: "steer-injected-1" }, + }, + }); + yield* Fiber.join(injectedSteerFiber); + assert.include(steeredTexts.at(-1) ?? "", tag("Note D")); + yield* Deferred.succeed(turn3.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 4 sees Note D already delivered. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 4, + messageText: "Start native turn 4", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note D" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d9410e4754f35..065f95a3e247a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -164,6 +164,34 @@ function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean { ); } +type AcpAppContextEntry = NonNullable< + ProviderAdapter.ProviderAdapterV2TurnInput["appContext"] +>[number]; + +function formatAcpAppContextEntry(entry: AcpAppContextEntry): string { + return `${entry.text}`; +} + +function unsentAcpAppContext( + appContext: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"], + seen: ReadonlyMap | undefined, + isNativeSlashCommand: boolean, +): ReadonlyArray { + if (isNativeSlashCommand || appContext === undefined || appContext.length === 0) return []; + return appContext.filter((entry) => seen?.get(entry.key) !== entry.text); +} + +function mergeAcpAppContext( + base: ReadonlyMap | undefined, + entries: ReadonlyArray, +): ReadonlyMap { + const merged = new Map(base); + for (const entry of entries) { + merged.set(entry.key, entry.text); + } + return merged; +} + function sendPromptWhenIdle( turn: { readonly interrupted: boolean; readonly finalized: boolean }, prompt: () => Effect.Effect, @@ -1667,6 +1695,9 @@ interface ActiveAcpTurn { readonly completed: Deferred.Deferred; readonly itemOrdinals: Map; readonly outgoingPrompt?: ReadonlyArray | undefined; + appContextOffered?: ReadonlyMap | undefined; + readonly appContextCommittedSequence: Map; + appContextSequence: number; consumedPromptMessageId?: string; readonly user: ActiveTextStream; readonly assistant: ActiveTextStream; @@ -2343,6 +2374,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(null); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); + const deliveredAppContext = yield* Ref.make(new Map>()); // Unique markers keep delayed prompt completions from clearing later compactions. const compactionMarkers = yield* Ref.make(new Map()); // ACP may patch a completed compaction again; each compaction id marks its session once. @@ -2365,6 +2397,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(compactionMarkers, (current) => new Map(current).set(sessionId, Symbol()), ); + yield* Ref.update(deliveredAppContext, (current) => { + if (!current.has(sessionId)) return current; + const updated = new Map(current); + updated.delete(sessionId); + return updated; + }); + const currentTurn = yield* Ref.get(activeTurn); + if (currentTurn !== null && currentTurn.nativeThreadId === sessionId) { + currentTurn.appContextOffered = undefined; + currentTurn.appContextCommittedSequence.clear(); + } }); const advertisedCommandNames = yield* SubscriptionRef.make( new Map>(), @@ -8003,6 +8046,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeInteractionMode, null); yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); @@ -9101,6 +9145,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // while the prompt is prepared still resends the notes in this prompt. const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId); const compactionMarker = (yield* Ref.get(compactionMarkers)).get(sessionId); + const deliveredContext = (yield* Ref.get(deliveredAppContext)).get(sessionId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + deliveredContext, + isNativeSlashCommand, + ); const text = t3AcpPromptWithInstructions({ prompt: messageText, state: instructionState, @@ -9133,6 +9183,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: "ACP turn requires non-empty text or attachments", }); } + if (appContextEntries.length > 0) { + prompt.unshift( + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + ); + } if (sendRuntimeInstructions) { prompt.push({ type: "text", text: runtimeInstructions }); } @@ -9140,6 +9198,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( prompt, instructionState: text === messageText ? undefined : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, + appContextEntries, compactionMarker, }; }); @@ -9158,12 +9217,44 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); return true; }); + const commitAcpAppContext = Effect.fnUntraced(function* (input: { + readonly context: ActiveAcpTurn; + readonly entries: ReadonlyArray; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + }) { + if (input.entries.length === 0) return; + if ( + (yield* Ref.get(compactionMarkers)).get(input.context.nativeThreadId) !== + input.compactionMarker + ) { + return; + } + const freshEntries = input.entries.filter( + (entry) => + (input.context.appContextCommittedSequence.get(entry.key) ?? 0) < input.sequence, + ); + if (freshEntries.length === 0) return; + for (const entry of freshEntries) { + input.context.appContextCommittedSequence.set(entry.key, input.sequence); + } + yield* Ref.update(deliveredAppContext, (current) => { + const updated = new Map(current); + updated.set( + input.context.nativeThreadId, + mergeAcpAppContext(current.get(input.context.nativeThreadId), freshEntries), + ); + return updated; + }); + }); + /** Follows a turn's `session/prompt`; a prompt-steer's prompt supersedes the one before. */ const followPrompt = ( context: ActiveAcpTurn, @@ -9176,11 +9267,28 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( | Effect.Success>> | undefined; readonly promptParts: Effect.Success> | null; + readonly appContext?: + | { + readonly entries: ReadonlyArray; + readonly offered: ReadonlyMap | undefined; + readonly before: ReadonlyMap | undefined; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + } + | undefined; readonly compactSession: AcpAdapterV2Flavor["compactSession"]; }, ): Effect.Effect => { const sequence = ++context.promptSequence; const superseded = () => context.promptSequence !== sequence; + const rollbackOfferedAppContext = () => { + if ( + settle.appContext?.offered !== undefined && + context.appContextOffered === settle.appContext.offered + ) { + context.appContextOffered = settle.appContext.before; + } + }; return prompt(superseded).pipe( // Settle the wire before the completion callback's permit so a settled-soft // Stop sees the native return. Capture usage only before finalize: a late @@ -9223,6 +9331,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.set(context.nativeThreadId, promptParts.runtimeInstructions); return updated; }); + if ( + !context.interrupted && + !(context.finalized && context.finalizedStatus !== "completed") + ) { + if (settle.appContext !== undefined) { + yield* commitAcpAppContext({ + context, + entries: settle.appContext.entries, + compactionMarker: settle.appContext.compactionMarker, + sequence: settle.appContext.sequence, + }); + } + } else { + rollbackOfferedAppContext(); + } yield* Ref.update(compactionMarkers, (current) => { if (promptParts?.instructionState === undefined) return current; const observedMarker = promptParts.compactionMarker; @@ -9235,6 +9358,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.delete(context.nativeThreadId); return updated; }); + } else { + rollbackOfferedAppContext(); } if (context.finalized || followsAgentWorkState || superseded()) return; // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. @@ -9356,6 +9481,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runRuntimeCallbackAtGeneration( settle.generation, Effect.gen(function* () { + rollbackOfferedAppContext(); if (context.finalized || superseded()) return; const error = Cause.findError(cause); // Native close rejects prompts cancelled before insertion with -32800. @@ -9559,6 +9685,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (yield* Ref.get(activeSessionSetup))?.initializeResult.protocolVersion === 2 ? promptParts?.prompt : undefined, + appContextOffered: + promptParts !== null && + promptParts.appContextEntries.length > 0 && + (yield* Ref.get(compactionMarkers)).get(requestedSessionId) === + promptParts.compactionMarker + ? mergeAcpAppContext( + (yield* Ref.get(deliveredAppContext)).get(requestedSessionId), + promptParts.appContextEntries, + ) + : undefined, + appContextCommittedSequence: new Map(), + appContextSequence: 0, user: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, assistant: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, reasoning: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, @@ -9761,6 +9899,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; + const initialAppContext = + promptParts !== null && promptParts.appContextEntries.length > 0 + ? { + entries: promptParts.appContextEntries, + offered: context.appContextOffered, + before: undefined, + compactionMarker: promptParts.compactionMarker, + sequence: ++context.appContextSequence, + } + : undefined; yield* followPrompt( context, (superseded) => @@ -9776,7 +9924,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stopReason: "end_turn", } satisfies EffectAcpSchema.PromptResponse), ), - { generation: promptGeneration, checkPromptOutcome, promptParts, compactSession }, + { + generation: promptGeneration, + checkPromptOutcome, + promptParts, + appContext: initialAppContext, + compactSession, + }, ).pipe(Effect.forkIn(sessionScope)); }, (effect, turnInput) => @@ -9803,6 +9957,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2SteerInput, ) { + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); const text = yield* providerMessageTextWithAttachmentPaths({ text: turnInput.message.text, attachments: turnInput.message.attachments, @@ -9837,6 +9992,43 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, Effect.gen(function* () { if (context.finalized || context.interrupted) return false; + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const appContextBefore = context.appContextOffered; + const appContextOffered = + appContextEntries.length === 0 + ? undefined + : mergeAcpAppContext(seenAppContext, appContextEntries); + const steerAppContext = + appContextOffered === undefined + ? undefined + : { + entries: appContextEntries, + offered: appContextOffered, + before: appContextBefore, + compactionMarker, + sequence: ++context.appContextSequence, + }; + if (appContextOffered !== undefined) { + context.appContextOffered = appContextOffered; + } + const steerPrompt: Array = [ + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + { type: "text", text }, + ...attachmentBlocks, + ]; // The steer prompt carries the turn on, also past a prompt that already settled. const released = context.foregroundIdle; context.foregroundIdle = yield* Deferred.make(); @@ -9869,7 +10061,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, () => runtime.prompt( - { prompt: [{ type: "text", text }, ...attachmentBlocks] }, + { prompt: steerPrompt }, { dispatched, released: releasedForSteer }, ), superseded, @@ -9878,6 +10070,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, checkPromptOutcome, promptParts: null, + appContext: steerAppContext, compactSession: undefined, }, ).pipe(Effect.forkIn(sessionScope)); @@ -10210,26 +10403,69 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); + const images = yield* imageAttachmentBlocks(turnInput.message.attachments); + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const steerText = + appContextEntries.length === 0 + ? text + : text.length > 0 + ? `${appContextEntries.map(formatAcpAppContextEntry).join("\n")}\n\n${text}` + : appContextEntries.map(formatAcpAppContextEntry).join("\n"); + const appContextSequence = + appContextEntries.length === 0 ? 0 : ++context.appContextSequence; const steerId = yield* steering.send( runtime, context.nativeThreadId, - text, - yield* imageAttachmentBlocks(turnInput.message.attachments), + steerText, + images, ); - if (steerId === undefined) return; - const injected = steerInjection(steerId); - // The agent reads a steer at its next step. One that lands after the last - // step is dropped, and the turn settles right after; the orchestrator then - // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. - const outcome = yield* Effect.raceFirst( - Deferred.await(injected).pipe(Effect.as("injected" as const)), - Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), - ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); - steerInjections.delete(steerId); - if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + let steerConfirmed = true; + if (steerId !== undefined) { + const injected = steerInjection(steerId); + // The agent reads a steer at its next step. One that lands after the last + // step is dropped, and the turn settles right after; the orchestrator then + // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. + const outcome = yield* Effect.raceFirst( + Deferred.await(injected).pipe(Effect.as("injected" as const)), + Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), + ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); + steerInjections.delete(steerId); + if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + }); + } + // A steer still unread at the bound may yet be dropped, so its notes stay unsent. + steerConfirmed = yield* Deferred.isDone(injected); + } + if ( + steerConfirmed && + appContextEntries.length > 0 && + !context.interrupted && + (yield* Ref.get(compactionMarkers)).get(context.nativeThreadId) === compactionMarker + ) { + context.appContextOffered = mergeAcpAppContext( + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId), + appContextEntries, + ); + yield* commitAcpAppContext({ + context, + entries: appContextEntries, + compactionMarker, + sequence: appContextSequence, }); } }, From 49ce71efa38a3ca5ae9cde01bc9c3da04a38dbb2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:45:02 -0800 Subject: [PATCH 037/288] fix(server): later Codex retry or failure no longer sorts above same-turn progress (#41255) --- .../Adapters/CodexAdapterV2.test.ts | 126 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 36 ++++- .../orchestration-v2/ProviderEventIngestor.ts | 3 + .../ProviderSessionManager.test.ts | 1 + .../ProviderSessionManager.ts | 1 + .../orchestration-v2/RunExecutionService.ts | 3 + .../src/server/ProviderAdapter.ts | 2 + packages/provider-core/src/server/failure.ts | 24 ++-- 8 files changed, 182 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 330524c99ad3b..afb1d08147111 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5805,6 +5805,132 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each(["retry", "failure"] as const)( + "orders a later provider %s after progress from the same turn", + (tail) => + Effect.gen(function* () { + const scenario = `codex-provider-later-${tail}`; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const retryNotice = (message: string) => ({ + type: "emit_inbound" as const, + label: `error/retry/${message}`, + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message, + additionalDetails: "The response stream disconnected.", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 529 } }, + }, + }, + }, + }); + const commandItem = (status: "inProgress" | "completed") => ({ + type: "commandExecution", + id: "command-between-retries", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status, + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: status === "completed" ? "/workspace\n" : null, + exitCode: status === "completed" ? 0 : null, + durationMs: status === "completed" ? 10 : null, + }); + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run pwd." }), + retryNotice("Reconnecting... 1/5"), + { + type: "emit_inbound", + label: "item/started", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622445000, + item: commandItem("inProgress"), + }, + }, + }, + { + type: "emit_inbound", + label: "item/completed", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + completedAtMs: 1782622445010, + item: commandItem("completed"), + }, + }, + }, + ...(tail === "retry" ? [retryNotice("Reconnecting... 1/5")] : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: nativeTurnId, + status: tail === "retry" ? "completed" : "failed", + }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-${scenario}`), + text: "Run pwd.", + }), + ); + yield* harness.awaitTerminal(1); + + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" ? [event.turnItem] : [], + ); + const command = items.find((item) => item.type === "command_execution"); + assert.isDefined(command); + const terminal = harness.terminalEvents()[0]; + const firstRetry = items.find((item) => item.type === "error"); + const latest = + tail === "retry" + ? items.findLast((item) => item.type === "error") + : terminal?.status === "failed" + ? { id: terminal.failureItemId, ordinal: terminal.failureItemOrdinal } + : undefined; + assert.isAbove(latest?.ordinal ?? 0, command?.ordinal ?? Infinity); + // Stored positions are per row, so the later notice needs its own row to sort after. + assert.isDefined(latest?.id); + assert.notStrictEqual(latest?.id, firstRetry?.id); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () => Effect.gen(function* () { const scenario = "codex-provider-retry-stall"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index a35767f62eecf..91dbb2f534970 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -46,6 +46,7 @@ import { type ServerProviderModel, isDelegatedAppThread, ThreadId, + type TurnItemId, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { AgentScope } from "@t3tools/shared/AgentScope"; @@ -1390,6 +1391,7 @@ interface ActiveCodexTurnContext { capacityRetryAttempt?: number; capacityRetryPending?: Deferred.Deferred; closedCommandItemIds?: ReadonlySet; + recoveredProviderRetries?: number; latestProviderFailure?: { readonly nativeMessage: string; readonly nativeCode: string | null; @@ -1432,6 +1434,24 @@ interface ActiveCodexProviderRetry { readonly failure: OrchestrationV2ProviderFailure; readonly startedAt: DateTime.Utc; readonly itemOrdinal: number; + readonly id: TurnItemId | undefined; +} + +// Each retry episode after a recovery gets its own row, placed after the turn's progress so far. +function codexFailureItemKey(context: ActiveCodexTurnContext): string { + const key = `terminal-failure:${context.providerTurnId}`; + return context.recoveredProviderRetries === undefined + ? key + : `${key}:${context.recoveredProviderRetries}`; +} + +function codexFailureItemId(context: ActiveCodexTurnContext): TurnItemId | undefined { + return context.recoveredProviderRetries === undefined + ? undefined + : IdAllocator.derive.turnItemFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: codexFailureItemKey(context), + }); } function codexRetryTurnItem( @@ -1443,6 +1463,7 @@ function codexRetryTurnItem( // A continuation keeps the retry row attached to the native turn that failed. const context = state.context ?? activeContext; return makeProviderRetryTurnItem({ + ...(state.id === undefined ? {} : { id: state.id }), driver: CODEX_PROVIDER, threadId: context.projectionThreadId, runId: context.projectionRunId, @@ -2614,6 +2635,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (providerRetry === undefined) { return; } + context.recoveredProviderRetries = (context.recoveredProviderRetries ?? 0) + 1; yield* emitProviderEvent({ type: "turn_item.updated", driver: CODEX_PROVIDER, @@ -5428,8 +5450,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const itemOrdinal = previous?.itemOrdinal ?? - (yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`)); + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))); const state: ActiveCodexProviderRetry = { + id: previous === undefined ? codexFailureItemId(context) : previous.id, ...(previous?.context === undefined ? {} : { context: previous.context }), nativeMessage: payload.error.message, nativeCode: code, @@ -6609,6 +6632,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { failure = { ...failure, class: "transport_error" }; } + const failureItemId = codexFailureItemId(input.context); return { type: "turn.terminal", driver: CODEX_PROVIDER, @@ -6617,8 +6641,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( runOrdinal: input.context.input.runOrdinal, failureItemOrdinal: yield* resolveItemOrdinal( input.context, - `terminal-failure:${input.context.providerTurnId}`, + codexFailureItemKey(input.context), ), + ...(failureItemId === undefined ? {} : { failureItemId }), status: terminalStatus, failure: failure.class === "usage_limit" @@ -6674,6 +6699,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* emitProviderEvent(current); if (current.status === "failed" && current.failure.class === "usage_limit") { const item = makeProviderFailureTurnItem({ + ...(current.failureItemId === undefined ? {} : { id: current.failureItemId }), driver: CODEX_PROVIDER, threadId: context.input.threadId, runId: context.input.runId, @@ -7415,10 +7441,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( retry: { attempt, maxAttempts: CODEX_CAPACITY_MAX_RETRIES, retryDelayMs }, itemOrdinal: previous?.itemOrdinal ?? - (yield* resolveItemOrdinal( - context, - `terminal-failure:${context.providerTurnId}`, - )), + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))), + id: previous === undefined ? codexFailureItemId(context) : previous.id, startedAt: previous?.startedAt ?? now, }; yield* Ref.update(providerRetries, (current) => diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 118a13a334266..02057de1cae6d 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -737,6 +737,9 @@ export const layer: Layer.Layer< yield* makeDomainEvent(input, { type: "turn-item.updated", payload: makeProviderFailureTurnItem({ + ...(input.event.failureItemId === undefined + ? {} + : { id: input.event.failureItemId }), driver: input.event.driver, threadId: input.threadId, runId: input.runId ?? null, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 14d17371983b5..f2f992d8f4ee9 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2534,6 +2534,7 @@ it.effect("ProviderSessionManagerV2 fails a turn whose provider retry never resu providerTurnId, runOrdinal: 1, failureItemOrdinal: 3, + failureItemId: retryItem("running").id, status: "failed", failure: { ...failure, retryable: false }, retry, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 6d445f5b0bdf7..dc1ae318a4c2a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2942,6 +2942,7 @@ export const layerWithOptions = ( providerTurnId: event.providerTurnId, runOrdinal: event.runOrdinal, failureItemOrdinal: stalled.ordinal, + failureItemId: stalled.id, status: "failed", failure: { ...stalled.failure, retryable: false }, retry: stalled.retry, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index a5eeaa9cb8b95..21065b41a5f3e 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -993,6 +993,9 @@ export const layer: Layer.Layer< providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: makeProviderFailureTurnItem({ + ...(input.terminal.failureItemId === undefined + ? {} + : { id: input.terminal.failureItemId }), driver: input.terminal.driver, threadId: input.run.threadId, runId: input.run.id, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 4d008a7233900..015a68f48982b 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -234,6 +234,8 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, runOrdinal: PositiveInt, failureItemOrdinal: PositiveInt, + /** The row the failure lands on; defaults to the turn's `terminal-failure` row. */ + failureItemId: Schema.optional(TurnItemId), status: Schema.Literal("failed"), failure: OrchestrationV2ProviderFailure, retry: Schema.optional(OrchestrationV2ProviderRetry), diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index e7d47cdb2175e..267e402900d25 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -9,6 +9,7 @@ import type { ProviderTurnId, RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Cause from "effect/Cause"; @@ -334,6 +335,8 @@ export function makeProviderFailure(input: { } export function makeProviderFailureTurnItem(input: { + // Defaults to the turn's single failure row. + readonly id?: TurnItemId; readonly driver: ProviderDriverKind; readonly threadId: ThreadId; readonly runId: RunId | null; @@ -347,10 +350,12 @@ export function makeProviderFailureTurnItem(input: { readonly occurredAt: DateTime.Utc; }): Extract { return { - id: IdAllocator.derive.turnItemFromProviderItem({ - driver: input.driver, - nativeItemId: `terminal-failure:${input.providerTurnId}`, - }), + id: + input.id ?? + IdAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), threadId: input.threadId, runId: input.runId, nodeId: input.nodeId, @@ -378,6 +383,7 @@ export function makeProviderFailureTurnItem(input: { export const PROVIDER_RETRY_BUDGET_MS = 10 * 60 * 1000; export function makeProviderRetryTurnItem(input: { + readonly id?: TurnItemId; readonly driver: ProviderDriverKind; readonly threadId: ThreadId; readonly runId: RunId | null; @@ -404,10 +410,12 @@ export function makeProviderRetryTurnItem(input: { title = "Provider retry stopped"; } return { - id: IdAllocator.derive.turnItemFromProviderItem({ - driver: input.driver, - nativeItemId: `terminal-failure:${input.providerTurnId}`, - }), + id: + input.id ?? + IdAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), threadId: input.threadId, runId: input.runId, nodeId: input.nodeId, From f00893a512b9c32187ac32c795f1e3ef3839521a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:52:04 -0800 Subject: [PATCH 038/288] fix(server): branch names keep leading and trailing Unicode whitespace (#41274) --- apps/server/src/git/GitManager.ts | 14 ++- apps/server/src/git/GitWorkflowService.ts | 3 +- apps/server/src/git/remoteRefs.ts | 12 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 111 +++++++++++-------- apps/server/src/vcs/GitVcsDriverCore.ts | 53 +++++---- packages/contracts/src/baseSchemas.ts | 33 ++++++ packages/contracts/src/git.test.ts | 33 ++++++ packages/contracts/src/git.ts | 55 ++++----- packages/contracts/src/orchestrationV2.ts | 21 ++-- packages/contracts/src/pullRequest.ts | 19 ++-- packages/contracts/src/review.ts | 14 +-- packages/contracts/src/sourceControl.ts | 8 +- packages/contracts/src/threadPullRequest.ts | 9 +- packages/contracts/src/worktreeMcp.ts | 12 +- packages/contracts/src/worktreeSetup.ts | 12 +- 15 files changed, 257 insertions(+), 152 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dedf2d19f54ed..4b23f8cd6c66f 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -66,7 +66,11 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts"; +import { + GitManagerError, + GitPullRequestMaterializationError, + trimAsciiWhitespace, +} from "@t3tools/contracts"; import { historicalMessage, renderHistory, @@ -278,7 +282,7 @@ const prLookupGitReads = Context.Reference( function parseRemoteNames(stdout: string): ReadonlyArray { return stdout .split("\n") - .map((name) => name.trim()) + .map(trimAsciiWhitespace) .filter((name) => name.length > 0); } @@ -2012,7 +2016,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, })).stdout .split("\n") - .map((ref) => ref.trim()) + .map(trimAsciiWhitespace) .filter((ref) => ref.length > 0), ); const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`)); @@ -2049,7 +2053,7 @@ export const make = Effect.gen(function* () { const oidByRef = new Map( refs.stdout .split("\n") - .map((line) => line.trim().split("\u0000")) + .map((line) => trimAsciiWhitespace(line).split("\u0000")) .filter((entry): entry is [string, string] => entry.length === 2), ); const localOid = oidByRef.get(localRef); @@ -3354,7 +3358,7 @@ export const make = Effect.gen(function* () { const refNames = new Set( trackingRefs.stdout .split("\n") - .map((remoteRef) => remoteRef.trim()) + .map(trimAsciiWhitespace) .filter((remoteRef) => remoteRef.length > 0), ); return remoteNames diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 4cf3e62d9a93f..ca7c0b03c13d4 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,6 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; +import { trimAsciiWhitespace } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -365,7 +366,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, }); if (result.exitCode === 0) { - return result.stdout.trim().replace(/^refs\/heads\//, "") || null; + return trimAsciiWhitespace(result.stdout).replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index e3873effe475e..c5be08c165676 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,7 +1,9 @@ +import { trimAsciiWhitespace } from "@t3tools/contracts"; + export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; for (const line of stdout.split("\n")) { - const remoteName = line.trim(); + const remoteName = trimAsciiWhitespace(line); if (remoteName.length > 0) { remoteNames.push(remoteName); } @@ -17,7 +19,7 @@ export function parseRemoteRefWithRemoteNames( ref: string, remoteNames: ReadonlyArray, ): { remoteRef: string; remoteName: string; branchName: string } | null { - const trimmedRef = ref.trim(); + const trimmedRef = trimAsciiWhitespace(ref); if (trimmedRef.length === 0) { return null; } @@ -27,7 +29,7 @@ export function parseRemoteRefWithRemoteNames( if (!trimmedRef.startsWith(remotePrefix)) { continue; } - const branchName = trimmedRef.slice(remotePrefix.length).trim(); + const branchName = trimmedRef.slice(remotePrefix.length); if (branchName.length === 0) { return null; } @@ -48,7 +50,7 @@ export function extractBranchNameFromRemoteRef( remoteNames?: ReadonlyArray; }, ): string { - const normalized = ref.trim(); + const normalized = trimAsciiWhitespace(ref); if (normalized.length === 0) { return ""; } @@ -67,5 +69,5 @@ export function extractBranchNameFromRemoteRef( if (firstSlash === -1) { return normalized; } - return normalized.slice(firstSlash + 1).trim(); + return normalized.slice(firstSlash + 1); } diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d64c0ec5cbb5b..b7125614c0ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6485,24 +6485,36 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("marks the origin default ref as default when no local copy exists", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["remote", "set-head", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/only-local"]); - yield* git(cwd, ["branch", "-D", initialBranch]); - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["trunk", "feature/memo\u3000", "\u00a0release"])( + "marks the origin default ref %s as default when no local copy exists", + (defaultBranch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", defaultBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", defaultBranch]); + yield* git(cwd, ["remote", "set-head", "origin", defaultBranch]); + const driver = yield* GitVcsDriver.GitVcsDriver; - const refs = yield* driver.listRefs({ cwd }); - const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`); - assert.equal(remoteDefault?.isRemote, true); - assert.equal(remoteDefault?.isDefault, true); - }), + const localStatus = yield* driver.statusDetails(cwd); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + for (const status of [localStatus, remoteStatus]) { + assert.equal(status.branch, defaultBranch); + assert.equal(status.upstreamRef, `origin/${defaultBranch}`); + assert.isTrue(status.isDefaultBranch); + } + + yield* git(cwd, ["checkout", "-b", "feature/only-local"]); + yield* git(cwd, ["branch", "-D", defaultBranch]); + + const refs = yield* driver.listRefs({ cwd }); + const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${defaultBranch}`); + assert.equal(remoteDefault?.isRemote, true); + assert.equal(remoteDefault?.isDefault, true); + }), ); it.effect("preserves exact custom names and refuses collisions without a suffix", () => @@ -7444,37 +7456,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["release/v2", "origin/release/v2", "refs/remotes/origin/release/v2"])( - "records a remote-only PR base when creating a worktree from %s", - (baseRef) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release/v2"]); - const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); - yield* driver.createWorktree({ - cwd, - path: worktreePath, - refName: commit, - newRefName: "feature/remote", - baseRefName: baseRef, - }); + it.effect.each([ + "release/v2", + "origin/release/v2", + "refs/remotes/origin/release/v2", + "origin/release/v2\u3000", + ])("records a remote-only PR base when creating a worktree from %s", (baseRef) => + Effect.gen(function* () { + const branch = baseRef.replace(/^(refs\/remotes\/)?origin\//, ""); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `HEAD:refs/heads/${branch}`]); + const commit = yield* git(cwd, ["rev-parse", `origin/${branch}`]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: commit, + newRefName: "feature/remote", + baseRefName: baseRef, + }); - const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); - const comparisonBase = preview.sources.find( - (source) => source.kind === "branch-range", - )!.baseRef; - assert.equal( - yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), - commit, - ); - }), + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/remote.t3-merge-base"), + branch, + ); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + assert.equal(yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), commit); + }), ); it("parses checkout progress lines from git's stderr", () => { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 9ee53e4e90ac3..4981ece0979e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -34,6 +34,7 @@ import { type ReviewDiffPreviewInput, type ReviewDiffFileStat, type ReviewDiffPreviewSource, + trimAsciiWhitespace, type VcsRef, } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; @@ -452,8 +453,8 @@ function parseUpstreamRefByFirstSeparator( return null; } - const remoteName = upstreamRef.slice(0, separatorIndex).trim(); - const branchName = upstreamRef.slice(separatorIndex + 1).trim(); + const remoteName = upstreamRef.slice(0, separatorIndex); + const branchName = upstreamRef.slice(separatorIndex + 1); if (remoteName.length === 0 || branchName.length === 0) { return null; } @@ -467,13 +468,13 @@ function parseUpstreamRefByFirstSeparator( function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { - const trimmedLine = line.trim(); + const trimmedLine = trimAsciiWhitespace(line); if (trimmedLine.length === 0) { continue; } const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); - const branchName = branchNameRaw?.trim() ?? ""; - const candidateUpstreamRef = upstreamBranchRaw.trim(); + const branchName = branchNameRaw ?? ""; + const candidateUpstreamRef = upstreamBranchRaw; if (branchName.length === 0 || candidateUpstreamRef.length === 0) { continue; } @@ -490,7 +491,7 @@ function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { return null; } - const localBranch = branchName.slice(separatorIndex + 1).trim(); + const localBranch = branchName.slice(separatorIndex + 1); return localBranch.length > 0 ? localBranch : null; } @@ -592,19 +593,19 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { // `--short` and `--abbrev-ref` print `heads/` when a tag shares the branch's name, so // branch reads take the full ref and strip the prefix themselves. function branchNameFromHeadRef(value: string): string | null { - const ref = value.trim(); + const ref = trimAsciiWhitespace(value); return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length ? ref.slice("refs/heads/".length) : null; } function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { - const trimmed = value.trim(); + const trimmed = trimAsciiWhitespace(value); const prefix = `refs/remotes/${remoteName}/`; if (!trimmed.startsWith(prefix)) { return null; } - const refName = trimmed.slice(prefix.length).trim(); + const refName = trimmed.slice(prefix.length); return refName.length > 0 && refName !== "HEAD" ? refName : null; } @@ -1472,7 +1473,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); + ).pipe( + Effect.map((stdout) => trimAsciiWhitespace(stdout).replace(/^refs\/(?:remotes|heads)\//, "")), + ); if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; @@ -2056,7 +2059,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["symbolic-ref", "--quiet", "HEAD"], true, - ).pipe(Effect.map((stdout) => stdout.trim()))); + ).pipe(Effect.map(trimAsciiWhitespace))); if (headRef.length === 0) return undefined; const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", @@ -2065,7 +2068,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (upstreamRemote.exitCode !== 0) return undefined; - const remoteName = upstreamRemote.stdout.trim(); + const remoteName = trimAsciiWhitespace(upstreamRemote.stdout); // Empty means no upstream; `.` means the upstream is a local branch. if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); @@ -2202,7 +2205,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); if (branchPushRemote.length > 0) { return branchPushRemote; } @@ -2212,7 +2215,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", "remote.pushDefault"], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; }); @@ -2351,7 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], { allowNonZeroExit: true }, ); - const comparisonRef = upstream.stdout.trim(); + const comparisonRef = trimAsciiWhitespace(upstream.stdout); if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; }); @@ -2665,7 +2668,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); - headRef = branchResult.stdout.trim(); + headRef = trimAsciiWhitespace(branchResult.stdout); } let upstreamRemoteName: string | undefined; if (refreshUpstream) { @@ -2945,13 +2948,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.head ".length)); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.upstream ".length)); upstreamRef = value.length > 0 ? value : null; continue; } @@ -4031,7 +4034,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get-all", `branch.${refName}.merge`], true, - ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + ).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout).split("\n").filter(Boolean))), runGitStdout( "GitVcsDriver.pullCurrentBranch.currentBranch", cwd, @@ -5233,7 +5236,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) => runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), + Effect.map(trimAsciiWhitespace), Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); @@ -5279,7 +5282,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.cwd, ["rev-parse", "--symbolic-full-name", startPoint], { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : ""))); + ).pipe( + Effect.map((result) => (result.exitCode === 0 ? trimAsciiWhitespace(result.stdout) : "")), + ); if (!startRef.startsWith("refs/remotes/")) return; yield* executeGitWithStableDiagnostics( `${operation}.track`, @@ -5326,7 +5331,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } - const ref = result.stdout.trim(); + const ref = trimAsciiWhitespace(result.stdout); if (ref.startsWith("refs/heads/")) { const branchName = ref.slice("refs/heads/".length); return { baseRef: ref, branchName }; @@ -6897,7 +6902,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", "--show-current", - ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + ]).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout) || null)); return { refName }; }, @@ -6937,7 +6942,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((stdout) => { const branchNames: Array = []; for (const line of stdout.split("\n")) { - const branchName = line.trim(); + const branchName = trimAsciiWhitespace(line); if (branchName.length > 0) { branchNames.push(branchName); } diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index d8137fc8ca9ec..be27f15c58753 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -28,6 +28,39 @@ const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, }); export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank); +// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such +// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. +export function trimAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; + while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; + return end - start === value.length ? value : value.slice(start, end); +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || (code >= 0x09 && code <= 0x0d); +} + +const isNonBlankGitRefName = Schema.makeFilter( + (value: string) => trimAsciiWhitespace(value).length > 0, + { + expected: "a non-blank string", + toJsonSchema: () => [{ minLength: 1 }, true], + arbitraryConstraint: { minLength: 1 }, + }, +); +/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */ +export const GitRefName = Schema.String.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transformEffect({ + decode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + encode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + }), + ), +).check(isNonBlankGitRefName); + export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index ae7b260c368f9..8802b445e53ac 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -5,10 +5,18 @@ import { GitCommandError, GitPreparePullRequestThreadResult, GitRunStackedActionInput, + VcsCreateWorktreeInput, + VcsRef, } from "./git.ts"; +import { WorktreeMcpHandoffInput } from "./worktreeMcp.ts"; import { PullRequestDiffFileContentsInput } from "./pullRequest.ts"; import { ReviewDiffFileContentsInput } from "./review.ts"; +const encodeVcsRef = Schema.encodeUnknownSync(VcsRef); +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); +const encodeCreateWorktreeInput = Schema.encodeUnknownSync(VcsCreateWorktreeInput); +const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput); +const decodeWorktreeHandoffInput = Schema.decodeUnknownSync(WorktreeMcpHandoffInput); const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError)); const decodePreparePullRequestThreadResult = Schema.decodeUnknownSync( GitPreparePullRequestThreadResult, @@ -106,3 +114,28 @@ describe("Git file paths", () => { expect(encode(input)).toEqual(input); }); }); + +describe("Git ref names", () => { + it.each(["origin/release/v2\u3000", "\u00a0release", "\u3000"])( + "keeps Unicode whitespace at the edges of %j across the wire", + (name) => { + const ref = { name, upstreamRef: `refs/remotes/${name}`, current: false, isDefault: false }; + const wireRef = encodeVcsRef({ ...ref, worktreePath: null }); + expect(decodeVcsRef(wireRef)).toMatchObject(ref); + + const input = { cwd: "/repo", refName: name, newRefName: name, baseRefName: name }; + const wireInput = encodeCreateWorktreeInput({ ...input, path: null }); + expect(decodeCreateWorktreeInput(wireInput)).toMatchObject(input); + + const handoff = { branch: name, baseRef: name, startFromOrigin: true }; + expect(decodeWorktreeHandoffInput(handoff)).toEqual(handoff); + }, + ); + + it("still trims ASCII whitespace and rejects a blank name", () => { + expect( + decodeCreateWorktreeInput({ cwd: "/repo", refName: " \tmain\n", path: null }).refName, + ).toBe("main"); + expect(() => decodeCreateWorktreeInput({ cwd: "/repo", refName: " \t", path: null })).toThrow(); + }); +}); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 751f240f0709e..2faf0ffb8c248 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + GitRefName, ForwardCompatibleOptional, NonNegativeInt, PositiveInt, @@ -81,11 +82,11 @@ const GitRunStackedActionToast = Schema.Struct({ export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type; export const VcsRef = Schema.Struct({ - name: TrimmedNonEmptyStringSchema, + name: GitRefName, isRemote: Schema.optional(Schema.Boolean), - remoteName: Schema.optional(TrimmedNonEmptyStringSchema), + remoteName: Schema.optional(GitRefName), // Full Git ref, for example refs/remotes/origin/feature. - upstreamRef: Schema.optional(TrimmedNonEmptyStringSchema), + upstreamRef: Schema.optional(GitRefName), current: Schema.Boolean, isDefault: Schema.Boolean, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), @@ -94,14 +95,14 @@ export type VcsRef = typeof VcsRef.Type; const VcsWorktree = Schema.Struct({ path: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); const GitResolvedPullRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseBranch: TrimmedNonEmptyStringSchema, - headBranch: TrimmedNonEmptyStringSchema, + baseBranch: GitRefName, + headBranch: GitRefName, state: GitPullRequestState, }); export type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type; @@ -157,9 +158,9 @@ export type VcsListRefsInput = typeof VcsListRefsInput.Type; export const VcsCreateWorktreeInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, - newRefName: Schema.optional(TrimmedNonEmptyStringSchema), - baseRefName: Schema.optional(TrimmedNonEmptyStringSchema), + refName: GitRefName, + newRefName: Schema.optional(GitRefName), + baseRefName: Schema.optional(GitRefName), path: Schema.NullOr(TrimmedNonEmptyStringSchema), }); export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type; @@ -187,19 +188,19 @@ export type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type; export const VcsCreateRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, switchRef: Schema.optional(Schema.Boolean), }); export type VcsCreateRefInput = typeof VcsCreateRefInput.Type; export const VcsCreateRefResult = Schema.Struct({ - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsCreateRefResult = typeof VcsCreateRefResult.Type; export const VcsSwitchRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type; @@ -213,8 +214,8 @@ const VcsStatusChangeRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseRef: TrimmedNonEmptyStringSchema, - headRef: TrimmedNonEmptyStringSchema, + baseRef: GitRefName, + headRef: GitRefName, state: VcsStatusChangeRequestState, isDraft: Schema.optional(Schema.Boolean), updatedAt: Schema.optional(Schema.NullOr(Schema.String)), @@ -225,7 +226,7 @@ const VcsStatusLocalShape = { sourceControlProvider: Schema.optional(SourceControlProviderInfo), hasPrimaryRemote: Schema.Boolean, isDefaultRef: Schema.Boolean, - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), hasWorkingTreeChanges: Schema.Boolean, workingTree: Schema.Struct({ // Absolute worktree root on the environment that every files[].path is @@ -243,7 +244,7 @@ const VcsStatusLocalShape = { }), branchChanges: Schema.optional( Schema.Struct({ - baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + baseRef: Schema.NullOr(GitRefName), insertions: NonNegativeInt, deletions: NonNegativeInt, }), @@ -313,7 +314,7 @@ export type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Typ export const GitPreparePullRequestThreadResult = Schema.Struct({ pullRequest: GitResolvedPullRequest, - branch: TrimmedNonEmptyStringSchema, + branch: GitRefName, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), /** False when local commits or edits prevented a reused worktree from reaching the PR head. */ isOnPullRequestHead: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(true))), @@ -321,7 +322,7 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({ export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type; export const VcsSwitchRefResult = Schema.Struct({ - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), }); export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type; @@ -329,7 +330,7 @@ export const GitRunStackedActionResult = Schema.Struct({ action: GitStackedAction, branch: Schema.Struct({ status: GitBranchStepStatus, - name: Schema.optional(TrimmedNonEmptyStringSchema), + name: Schema.optional(GitRefName), }), commit: Schema.Struct({ status: GitCommitStepStatus, @@ -338,16 +339,16 @@ export const GitRunStackedActionResult = Schema.Struct({ }), push: Schema.Struct({ status: GitPushStepStatus, - branch: Schema.optional(TrimmedNonEmptyStringSchema), - upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema), + branch: Schema.optional(GitRefName), + upstreamBranch: Schema.optional(GitRefName), setUpstream: Schema.optional(Schema.Boolean), }), pr: Schema.Struct({ status: GitPrStepStatus, url: Schema.optional(Schema.String), number: Schema.optional(PositiveInt), - baseBranch: Schema.optional(TrimmedNonEmptyStringSchema), - headBranch: Schema.optional(TrimmedNonEmptyStringSchema), + baseBranch: Schema.optional(GitRefName), + headBranch: Schema.optional(GitRefName), title: Schema.optional(TrimmedNonEmptyStringSchema), }), toast: GitRunStackedActionToast, @@ -356,8 +357,8 @@ export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type; export const VcsPullResult = Schema.Struct({ status: Schema.Literals(["pulled", "skipped_up_to_date"]), - refName: TrimmedNonEmptyStringSchema, - upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), + refName: GitRefName, + upstreamRef: GitRefName.pipe(Schema.NullOr), }); export type VcsPullResult = typeof VcsPullResult.Type; @@ -430,8 +431,8 @@ export class GitPullRequestMaterializationError extends Schema.TaggedError Date: Mon, 23 Nov 2026 01:03:32 -0600 Subject: [PATCH 039/288] fix(cli): expand ~ paths in t3 thread --output-schema (#41271) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 16 ++++++++++++++++ apps/server/src/cli/thread.ts | 6 ++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index bb0906a9c6919..3e38b6885e9d9 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -27,6 +27,7 @@ import { latestRunError, launchModelSelection, readLatestMessages, + readOutputSchema, resolveProject, threadCommand, type ThreadTools, @@ -524,6 +525,21 @@ it.effect("start rejects a repeated --option before reaching the server", () => ), ); +it.effect("--output-schema reads a ~/ path from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-schema-" }); + yield* fs.writeFileString(path.join(home, "schema.json"), '{"type":"object"}'); + + const output = yield* readOutputSchema(Option.some("~/schema.json")).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + ); + + assert.deepStrictEqual(output, { outputSchema: { type: "object" } }); + }).pipe(Effect.provide(NodeServices.layer)), +); + /** Serves t3_thread_read pages the way the server does: positions count every item. */ const timelineTools = (types: ReadonlyArray) => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 1d81dcc6bd7cb..f57f1eed163f4 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -846,14 +846,16 @@ const outputSchemaFlag = Flag.String("output-schema").pipe( const decodeOutputSchema = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)), ); -const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( +export const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( path: Option.Option, ) { if (Option.isNone(path)) return {}; const fileSystem = yield* FileSystem.FileSystem; const usage = () => new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` }); - const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage)); + const text = yield* fileSystem + .readFileString(yield* expandHomePath(path.value)) + .pipe(Effect.mapError(usage)); return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) }; }); const messageArgument = Argument.String("message").pipe( From c8f8ad17ac50f4edfbc138969e1154fc0678494f Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:11:26 -0600 Subject: [PATCH 040/288] fix(web): RTF previews open files that declare code page 0 or 866 (#41277) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c2b6aa0b306d7..53783c7ded6a3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -296,6 +296,14 @@ Third}`; if (mac.type !== "document") throw new Error("Expected document"); expect(mac.pages[0]!.html).toBe("

Café Crème

"); } + for (const [rtf, expected] of [ + [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "

Café

"], + [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "

Привет

"], + ] as const) { + const decoded = openRtf(bytes(rtf)); + if (decoded.type !== "document") throw new Error("Expected document"); + expect(decoded.pages[0]!.html).toBe(expected); + } expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow( expect.objectContaining({ code: "rtf-code-page" }), ); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index f107ea0266043..d0c6bea968de1 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -704,6 +704,8 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { const label = ( { + 0: "windows-1252", + 866: "ibm866", 65001: "utf-8", 932: "shift_jis", 936: "gbk", From 0d2d6a0233ff8e84c2ee287d4a9533633d7acff3 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:41:39 +0530 Subject: [PATCH 041/288] fix(shared): composer file links to names with # ? & ' , % ! ~ open after sending (#41270) Co-authored-by: Julius Marminge --- .../shared/src/composerInlineTokens.test.ts | 27 +++++++++++++ packages/shared/src/composerInlineTokens.ts | 2 + packages/shared/src/composerTrigger.ts | 26 ++++++++++++- packages/shared/src/markdownLinks.test.ts | 16 ++++++++ ...-mention-punctuated-name-opens-file.e2e.ts | 39 +++++++++++++++++++ 5 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index c8c17b84a9b7b..bd50d1d345b9e 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -201,6 +201,33 @@ describe("collectComposerInlineTokens", () => { ]); }); + // regression: #41223 the composer's `./` is not part of the mention's path + it.each([ + "C#/Program.cs", + "docs/R&D/notes.md", + "docs/Bob's notes.md", + "docs/a,b.ts", + "docs/100%.md", + "docs/why?.md", + "icon@2x.png", + ])("reads a link to the punctuated file %s as that file's path", (path) => { + const link = serializeComposerFileLink(path); + expect(collectComposerInlineTokens(`fix ${link} please`)).toMatchObject([ + { type: "mention", value: path, source: link }, + ]); + }); + + // regression: #41223 a `./` the author wrote keeps its meaning, even where the parser rejects the rest + it.each([ + ["[draft:notes.md](./draft:notes.md)", "./draft:notes.md"], + ["[scratch](./%2Fscratch)", ".//scratch"], + ["[a.ts](./src/a.ts)", "./src/a.ts"], + ])("keeps the authored link %s as its own path", (link, value) => { + expect(collectComposerInlineTokens(`fix ${link} please`)).toMatchObject([ + { type: "mention", value, source: link }, + ]); + }); + it.each(["app/routes/posts.$postId.tsx", "pages/posts/[id].tsx"])( "preserves a confirmed TeX-like pill when its trailing delimiter is removed: %s", (path) => { diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 80a1b4d6916ae..f09ada6874a24 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,4 @@ +import { composerFileLinkPath } from "./composerTrigger.ts"; import { fileBasename } from "./path.ts"; /** The formulas a Markdown parser finds in text, as source offsets. */ @@ -57,6 +58,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { try { path = decodeURIComponent(encodedPath); } catch {} + path = composerFileLinkPath(encodedPath, path); const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path; const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path); diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 2a95d6b34cd0a..0aef14469813a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -1,3 +1,5 @@ +import { parseMarkdownFileLink } from "./markdownLinks.ts"; + export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill"; export type ComposerSlashCommand = "model" | "plan" | "default"; @@ -28,9 +30,31 @@ function encodeMarkdownLinkDestination(path: string): string { .replaceAll("\\", "%5C"); } +const URI_OR_ROOTED_PATH_PATTERN = /^(?:[a-z][a-z\d+.-]*:|[\\/])/i; + +// A relative destination the parser rejects (`C%23/Program.cs`) gets `./`, as codexFileCitations does. +function needsDotSlashPrefix(path: string): boolean { + return ( + path.length > 0 && + !parseMarkdownFileLink(encodeMarkdownLinkDestination(path)) && + !URI_OR_ROOTED_PATH_PATTERN.test(path) + ); +} + export function serializeComposerFileLink(path: string): string { const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path)); - return `[${label}](${encodeMarkdownLinkDestination(path)})`; + const destination = encodeMarkdownLinkDestination(path); + return `[${label}](${needsDotSlashPrefix(path) ? `./${destination}` : destination})`; +} + +/** The file a composer link names. Drops only the `./` serializeComposerFileLink adds, not one the author wrote. */ +export function composerFileLinkPath(encodedDestination: string, decodedPath: string): string { + if (!encodedDestination.startsWith("./")) return decodedPath; + const bare = decodedPath.slice(2); + return needsDotSlashPrefix(bare) && + encodeMarkdownLinkDestination(bare) === encodedDestination.slice(2) + ? bare + : decodedPath; } function clampCursor(text: string, cursor: number): number { diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 80204d903892b..27af706363367 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -95,6 +95,22 @@ describe("parseMarkdownFileLink", () => { expect(parseMarkdownFileLink(destination ?? "")?.path).toBe(path); }); + // regression: #41223 names the parser rejects bare; the composer adds `./` to them + it.each([ + "C#/Program.cs", + "docs/R&D/notes.md", + "docs/Bob's notes.md", + "docs/a,b.ts", + "docs/100%.md", + "docs/why?.md", + "icon@2x.png", + ])("resolves the composer's link to %s", (path) => { + const destination = /\]\((.*)\)$/.exec(serializeComposerFileLink(path))?.[1]; + expect(resolveMarkdownFileLinkTarget(destination ?? "", "/workspace/project")).toBe( + `/workspace/project/${path}`, + ); + }); + it.each([ "https://example.com/docs", "/chat/settings#L3", diff --git a/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts b/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts new file mode 100644 index 0000000000000..eda9c9f9a1e29 --- /dev/null +++ b/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts @@ -0,0 +1,39 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "C#/Program.cs"; + +test( + "An @-mention of a file whose folder has # opens it after the message is sent", + WEB, + async ({ t3, app, screen, browser }) => { + // The editor renders in a shadow root that locators do not reach. + const editorText = () => + browser.evaluate(() => { + for (const host of document.querySelectorAll("*")) { + const content = host.shadowRoot?.querySelector("[data-content]"); + if (content) return content.textContent ?? ""; + } + return null; + }); + + const project = await t3.project("demo", { [FILE]: "static void Main() {}\nProgram body\n" }); + const thread = await t3.thread({ project, title: "Mention", messages: ["Show me around"] }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @Program"); + await screen.getByRole("option", "Program.cs", { exact: false }).tap(); + await browser.keyboard.press("Enter"); + + const link = screen.getByRole("link", "Program.cs"); + await link.waitFor(); + await app.screenshot("sent-message"); + await link.tap(); + await expect.poll(editorText).toContain("Program body"); + await app.screenshot("file-opened"); + }, +); From 9f24cac6d42f99e92569b7cbd97ec07932f232d8 Mon Sep 17 00:00:00 2001 From: Kwan Li <71382503+Kwan-Li@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:13:06 +1000 Subject: [PATCH 042/288] fix(web): No project drafts no longer offer New worktree (#41269) Co-authored-by: Julius Marminge --- .../components/BranchToolbar.logic.test.ts | 14 +++ .../web/src/components/BranchToolbar.logic.ts | 10 ++ apps/web/src/components/BranchToolbar.tsx | 99 +++++++++++-------- apps/web/src/components/ChatView.tsx | 11 ++- .../chat/ThreadDetailsPanel.browser.test.tsx | 48 +++++++-- .../components/chat/ThreadDetailsPanel.tsx | 4 + 6 files changed, 135 insertions(+), 51 deletions(-) diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index c6006d36295db..05e49aa667b88 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -21,6 +21,7 @@ import { sanitizeNewRefName, shouldIncludeBranchPickerItem, isBranchHoldCurrent, + offersWorkspaceModes, toBranchActionErrorMessage, } from "./BranchToolbar.logic"; @@ -138,6 +139,19 @@ describe("resolveEffectiveEnvMode", () => { }); }); +describe("offersWorkspaceModes", () => { + it("offers worktrees from a repository or tracked repositories, never in No project", () => { + const folder = { isScratchProject: false, isGitRepo: false, tracksGitRepositories: false }; + expect(offersWorkspaceModes(folder)).toBe(false); + expect(offersWorkspaceModes({ ...folder, isGitRepo: true })).toBe(true); + expect(offersWorkspaceModes({ ...folder, tracksGitRepositories: true })).toBe(true); + // Git status assumes a repository until it loads. + expect(offersWorkspaceModes({ ...folder, isScratchProject: true, isGitRepo: true })).toBe( + false, + ); + }); +}); + describe("resolveLockedWorkspaceLabel", () => { it.each([ ["/home/me/.t3/worktrees/app/t3-ff466c42", "t3-ff466c42"], diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 21e75c4d8ed56..944ebe8b937be 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -81,6 +81,16 @@ export function shouldShowEnvironmentIndicator(input: { return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary; } +/** Whether a new thread here may choose between Current checkout and New worktree. */ +export function offersWorkspaceModes(input: { + isScratchProject: boolean; + isGitRepo: boolean; + tracksGitRepositories: boolean; +}): boolean { + // No project never has git, even while its status loads and isGitRepo still assumes it does. + return !input.isScratchProject && (input.isGitRepo || input.tracksGitRepositories); +} + export function shouldShowComposerContextStrip(input: { isDraftHeroState: boolean; persistInActiveThreads: boolean; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 43ea99b07480b..d42756a7daa5f 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -158,6 +158,8 @@ interface RunContextSelectorProps { displayMode?: "toolbar" | "panel"; workspaceRoot?: string; forceNewWorktree: boolean; + /** False when the folder has no repository a worktree could come from. */ + offersWorkspaceModes: boolean; autoEnvironmentLabel?: string | undefined; onAutoEnvironment?: (() => void) | undefined; envLocked: boolean; @@ -180,7 +182,8 @@ interface RunContextSelectorProps { const RunContextSelector = memo(function RunContextSelector({ displayMode = "toolbar", workspaceRoot, - forceNewWorktree, + forceNewWorktree: requestedForceNewWorktree, + offersWorkspaceModes, autoEnvironmentLabel, onAutoEnvironment, envLocked, @@ -190,7 +193,7 @@ const RunContextSelector = memo(function RunContextSelector({ showEnvironmentPicker, showEnvironmentIndicator, onEnvironmentChange, - effectiveEnvMode, + effectiveEnvMode: requestedEnvMode, activeWorktreePath, onEnvModeChange, previousWorktreeLabel, @@ -204,10 +207,13 @@ const RunContextSelector = memo(function RunContextSelector({ const composerFloatingLayerProps = useComposerMenuProps(); const activeEnvironment = availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null; + // A folder no worktree can come from runs threads in place, whatever mode was requested. + const forceNewWorktree = offersWorkspaceModes && requestedForceNewWorktree; + const effectiveEnvMode = offersWorkspaceModes ? requestedEnvMode : "local"; const WorkspaceIcon = effectiveEnvMode === "worktree" ? FolderGit2Icon - : activeWorktreePath + : activeWorktreePath && offersWorkspaceModes ? FolderGitIcon : FolderIcon; const workspaceLabel = forceNewWorktree @@ -218,7 +224,8 @@ const RunContextSelector = memo(function RunContextSelector({ ? resolveEnvModeLabel("worktree", m) : resolveCurrentWorkspaceLabel(activeWorktreePath, m); const isPanel = displayMode === "panel"; - const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker)); + const workspaceModesLocked = envModeLocked || !offersWorkspaceModes; + const isLocked = envLocked || (workspaceModesLocked && (!isPanel || !showEnvironmentPicker)); const workspacePath = forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath) ? null @@ -328,7 +335,7 @@ const RunContextSelector = memo(function RunContextSelector({ data-composer-context-control data-composer-shortcut={[ showEnvironmentPicker && !envLocked ? "composer.host" : "", - !envModeLocked ? "composer.workspace" : "", + !workspaceModesLocked ? "composer.workspace" : "", ].join(" ")} > {triggerContent} @@ -419,46 +426,52 @@ const RunContextSelector = memo(function RunContextSelector({ ) : null} - + {offersWorkspaceModes ? : null} ) : null} - - - Workspace - - { - if (value === "previous-worktree") { - onUsePreviousWorktree(); - return; - } - onEnvModeChange(value as EnvMode); - }} - > - - - {activeWorktreePath ? ( - - ) : ( - - )} - - - - - - - {resolveEnvModeLabel("worktree", m)} - - - {previousWorktreeLabel ? ( - - + {offersWorkspaceModes ? ( + + + Workspace + + { + if (value === "previous-worktree") { + onUsePreviousWorktree(); + return; + } + onEnvModeChange(value as EnvMode); + }} + > + + + {activeWorktreePath ? ( + + ) : ( + + )} + + + + + + + {resolveEnvModeLabel("worktree", m)} + - ) : null} - - + {previousWorktreeLabel ? ( + + + + ) : null} + + + ) : null} ); @@ -740,6 +753,7 @@ export const BranchToolbar = memo(function BranchToolbar({ displayMode="panel" workspaceRoot={activeProject.workspaceRoot} forceNewWorktree={forceNewWorktree} + offersWorkspaceModes={showGitControls} autoEnvironmentLabel={autoEnvironmentLabel} onAutoEnvironment={onAutoEnvironment} envLocked={envLocked} @@ -790,6 +804,7 @@ export const BranchToolbar = memo(function BranchToolbar({
}) { +const machines = (["This Mac", "Server"] as const).map((label, index) => ({ + environmentId: EnvironmentId.make(index === 0 ? "environment" : "other"), + projectId: ProjectId.make("project"), + label, + isPrimary: index === 0, + machine: "server" as const, +})); + +function Panel({ + fixture, + draftEnvMode, + onMachines = false, +}: { + fixture: ReturnType; + /** Renders an unsent draft in this mode instead of a started thread. */ + draftEnvMode?: "local" | "worktree"; + onMachines?: boolean; +}) { const noop = () => {}; const scriptResult = async () => ({ ok: true }) as never; return ( @@ -149,8 +166,8 @@ function Panel({ fixture }: { fixture: ReturnType }) { threadId={threadRef.threadId} projectId={ProjectId.make("project")} composerDraftTarget={threadRef} - worktreePath={state.folder} - isServerThread + worktreePath={draftEnvMode === undefined ? state.folder : null} + isServerThread={draftEnvMode === undefined} activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"} activeProjectScripts={undefined} preferredScriptId={null} @@ -161,10 +178,12 @@ function Panel({ fixture }: { fixture: ReturnType }) { gitCwd={state.folder} workspaceMutationId={null} isGitRepo={false} - envLocked - availableEnvironments={[]} + offersWorkspaceModes={false} + envLocked={draftEnvMode === undefined} + availableEnvironments={onMachines ? machines : []} + {...(onMachines ? { onEnvironmentChange: noop } : {})} onEnvModeChange={noop} - envMode="local" + envMode={draftEnvMode ?? "local"} startFromOrigin={false} onStartFromOriginChange={noop} onComposerFocusRequest={noop} @@ -191,6 +210,23 @@ it("offers no git controls in a No project thread, but shows its linked pull req .not.toBeInTheDocument(); }); +it("shows Current checkout where no worktree can come from, even when New worktree is the default", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render(); + await expect.element(page.getByLabelText("Run context: Current checkout")).toBeVisible(); + await expect.element(page.getByRole("button", { name: /Run context/ })).not.toBeInTheDocument(); +}); + +it("offers only machines where no worktree can come from and several machines exist", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render( + , + ); + await page.getByRole("button", { name: "Run context: This Mac, Current checkout" }).click(); + await expect.element(page.getByText("Run on")).toBeVisible(); + await expect.element(page.getByText("New worktree")).not.toBeInTheDocument(); +}); + it("shows a linked pull request in a folder that is not a git repository", async () => { using fixture = setup({ workspaceRoot: "/work/plain", diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 085815bed02cf..69c3cd7133aff 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -71,6 +71,8 @@ interface ThreadDetailsPanelProps extends Pick< gitCwd: string | null; workspaceMutationId: string | null; isGitRepo: boolean; + /** False when no worktree can come from this folder, so it offers no workspace modes. */ + offersWorkspaceModes: boolean; envLocked: boolean; availableEnvironments: readonly EnvironmentOption[]; autoEnvironmentLabel?: string | undefined; @@ -220,6 +222,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { autoEnvironmentLabel={props.autoEnvironmentLabel} onAutoEnvironment={props.onAutoEnvironment} {...branchToolbarProps} + // Workspace modes follow the composer's rule, not this folder's own status. + showGitControls={props.offersWorkspaceModes} /> ) : null} From 3b3255ccecf75db4c2da996eb153dca77373ff35 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 23:37:53 -0800 Subject: [PATCH 043/288] fix(server): queued messages stay visible when a restart cancels their started run (#41307) --- .../orchestration-v2/ProjectionStore.test.ts | 17 +++ .../src/orchestration-v2/ProjectionStore.ts | 23 +++- .../src/orchestration-v2/ThreadFind.test.ts | 3 +- .../src/orchestration-v2/ThreadSearch.test.ts | 20 +++- .../src/orchestration-v2/ThreadSearch.ts | 5 +- .../state/orchestrationV2Projection.test.ts | 8 +- .../src/orchestrationV2Timeline.test.ts | 110 ++++++++++-------- .../shared/src/orchestrationV2Timeline.ts | 17 +-- 8 files changed, 137 insertions(+), 66 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index f13f3f05409ba..636e69e7574b0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -5679,6 +5679,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ); } + // Recovery cancels a run that had started; its delivered queued message stays. + const setCancelledStartedAt = (startedAt: string | null) => sql` + UPDATE orchestration_v2_projection_runs + SET payload_json = json_set(payload_json, '$.startedAt', ${startedAt}) + WHERE run_id = ${cancelledRunId} + `; + yield* setCancelledStartedAt(nowIso); + const startedCancelledSnapshot = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + }); + assert.isTrue( + startedCancelledSnapshot.projection.visibleTurnItems.some((row) => + String(row.sourceItemId).includes(":cancelled:"), + ), + ); + yield* setCancelledStartedAt(null); + // A steer moves the cancelled queued message outside the window. const steeredItemId = "turn-item:bounded-sql-history:steered-output"; const steeredRunId = RunId.make("run:bounded-sql-history:1000"); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2278284d7fde7..84458e644e509 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3461,6 +3461,7 @@ export const layer: Layer.Layer = ) ) AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' + AND (run.status = 'queued' OR json_extract(run.payload_json, '$.startedAt') IS NULL) ) AND ( ${window.requiredRunId ?? null} IS NULL @@ -7374,7 +7375,9 @@ export const layer: Layer.Layer = const [hidingRuns, superseded] = yield* Effect.all([ sql<{ id: RunId; status: OrchestrationV2Run["status"] }>` SELECT run_id AS id, status FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} AND status IN ('rolled_back', 'queued', 'cancelled')`, + WHERE thread_id = ${threadId} + AND (status IN ('rolled_back', 'queued') + OR (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL))`, sql<{ runId: RunId; rootNodeId: NodeId; status: "superseded" }>` SELECT run_id AS runId, root_node_id AS rootNodeId, status FROM orchestration_v2_projection_run_attempts @@ -7396,8 +7399,8 @@ export const layer: Layer.Layer = })), }); // Only these runs can hide rows: every row of a rolled-back run, the queued turn of a - // queued or cancelled run, and the stop result of a replaced attempt. So the hidden rows - // are found without reading the thread. + // queued run or a cancelled one that never started, and the stop result of a replaced attempt. + // So the hidden rows are found without reading the thread. const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); const runsWithStatus = (...statuses: ReadonlyArray) => hidingRuns.flatMap((run) => (statuses.includes(run.status) ? [String(run.id)] : [])); @@ -8672,6 +8675,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) ELSE 0 END AS item_count @@ -8692,6 +8702,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) END) FROM orchestration_v2_projection_runs r INDEXED BY orchestration_v2_projection_runs_hidden_items_idx diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.ts index 6c6d0232bfce7..60c91be1065c9 100644 --- a/apps/server/src/orchestration-v2/ThreadFind.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts @@ -651,7 +651,8 @@ describe("V2 thread find", () => { Effect.gen(function* () { const projection = yield* setup; const queuedRunId = RunId.make("queued:cancelled"); - yield* commit([run(threadId, queuedRunId, 2, "cancelled")]); + const cancelled = run(threadId, queuedRunId, 2, "cancelled"); + yield* commit([{ ...cancelled, payload: { ...cancelled.payload, startedAt: null } }]); const queued = item("cancelled", 1, "needle", "user_message"); if (queued.type !== "user_message") return; const answer = item("async-answer:question", 2, "needle", "user_message"); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 399224533089d..e545d40633643 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -746,7 +746,8 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { const queued = ThreadId.make("thread:queued"); const stopped = ThreadId.make("thread:stopped"); const recovered = ThreadId.make("thread:recovered"); - const run = (owner: ThreadId, status: "rolled_back" | "cancelled") => + const restarted = ThreadId.make("thread:restarted"); + const run = (owner: ThreadId, status: "rolled_back" | "cancelled", started = true) => ({ id: EventId.make(`run:${owner}`), type: "run.created", @@ -767,7 +768,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { activeAttemptId: null, status, requestedAt: at(1), - startedAt: at(1), + startedAt: started ? at(1) : null, completedAt: at(2), checkpointId: null, contextHandoffId: null, @@ -818,7 +819,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${rewound}`), }), thread(queued, project), - run(queued, "cancelled"), + run(queued, "cancelled", false), message(queued, "queued-prompt", "user", "then mount the albatross drive", { runId: RunId.make(`run:${queued}`), }), @@ -840,6 +841,13 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${recovered}`), }), shown(recovered, "recovered-reply", "reply"), + // A restart cancels a turn that already took its queued prompt. + thread(restarted, project), + run(restarted, "cancelled"), + message(restarted, "delivered-prompt", "user", "then label the albatross drive", { + runId: RunId.make(`run:${restarted}`), + }), + shown(restarted, "delivered-prompt", "queued_turn"), ], projections.apply, { discard: true }, @@ -848,7 +856,11 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { (yield* search.search({ query: "albatross" })).matches .map((match) => match.messageId) .sort(), - [MessageId.make("recovered-reply"), MessageId.make("stopped-prompt")], + [ + MessageId.make("delivered-prompt"), + MessageId.make("recovered-reply"), + MessageId.make("stopped-prompt"), + ], ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 3ad48b26f172d..f3f8c6061dbe7 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -293,7 +293,10 @@ export const messageHitsQuery = ( SELECT 1 FROM orchestration_v2_projection_turn_items AS items WHERE items.run_id = runs.run_id AND json_extract(items.payload_json, '$.messageId') = messages.message_id - AND json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + AND ( + json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + OR json_extract(runs.payload_json, '$.startedAt') IS NOT NULL + ) ) ) ) diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index 16301157a6a4e..6436de7c7d907 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -486,7 +486,13 @@ describe("applyOrchestrationV2ProjectionEvent", () => { it("hides a steer that fell back to the queue until its run starts", () => { const queuedRunId = RunId.make("run-requeued-steer"); - const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const; + const queuedRun = { + ...run, + id: queuedRunId, + ordinal: 2, + status: "queued", + startedAt: null, + } as const; const reply = commandItem("item-reply", "reply", 102); const steer: OrchestrationV2TurnItem = { id: TurnItemId.make("item-steer"), diff --git a/packages/shared/src/orchestrationV2Timeline.test.ts b/packages/shared/src/orchestrationV2Timeline.test.ts index c2b7a0c920159..18a59c28a8fbe 100644 --- a/packages/shared/src/orchestrationV2Timeline.test.ts +++ b/packages/shared/src/orchestrationV2Timeline.test.ts @@ -1,4 +1,5 @@ import { NodeId, RunId } from "@t3tools/contracts"; +import { DateTime } from "effect"; import { describe, expect, it } from "vite-plus/test"; import { @@ -91,62 +92,73 @@ describe.each([ ).toBe(true); }); - it.each([ + it.each<{ + status: VisibilityInput["runs"][number]["status"]; + startedAt?: string; + hidden: string[]; + }>([ ...ordinaryStatuses.map((status) => ({ status, hidden: [] })), { status: "queued", hidden: ["queued"] }, { status: "cancelled", hidden: ["queued"] }, + { status: "cancelled", startedAt: "2026-11-23T06:11:54.535Z", hidden: [] }, { status: "rolled_back", hidden: ["queued", "start", "steer", "promoted", "legacy", "assistant", "request", "result"], }, - ] satisfies ReadonlyArray<{ - status: VisibilityInput["runs"][number]["status"]; - hidden: string[]; - }>)("keeps the correct transcript rows for $status runs", ({ status, hidden }) => { - const rows = [ - { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, - { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, - { - id: "promoted", - type: "user_message", - inputIntent: "promoted_queued_to_steer", - runId, - nodeId, - }, - { id: "legacy", type: "user_message", runId, nodeId }, - { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "request", type: "run_interrupt_request", runId, nodeId }, - { id: "result", type: "run_interrupt_result", runId, nodeId }, - { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, - { - id: "missing", - type: "user_message", - inputIntent: "queued_turn", - runId: otherRunId, - nodeId, - }, - ] satisfies ReadonlyArray; - const input = { - runs: [{ id: runId, status }], - attempts: [], - items: rows, - } satisfies VisibilityInput; - expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( - [ - "queued", - "start", - "steer", - "promoted", - "legacy", - "assistant", - "request", - "result", - "null", - "missing", - ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), - ); - }); + ])( + "keeps the correct transcript rows for $status runs (started $startedAt)", + ({ status, startedAt, hidden }) => { + const rows = [ + { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, + { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, + { + id: "promoted", + type: "user_message", + inputIntent: "promoted_queued_to_steer", + runId, + nodeId, + }, + { id: "legacy", type: "user_message", runId, nodeId }, + { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "request", type: "run_interrupt_request", runId, nodeId }, + { id: "result", type: "run_interrupt_result", runId, nodeId }, + { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, + { + id: "missing", + type: "user_message", + inputIntent: "queued_turn", + runId: otherRunId, + nodeId, + }, + ] satisfies ReadonlyArray; + const input = { + runs: [ + { + id: runId, + status, + ...(startedAt === undefined ? {} : { startedAt: DateTime.makeUnsafe(startedAt) }), + }, + ], + attempts: [], + items: rows, + } satisfies VisibilityInput; + expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( + [ + "queued", + "start", + "steer", + "promoted", + "legacy", + "assistant", + "request", + "result", + "null", + "missing", + ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), + ); + }, + ); it.each([ { name: "empty history", runs: [], attempts: [] }, diff --git a/packages/shared/src/orchestrationV2Timeline.ts b/packages/shared/src/orchestrationV2Timeline.ts index e651dbfb01653..292a0dfbbb8ab 100644 --- a/packages/shared/src/orchestrationV2Timeline.ts +++ b/packages/shared/src/orchestrationV2Timeline.ts @@ -5,7 +5,8 @@ import type { OrchestrationV2UserMessageInputIntent, } from "@t3tools/contracts"; -type TimelineRun = Pick; +type TimelineRun = Pick & + Partial>; type TimelineRunAttempt = Pick; type TimelineTurnItem = Pick & { readonly inputIntent?: OrchestrationV2UserMessageInputIntent; @@ -38,6 +39,11 @@ function isOrchestrationV2SupersededInterrupt(input: { return !hasMatchingRequest; } +// A run that started received its queued input, even if recovery cancelled it later. +function isHeldRun(run: TimelineRun): boolean { + return run.status === "queued" || (run.status === "cancelled" && run.startedAt == null); +} + export function isOrchestrationV2TurnItemVisible(input: { readonly item: TimelineTurnItem; readonly runs: ReadonlyArray; @@ -53,14 +59,12 @@ export function isOrchestrationV2TurnItemVisible(input: { } // A steer can return to the queue before delivery. Keep its retained item out - // of conversation history until its run starts; cancelled queued inputs stay hidden. + // of conversation history until its run starts; cancelled undelivered inputs stay hidden. if ( item.type === "user_message" && item.inputIntent === "queued_turn" && item.runId !== null && - input.runs.some( - (run) => run.id === item.runId && (run.status === "queued" || run.status === "cancelled"), - ) + input.runs.some((run) => run.id === item.runId && isHeldRun(run)) ) { return false; } @@ -79,8 +83,7 @@ export function createOrchestrationV2TurnItemVisibility(input: { }): (item: TimelineTurnItem) => boolean { const statuses = new Map(); for (const run of input.runs) { - if (run.status === "rolled_back" || run.status === "cancelled" || run.status === "queued") - statuses.set(run.id, run.status); + if (run.status === "rolled_back" || isHeldRun(run)) statuses.set(run.id, run.status); else statuses.delete(run.id); } const supersededRoots = new Map< From 9cf81e2a6e717510708713fa951d368095a1de71 Mon Sep 17 00:00:00 2001 From: fixfon <12512757+fixfon@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:39:47 +0300 Subject: [PATCH 044/288] fix(desktop): annotation Select picks elements inside open shadow roots (#23180) Co-authored-by: Julius Marminge --- apps/desktop/src/preview/PickPreload.ts | 18 +-- apps/desktop/src/preview/PickTarget.test.ts | 121 ++++++++++++++++++++ apps/desktop/src/preview/PickTarget.ts | 22 ++++ 3 files changed, 154 insertions(+), 7 deletions(-) create mode 100644 apps/desktop/src/preview/PickTarget.test.ts create mode 100644 apps/desktop/src/preview/PickTarget.ts diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index c7599d217b1a1..5113617a8f324 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -28,6 +28,7 @@ import { type StrokeGeometry, } from "./AnnotationStroke.ts"; import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts"; +import { pickElementAtPoint } from "./PickTarget.ts"; import { installRecordingCursor } from "./RecordingCursor.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts"; import { @@ -320,13 +321,16 @@ function isAnnotationNode(element: Element): boolean { } function pickFromPoint(clientX: number, clientY: number): Element | null { - for (const candidate of document.elementsFromPoint(clientX, clientY)) { - if (!(candidate instanceof Element)) continue; - if (isAnnotationNode(candidate) || candidate.hasAttribute(INPUT_LAYER_ATTRIBUTE)) continue; - if (candidate === document.documentElement || candidate === document.body) continue; - return candidate; - } - return null; + return pickElementAtPoint( + document, + clientX, + clientY, + (element) => + isAnnotationNode(element) || + element.hasAttribute(INPUT_LAYER_ATTRIBUTE) || + element === document.documentElement || + element === document.body, + ); } function describeRawElement(element: Element): string { diff --git a/apps/desktop/src/preview/PickTarget.test.ts b/apps/desktop/src/preview/PickTarget.test.ts new file mode 100644 index 0000000000000..cb245e9565a1c --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { pickElementAtPoint } from "./PickTarget.ts"; + +// Models the DOM contract the picker relies on: hit-testing covers the whole page, and each +// `elementsFromPoint` retargets the hits against the scope it is called on, like Blink does. +class FakeElement { + shadowRoot: FakeScope | null = null; + readonly label: string; + readonly scope: FakeScope; + + constructor(label: string, scope: FakeScope) { + this.label = label; + this.scope = scope; + scope.members.add(this); + } +} + +class FakeScope { + readonly members = new Set(); + readonly host: FakeElement | null; + private readonly page: FakePage; + + constructor(page: FakePage, host: FakeElement | null) { + this.page = page; + this.host = host; + } + + contains(element: FakeElement): boolean { + return this.members.has(element); + } + + elementsFromPoint(): FakeElement[] { + const elements: FakeElement[] = []; + for (const hit of this.page.hits) { + const element = this.retarget(hit); + if (elements.at(-1) !== element) elements.push(element); + } + if (elements.at(-1) !== this.page.html) elements.push(this.page.html); + return elements; + } + + private retarget(target: FakeElement): FakeElement { + let element = target; + while (element.scope.host && !element.scope.encloses(this)) element = element.scope.host; + return element; + } + + private encloses(scope: FakeScope): boolean { + for (let current: FakeScope | null = scope; current; current = current.host?.scope ?? null) { + if (current === this) return true; + } + return false; + } +} + +class FakePage { + hits: FakeElement[] = []; + readonly overlays = new Set(); + readonly document = new FakeScope(this, null); + readonly html = new FakeElement("html", this.document); + readonly body = new FakeElement("body", this.document); + + attachShadow(host: FakeElement, mode: "open" | "closed"): FakeScope { + const root = new FakeScope(this, host); + if (mode === "open") host.shadowRoot = root; + return root; + } + + pick(): FakeElement | null { + return pickElementAtPoint( + this.document, + 0, + 0, + (element) => this.overlays.has(element) || element === this.html || element === this.body, + ); + } +} + +describe("pickElementAtPoint", () => { + it("picks the element inside an open shadow root instead of its host", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + page.hits = [button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); + + it("falls back to the host when the point misses its shadow content", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + page.attachShadow(host, "open"); + page.hits = [host, page.body, page.html]; + + expect(page.pick()?.label).toBe("shadow-demo"); + }); + + it("keeps a closed shadow root opaque", () => { + const page = new FakePage(); + const outerHost = new FakeElement("outer-host", page.document); + const outerRoot = page.attachShadow(outerHost, "open"); + const closedHost = new FakeElement("closed-host", outerRoot); + const secret = new FakeElement("secret", page.attachShadow(closedHost, "closed")); + page.hits = [secret, closedHost, outerHost, page.body, page.html]; + + expect(page.pick()?.label).toBe("closed-host"); + }); + + it("picks the page element beneath the picker overlay, never the overlay", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + const overlay = new FakeElement("overlay", page.document); + page.overlays.add(overlay); + const toolbar = new FakeElement("toolbar", page.attachShadow(overlay, "closed")); + page.hits = [toolbar, button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); +}); diff --git a/apps/desktop/src/preview/PickTarget.ts b/apps/desktop/src/preview/PickTarget.ts new file mode 100644 index 0000000000000..af689a07bedda --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.ts @@ -0,0 +1,22 @@ +interface PickScope { + elementsFromPoint(x: number, y: number): ReadonlyArray; + contains(node: NoInfer): boolean; +} + +// Document hit-testing retargets shadow content to its host, so descend into open roots. +// ShadowRoot.elementsFromPoint still lists the host and the rest of the page (the overlay +// too), so only the root's own elements count. Closed roots expose no shadowRoot. +export function pickElementAtPoint | null }>( + scope: PickScope, + x: number, + y: number, + isExcluded: (element: E) => boolean, +): E | null { + for (const candidate of scope.elementsFromPoint(x, y)) { + if (!scope.contains(candidate) || isExcluded(candidate)) continue; + const inner = + candidate.shadowRoot && pickElementAtPoint(candidate.shadowRoot, x, y, isExcluded); + return inner ?? candidate; + } + return null; +} From 65cd6446233a8001c8c4f8e06cb4eee987cac0e9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:44:31 -0600 Subject: [PATCH 045/288] fix(web): archive folders with leading or repeated slashes show their names (#41301) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 57 ++++++++++++------- .../web/src/components/files/BinaryViewer.tsx | 27 ++++++--- 2 files changed, 54 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 9316935ba2df0..77e339925c97e 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -238,37 +238,52 @@ describe("bounded binary previews", () => { } }); - it("can leave an archive folder with a repeated separator", async () => { + it("names archive folders whose paths have leading or repeated slashes", async () => { const bytes = new Uint8Array(2048); const write = (offset: number, value: string) => bytes.set(new TextEncoder().encode(value), offset); - write(0, "a//hello.txt"); - write(124, "00000000014\0"); - bytes.fill(32, 148, 156); - write(156, "0"); - write( - 148, - bytes - .subarray(0, 512) - .reduce((sum, byte) => sum + byte, 0) - .toString(8) - .padStart(6, "0") + "\0 ", - ); - write(512, "nested hello"); + const member = (offset: number, name: string, content: string) => { + write(offset, name); + write(offset + 124, content.length.toString(8).padStart(11, "0") + "\0"); + bytes.fill(32, offset + 148, offset + 156); + write(offset + 156, "0"); + write( + offset + 148, + bytes + .subarray(offset, offset + 512) + .reduce((sum, byte) => sum + byte, 0) + .toString(8) + .padStart(6, "0") + "\0 ", + ); + write(offset + 512, content); + }; + member(0, "/a//hello.txt", "nested hello"); + member(1024, "a/hello.txt", "plain hello"); const src = URL.createObjectURL(new Blob([bytes])); try { await using screen = await render(); - const child = () => screen.container.querySelector("tbody button"); - await vi.waitFor(() => expect(child()?.textContent).toBe("a"), 10_000); - await act(() => child()!.click()); - await act(() => child()!.click()); - await vi.waitFor(() => expect(child()?.textContent).toBe("hello.txt")); + const buttons = () => [ + ...screen.container.querySelectorAll("tbody button"), + ]; + const rows = () => buttons().map((button) => button.textContent); + const back = () => + screen.container.querySelector('[aria-label="Back to archive"]')!; + const preview = () => screen.container.querySelector("pre")?.textContent; + await vi.waitFor(() => expect(rows()).toEqual(["a"]), 10_000); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(preview()).toContain("nested hello"), 10_000); + await act(() => back().click()); + await act(() => buttons()[1]!.click()); + await vi.waitFor(() => expect(preview()).toContain("plain hello"), 10_000); + await act(() => back().click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); const parent = () => screen.container.querySelector('[aria-label="Parent folder"]')!; await act(() => parent().click()); - await act(() => parent().click()); expect(parent().disabled).toBe(true); - expect(child()?.textContent).toBe("a"); + expect(rows()).toEqual(["a"]); } finally { URL.revokeObjectURL(src); } diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 0151e9f08c0a7..63a2f119056c1 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -202,19 +202,28 @@ export default function BinaryViewer(props: { }; const children = new Map< string, - { path: string; directory: boolean; size: number; modified: string | null } + { path: string; entryPath: string; directory: boolean; size: number; modified: string | null } >(); for (const item of archive?.entries ?? []) { - if (!item.path.startsWith(folder)) continue; - const rest = item.path.slice(folder.length).replace(/\/$/, ""); + const name = item.path.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"); + if (!name.startsWith(folder)) continue; + const rest = name.slice(folder.length); if (!rest) continue; const slash = rest.indexOf("/"); - const path = slash < 0 ? item.path.replace(/\/$/, "") : `${folder}${rest.slice(0, slash)}`; + const path = slash < 0 ? name : `${folder}${rest.slice(0, slash)}`; const directory = slash >= 0 || item.directory; - const key = `${path}${directory ? "/" : ""}`; + // Files stay keyed by their raw name so `/a.txt` and `a.txt` remain two openable rows. + const key = directory ? `d:${path}` : `f:${item.path}`; const previous = children.get(key); - if (previous) previous.size += item.size; - else children.set(key, { path, directory, size: item.size, modified: item.modified }); + if (previous && directory) previous.size += item.size; + else + children.set(key, { + path, + entryPath: item.path, + directory, + size: item.size, + modified: item.modified, + }); } return (
@@ -347,7 +356,7 @@ export default function BinaryViewer(props: { ) .map((item) => ( @@ -359,7 +368,7 @@ export default function BinaryViewer(props: { else { setSelectedPath(item.path); setEntry(null); - send({ type: "entry", path: item.path }); + send({ type: "entry", path: item.entryPath }); } }} > From fcdaef886a91bd92e824db6b8670be1fbeb838fe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 00:00:57 -0800 Subject: [PATCH 046/288] fix(server): provider updates keep running when the client disconnects (#27261) --- .../providerMaintenanceRunner.test.ts | 210 ++++++++++++------ .../src/provider/providerMaintenanceRunner.ts | 28 ++- apps/server/src/server.ts | 2 + apps/server/src/ws.ts | 9 +- 4 files changed, 166 insertions(+), 83 deletions(-) diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 985347a66e96b..6fec324302fea 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -8,12 +8,14 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -250,27 +252,25 @@ const makeTestRunner = ( }, latestVersions: Layer.Layer = ProviderLatestVersions.layer, ) => - Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe( - Effect.provide( - ProviderMaintenanceRunner.layer.pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ProviderRegistry.ProviderRegistry, registry), - Layer.succeed(ModelManifest.ModelManifest, { - current: Effect.succeed(manifest), - refresh: Effect.succeed(manifest), - forceRefresh: Effect.succeed(manifest), - refreshOnDemand: Effect.succeed(manifest), - refreshInBackground: Effect.void, - }), - latestVersions, - // Layers memoize by reference, so a test that provides the gate shares it. - ProviderInstallationGate.layer, - ), + Layer.build( + ProviderMaintenanceRunner.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ProviderRegistry.ProviderRegistry, registry), + Layer.succeed(ModelManifest.ModelManifest, { + current: Effect.succeed(manifest), + refresh: Effect.succeed(manifest), + forceRefresh: Effect.succeed(manifest), + refreshOnDemand: Effect.succeed(manifest), + refreshInBackground: Effect.void, + }), + latestVersions, + // Layers memoize by reference, so a test that provides the gate shares it. + ProviderInstallationGate.layer, ), ), ), - ); + ).pipe(Effect.map(Context.get(ProviderMaintenanceRunner.ProviderMaintenanceRunner))); function layerFailingLatestLookupAfterFirst() { let lookups = 0; @@ -905,14 +905,15 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("an interrupted update ends failed instead of running forever", () => { + it.effect("an update stopped by server shutdown ends failed instead of running forever", () => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); - const updater = yield* makeTestRunner(registry); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + const serverScope = yield* Scope.make(); + const updater = yield* makeTestRunner(registry).pipe(Scope.provide(serverScope)); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(started); - yield* Fiber.interrupt(update); + yield* Scope.close(serverScope, Exit.void); const last = (yield* Ref.get(updateStatesRef)).at(-1); assert.deepStrictEqual( [last?.status, last?.message], @@ -931,11 +932,12 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("a request dropped while the final state is written still records it", () => { + it.effect("a shutdown while the final state is written still records it", () => { const writing = Deferred.makeUnsafe(); const release = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const serverScope = yield* Scope.make(); const updater = yield* makeTestRunner({ ...registry, setProviderMaintenanceActionState: (input) => @@ -945,13 +947,13 @@ describe("providerMaintenanceRunner", () => { Effect.andThen(registry.setProviderMaintenanceActionState(input)), ) : registry.setProviderMaintenanceActionState(input), - }); + }).pipe(Scope.provide(serverScope)); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(writing); - update.interruptUnsafe(); + const shutdown = yield* Scope.close(serverScope, Exit.void).pipe(Effect.forkScoped); yield* Deferred.succeed(release, undefined); - yield* Fiber.await(update); + yield* Fiber.join(shutdown); assert.strictEqual((yield* Ref.get(updateStatesRef)).at(-1)?.status, "succeeded"); }).pipe( @@ -1150,58 +1152,124 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("finishes a queued update whose caller is interrupted", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider, { + installedVersionAfterUpdate: "1.0.0", + }); + const firstFinished = yield* Deferred.make(); + let blockQueuedState = true; + const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; + const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; + const queuedStateWritten = new Promise((resolve) => { + queuedStateWrittenLatch.resolve = resolve; + }); + const releaseQueuedState = new Promise((resolve) => { + releaseQueuedStateLatch.resolve = resolve; + }); + + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.blockQueuedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + if (input.state?.status === "queued" && blockQueuedState) { + queuedStateWrittenLatch.resolve(); + yield* Effect.promise(() => releaseQueuedState); + } + if (input.state?.status === "succeeded") { + yield* Deferred.succeed(firstFinished, undefined); + } + return providers; + }), + }); + + const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Effect.promise(() => queuedStateWritten); + blockQueuedState = false; + + yield* Fiber.interrupt(first); + releaseQueuedStateLatch.resolve(); + yield* Deferred.await(firstFinished); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ stdout: "updated" })), + ), + ), + ), + ); + it.effect( - "releases the running-provider marker when interrupted after queuing but before the lock run starts", + "keeps the update command running and records its result when the caller is interrupted", () => Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider, { - installedVersionAfterUpdate: "1.0.0", - }); - let blockQueuedState = true; - const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; - const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; - const queuedStateWritten = new Promise((resolve) => { - queuedStateWrittenLatch.resolve = resolve; - }); - const releaseQueuedState = new Promise((resolve) => { - releaseQueuedStateLatch.resolve = resolve; - }); + const kills: Array = []; + const spawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed(spawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode("added 1 package")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); - const updater = yield* makeTestRunner({ - ...registry, - setProviderMaintenanceActionState: Effect.fn( - "providerMaintenanceRunner.test.blockQueuedState", - )(function* (input) { - const providers = yield* registry.setProviderMaintenanceActionState(input); - if (input.state?.status === "queued" && blockQueuedState) { - queuedStateWrittenLatch.resolve(); - yield* Effect.promise(() => releaseQueuedState); - } - return providers; - }), - }); + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.recordFinishedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + const status = input.state?.status; + if (input.state && status !== "queued" && status !== "running") { + yield* Deferred.succeed(finished, input.state); + } + return providers; + }), + }); - const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); - yield* Effect.promise(() => queuedStateWritten); - blockQueuedState = false; + const caller = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkChild); + yield* Deferred.await(spawned); + yield* Fiber.interrupt(caller); - yield* Fiber.interrupt(first); - releaseQueuedStateLatch.resolve(); + assert.deepStrictEqual( + kills, + [], + "interrupting the updateProvider caller killed the running npm install", + ); - const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit); - assert.strictEqual(Exit.isSuccess(second), true); - if (Exit.isSuccess(second)) { - assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("1.0.0"), - layerMockSpawner(() => ({ stdout: "updated" })), + yield* Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)); + const finalState = yield* Deferred.await(finished); + assert.strictEqual(finalState.status, "succeeded"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), ), - ), - ), + ); + }), ); it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 014aa67c26df0..a09bf1ee7dbba 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -13,6 +13,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -323,6 +324,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const serviceScope = yield* Effect.scope; const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const runMaintenanceCommand = ( update: ProviderMaintenanceCommandAction, @@ -685,7 +687,8 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { }, ); - return yield* commandCoordinator + // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller. + const updateFiber = yield* commandCoordinator .withCommandLock({ targetKey, lockKey: update.lockKey, @@ -693,10 +696,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { run: runProviderUpdate(), }) .pipe( - // A dropped request interrupts the update; a "running" state would spin until restart. + // Server shutdown interrupts the update; a "running" state would spin until restart. Effect.onInterrupt(() => Effect.gen(function* () { - // A finished state stays, even if the request drops while it is being written. + // A finished state stays, even if shutdown lands while it is being written. if (yield* Ref.get(settled)) return; yield* setUpdateState( makeUpdateState({ @@ -708,15 +711,18 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ); }).pipe(Effect.ignore), ), - Effect.mapError((error) => - isServerProviderUpdateError(error) - ? new ServerProviderUpdateError({ - provider, - reason: error.reason, - }) - : error, - ), + Effect.forkIn(serviceScope), ); + return yield* Fiber.join(updateFiber).pipe( + Effect.mapError((error) => + isServerProviderUpdateError(error) + ? new ServerProviderUpdateError({ + provider, + reason: error.reason, + }) + : error, + ), + ); }); return ProviderMaintenanceRunner.of({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 68f32f4ecf0a9..499c1e2acc0ca 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -78,6 +78,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ProviderHostLive from "./provider/ProviderHostLive.ts"; +import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; @@ -957,6 +958,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(layerServerSettings), Layer.provide(PreviewAutomationBroker.layer), Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))), + Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(layerCommandReadiness), Layer.provide(ServerHttp.layerBrowserApiCors), Layer.provide(ServerHttp.layerHttpCompression), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ff783eeb57324..b6922b9e90996 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3729,6 +3729,7 @@ export const layer = Layer.unwrap( Effect.gen(function* () { const serverBrowser = yield* ServerBrowser.ServerBrowser; const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; + const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; const npmRelease = yield* NpmRelease.NpmRelease; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; @@ -3820,7 +3821,13 @@ export const layer = Layer.unwrap( Layer.provide(DefectReporter.layer), Layer.provide(AcpRegistrySessions.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), - Layer.provide(ProviderMaintenanceRunner.layer), + // Installs outlive the connection that started them and lock across clients. + Layer.provide( + Layer.succeed( + ProviderMaintenanceRunner.ProviderMaintenanceRunner, + providerMaintenanceRunner, + ), + ), Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. From e20e769b0997adb6b2b3ec26e9562a3c3d55f41a Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 02:01:09 -0600 Subject: [PATCH 047/288] fix(server): reject workflow signals with conflicting destinations (#41312) Co-authored-by: Julius Marminge --- .../mcp/toolkits/workflow/handlers.test.ts | 89 ++++++++++++++----- .../src/mcp/toolkits/workflow/handlers.ts | 7 ++ 2 files changed, 73 insertions(+), 23 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index c036cb8d7e649..77b7036681ad6 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,29 +12,28 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; +const handlersWith = (workflows: Partial) => + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)(workflows), + ), + ), + ); + it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => Effect.gen(function* () { const payloads: Array = []; - const layerDependencies = Layer.mergeAll( - NodeCrypto.layer, - McpToolAccessTestkit.liveThreadsLayer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment:workflow"), - requestNamespace: "client:workflow", - thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, - }), - Layer.mock(Workflows.Workflows)({ - start: (_workflow, input) => - Effect.sync(() => { - payloads.push(input); - return { runId: "run-1" }; - }), - get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), - }), - ); yield* Effect.gen(function* () { const toolkit = yield* WorkflowToolkit; for (const input of [{ input: null }, {}]) { @@ -49,11 +48,55 @@ it.effect("start passes an explicit null payload through and defaults an omitted } }).pipe( Effect.provide( - McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( - Layer.provideMerge(layerDependencies), - ), + handlersWith({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), ), ); expect(payloads).toEqual([null, {}]); }), ); + +it.effect("signal refuses a run destination mixed with a channel destination", () => + Effect.gen(function* () { + const delivered: Array = []; + const results = yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* Effect.forEach( + [ + { runId: "run-1", wait: "review", channel: "other" }, + { workflow: "other", channel: "other", runId: "run-1" }, + { runId: "run-1", wait: "review" }, + ], + (address) => + toolkit + .handle("t3_workflow", { action: "signal", value: { choice: "yes" }, ...address }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ), + ); + }).pipe( + Effect.provide( + handlersWith({ + signal: (address) => + Effect.sync(() => { + delivered.push(address); + return "delivered" as const; + }), + }), + ), + ); + for (const result of results.slice(0, -1)) { + expect(result).toMatchObject({ code: "invalid_request" }); + } + expect(results.at(-1)).toEqual({ delivery: "delivered" }); + expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index b3ccb35f28151..7ebc6ac0cf7a4 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -58,6 +58,13 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { } if (input.action === "signal") { const value = yield* required(input.value, "value"); + const byRun = input.runId !== undefined || input.wait !== undefined; + const byChannel = input.workflow !== undefined || input.channel !== undefined; + if (byRun && byChannel) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or with `workflow` and `channel`, not both.", + ); + } const address = input.runId !== undefined && input.wait !== undefined ? { runId: input.runId, wait: input.wait } From 37b316ac314ebb991c498492b5f1eb036a0eed6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Hu=E1=BB=B3nh=20L=E1=BB=A3i?= Date: Mon, 23 Nov 2026 16:03:59 +0800 Subject: [PATCH 048/288] fix(desktop): declare Apple Events access for Computer Use cleanup (#33869) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- scripts/build-desktop-artifact.test.ts | 7 ++++++- scripts/build-desktop-artifact.ts | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..43e89846bded0 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -592,7 +592,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { ), ); - it.effect("declares Calendar access for hosted commands in macOS builds", () => + it.effect("declares Calendar and Apple Events access for hosted commands in macOS builds", () => Effect.gen(function* () { for (const version of ["0.1.0", "0.1.1-nightly.20261019.1"]) { for (const signed of [false, true]) { @@ -610,6 +610,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { "NSCalendarsUsageDescription", "NSCalendarsFullAccessUsageDescription", "NSCalendarsWriteOnlyAccessUsageDescription", + "NSAppleEventsUsageDescription", ]) { assert.isString(mac.extendInfo[key], `${version}, signed=${signed}: ${key}`); assert.isNotEmpty(mac.extendInfo[key]); @@ -1591,6 +1592,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.include(entitlements, "webcredentials:clerk.example.com"); assert.include(entitlements, "webcredentials:example.clerk.accounts.dev"); assert.include(entitlements, "com.apple.security.cs.allow-jit"); + assert.match( + entitlements, + /com\.apple\.security\.automation\.apple-events<\/key>\s*/u, + ); assert.match(entitlements, /com\.apple\.security\.device\.camera<\/key>\s*/u); assert.match(entitlements, /com\.apple\.security\.device\.audio-input<\/key>\s*/u); assert.notInclude(entitlements, "keychain-access-groups"); diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 746ac826005b3..90cc9e1118235 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -1395,6 +1395,8 @@ ${associatedDomains} com.apple.security.cs.disable-library-validation + com.apple.security.automation.apple-events + + + + +
+${action} +
+
+
+ +${status} + +> Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. + +
+
+
`; + describe("evaluatePullRequestWatch", () => { it.each(["pending", "success"] as const)( "reports a required rebase once with %s CI", @@ -913,6 +932,76 @@ describe("evaluatePullRequestWatch", () => { assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); }); + it("skips CodeRabbit review acknowledgements and wakes once for their outcome edits", () => { + const current = ` +
+✅ Actions performed + +Review triggered. + +
`; + // GitHub's GraphQL API names bots without the "[bot]" suffix that its REST API adds. + for (const [login, acknowledgement] of [ + ["coderabbitai[bot]", codeRabbitReply("Review triggered.")], + ["coderabbitai[bot]", codeRabbitReply("Full review triggered.")], + ["coderabbitai[bot]", current], + ["coderabbitai", current], + ] as const) { + const queued = { + ...remark(login, "2026-10-02T12:06:00Z", acknowledgement), + kind: "issue-comment" as const, + path: null, + }; + const watching = watch({ headSha: "aaaaaaaaaa", wakes: 2 }); + const progress = evaluatePullRequestWatch(watching, detail(), [queued]); + assert.deepEqual(progress.changes, []); + assert.equal(progress.next.remarksThrough, queued.createdAt); + assert.deepEqual(progress.next.remarkIds, [queued.id]); + assert.equal(progress.next.wakes, 2); + assert.isFalse(progress.exhausted); + assert.deepEqual(evaluatePullRequestWatch(progress.next, detail(), [queued]).changes, []); + + const outcome = { + ...queued, + body: codeRabbitReply("Review finished."), + editedAt: "2026-10-02T12:07:00Z", + }; + const finished = evaluatePullRequestWatch(progress.next, detail(), [outcome]); + assert.deepEqual(finished.changes, [{ kind: "remarks", remarks: [outcome] }]); + assert.equal(finished.next.wakes, 3); + assert.deepEqual(evaluatePullRequestWatch(finished.next, detail(), [outcome]).changes, []); + + const late = remark("reviewer", queued.createdAt); + const mixed = evaluatePullRequestWatch(watching, detail(), [queued, late]); + assert.deepEqual(mixed.changes, [{ kind: "remarks", remarks: [late] }]); + assert.deepEqual(mixed.next.remarkIds, [queued.id, late.id]); + } + }); + + it("keeps other replies and outcomes actionable beside CodeRabbit review progress", () => { + const bodies = [ + codeRabbitReply("Full review triggered.", "Actions performed"), + codeRabbitReply("Unable to review.", "Action not completed"), + codeRabbitReply("Here is the answer to your question."), + "Review triggered.", + codeRabbitReply("Review triggered.").replace( + "", + "", + ), + ]; + const comments = [ + ...bodies.map((body, index) => ({ + ...remark("coderabbitai[bot]", "2026-10-02T12:06:00Z", body), + id: `coderabbit-${index}`, + })), + remark("other-bot[bot]", "2026-10-02T12:06:00Z", bodies[0]), + remark("reviewer", "2026-10-02T12:06:00Z", bodies[0]), + ]; + const report = evaluatePullRequestWatch(watch(), detail(), comments); + assert.deepEqual(report.changes, [{ kind: "remarks", remarks: comments.slice(1) }]); + assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); + }); + it("cuts a long remark in the wake message without splitting an emoji", () => { const body = `${"x".repeat(196)}🚀 and more`; const report = evaluatePullRequestWatch(watch(), detail(), [ diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index 5999996ec5dda..e6e0be0f20310 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -42,6 +42,15 @@ const isFailedCheck = (check: PullRequestCheck) => const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; +function isReviewAcknowledgement(remark: PullRequestComment): boolean { + return ( + remark.author?.login.toLowerCase().replace(/\[bot\]$/, "") === "coderabbitai" && + /[\s\S]*?
[^\p{L}<]*Actions? performed<\/summary>\s*(?:
\s*
\s*
\s*)?(?:Full review|Review) triggered\./u.test( + remark.body.slice(0, 1_000), + ) + ); +} + export function evaluatePullRequestWatch( watch: ThreadPullRequestWatch, detail: Pick< @@ -219,7 +228,8 @@ export function evaluatePullRequestWatch( remark.author?.login.toLowerCase() !== own ); }); - if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); + const actionable = fresh.filter((remark) => !isReviewAcknowledgement(remark)); + if (actionable.length > 0) changes.push({ kind: "remarks", remarks: actionable }); const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark)))); const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest); const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!); From c768764bb6c599244b884ddbc53dd0da024eea2d Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 14:25:39 +0200 Subject: [PATCH 095/288] fix(cli): expand ~ in t3 environment link --from (#41430) Co-authored-by: Julius Marminge --- apps/server/src/cli/environment.test.ts | 3 ++- apps/server/src/cli/environment.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/environment.test.ts b/apps/server/src/cli/environment.test.ts index 9ad17441add6e..2fcdc88589e6e 100644 --- a/apps/server/src/cli/environment.test.ts +++ b/apps/server/src/cli/environment.test.ts @@ -5,6 +5,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -101,7 +102,7 @@ it.effect("links a file of environments, reports each line, and fails when one d retry, `${one.url} ${firstCode}\n${two.url} ${yield* codeFor(two)}\n${three.url} never-valid\n`, ); - yield* link(retry); + yield* link("~/retry.txt").pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)); const retried = (yield* reports).at(-1) ?? ""; expect(retried).toContain( `${one.url}: already linked as VM 1 (environment-vm-1), left as it is`, diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index ab55715e721cb..a4b47ebbe8c55 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -29,6 +29,7 @@ import * as PeerLinks from "../peer/PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { expandHomePath } from "../os-jank.ts"; import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -201,7 +202,7 @@ const readLinkBatch = Effect.fn("environment.readLinkBatch")(function* (from: st ); } const fs = yield* FileSystem.FileSystem; - return yield* fs.readFileString(from); + return yield* fs.readFileString(yield* expandHomePath(from)); }); const environmentLinkCommand = Command.make("link", { From 27ecc0fad96609ea1d42f9388541199336c02ae9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 06:31:02 -0600 Subject: [PATCH 096/288] fix(cli): reject incomplete workflow signal addresses locally (#41431) Co-authored-by: Julius Marminge --- apps/server/src/cli/workflow.test.ts | 34 ++++++++++++++++------------ apps/server/src/cli/workflow.ts | 7 ++++++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts index 0c99ca8ee8d21..82b4705e45fa6 100644 --- a/apps/server/src/cli/workflow.test.ts +++ b/apps/server/src/cli/workflow.test.ts @@ -166,21 +166,25 @@ it.effect("reports what the server refused instead of calling it unreachable", ( }), ); -it.effect("signal refuses both addresses at once before reaching the server", () => +it.effect("signal sends only one complete address to the server", () => Effect.gen(function* () { - const { error, calls } = yield* runCli([ - "signal", - "{}", - "--run", - "run-1", - "--wait", - "approve", - "--workflow", - "review", - "--channel", - "pr-1", - ]); - assert.strictEqual(error?._tag, "ThreadUsageError"); - assert.lengthOf(calls, 0); + const byRun = ["--run", "run-1", "--wait", "approve"]; + const byChannel = ["--workflow", "review", "--channel", "pr-1"]; + for (const [address, sent] of [ + [byRun, true], + [byChannel, true], + [[...byRun, ...byChannel], false], + [[], false], + [["--run", "run-1"], false], + [["--wait", "approve"], false], + [["--workflow", "review"], false], + [["--channel", "pr-1"], false], + ] as const) { + const { error, calls } = yield* runCli(["signal", "{}", ...address], () => + Effect.succeed({ structuredContent: { delivery: "delivered" } }), + ); + assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError"); + assert.lengthOf(calls, sent ? 1 : 0); + } }), ); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts index 95a499043c6c6..c02ee63551f88 100644 --- a/apps/server/src/cli/workflow.ts +++ b/apps/server/src/cli/workflow.ts @@ -244,6 +244,13 @@ const signalCommand = Command.make("signal", { "Address a signal with --run and --wait, or with --workflow and --channel, not both.", }); } + const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait); + const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel); + if (!completeRun && !completeChannel) { + return yield* new ThreadUsageError({ + detail: "Address a signal with --run and --wait, or with --workflow and --channel.", + }); + } yield* withThreadTools( { ...flags, json: false }, Effect.fn("cli.workflow.signal")(function* (tools) { From 6ec46a61e60e1bbc60ef48b919d41b124632db7c Mon Sep 17 00:00:00 2001 From: Nirmal Thewarathanthri Date: Mon, 23 Nov 2026 20:43:59 +0800 Subject: [PATCH 097/288] =?UTF-8?q?fix(opencode):=20Usage=20=E2=86=92=20Li?= =?UTF-8?q?mits=20no=20longer=20warns=20when=20no=20Console=20workspace=20?= =?UTF-8?q?is=20signed=20in=20(#41415)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nirmal Thewarathanthri <8257850+nthewara@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/v2/OpenCode2Client.test.ts | 3 +-- packages/provider-opencode/src/server/v2/usageLimits.ts | 8 ++------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index 701ad57fe488a..c08627eccdc00 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -495,8 +495,7 @@ describe("OpenCode2Client usage limits", () => { const result = yield* api.usageLimits("/remote"); if (reason === undefined) assert.strictEqual(result, undefined); else assert.strictEqual(result?.unavailable?.reason, reason); - if ("data" in body && body.data === null) - assert.include(result?.unavailable?.message ?? "", "signed in"); + if (reason === "unsupported") assert.strictEqual(result?.unavailable?.message, undefined); if ("message" in body) assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index bdf678e424692..ea3f141b2100a 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -95,12 +95,8 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu ), }); const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); - if (body.data === null) - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "No OpenCode Console workspace is signed in.", - }); + // OpenCode needs no Console workspace, so its absence is not worth a notice. + if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); const { go, budgets, workspace } = body.data; const usageURL = URL.parse(workspace.usageURL); const externalUsage = From 0db39e6b7c707334ddd5254d16a4486c48eb05d6 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 06:47:12 -0600 Subject: [PATCH 098/288] fix(cli): uninstall removes a script launcher whose target names the home through a symlink (#41435) Co-authored-by: Julius Marminge --- apps/server/src/cli/uninstall.test.ts | 16 ++++++++++++++++ apps/server/src/cli/uninstall.ts | 8 ++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index c22760da53453..7bb1046199c4e 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -200,9 +200,21 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { // recorded launchers: through a symlinked home, and dangling after a prune. const throughAlias = path.join(root, "bin/t3-alias"); const pruned = path.join(root, "bin/t3-pruned"); + const scriptThroughAlias = path.join(scriptDir, "t3-alias"); + const prunedScript = path.join(scriptDir, "t3-pruned"); yield* fs.symlink(root, path.join(root, "alias")); yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias); yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned); + yield* fs.writeFileString( + scriptThroughAlias, + posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")), + { mode: 0o755 }, + ); + yield* fs.writeFileString( + prunedScript, + posixLauncherScript(path.join(versionsDir, "0.9.0/t3")), + { mode: 0o755 }, + ); // Another program inside a version is not a launcher. const sibling = path.join(root, "bin/t3-sibling"); yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling); @@ -216,6 +228,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { pruned, sibling, script, + scriptThroughAlias, + prunedScript, editedScript, path.join(root, "missing"), ].join("\n") + "\n", @@ -226,6 +240,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { throughAlias, pruned, script, + scriptThroughAlias, + prunedScript, ]); } diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index a0d47c7384910..5624e6c2a894c 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -75,7 +75,8 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( const realVersionsDir = yield* fs .realPath(versionsDir) .pipe(Effect.orElseSucceed(() => versionsDir)); - // The link's own text keeps a pruned (dangling) target; the real path sees through a + const scriptTarget = platform === "win32" ? undefined : yield* readPosixLauncherTarget(launcher); + // The link or script text keeps a pruned (dangling) target; the real path sees through a // symlinked T3 home. const targets = platform === "win32" @@ -91,7 +92,10 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( Effect.orElseSucceed(() => undefined), ), yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined)), - yield* readPosixLauncherTarget(launcher), + scriptTarget, + scriptTarget !== undefined + ? yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => undefined)) + : undefined, ]; return targets.some( (target) => From 3ab1ee20bd451eee58c1cbc9d1fd135fe5425045 Mon Sep 17 00:00:00 2001 From: Anthony Mittaz Date: Mon, 23 Nov 2026 23:47:27 +1100 Subject: [PATCH 099/288] fix(server): long setup scripts complete in macOS zsh (#37836) Co-authored-by: Julius Marminge --- .../project/ProjectSetupScriptRunner.test.ts | 21 ++++++++++++------- .../src/project/ProjectSetupScriptRunner.ts | 9 ++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index c495feb4cef66..3827fca09cf74 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -138,7 +138,9 @@ describe("ProjectSetupScriptRunner", () => { const { writes } = yield* setup({ shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", }); - expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("$global:LASTEXITCODE"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -209,9 +211,11 @@ describe("ProjectSetupScriptRunner", () => { it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { - const { writes } = yield* setup(); + const { writes } = yield* setup({ command: "printf '%s\\n' 'setup-ready'\n".repeat(120) }); yield* TestClock.adjust("3 seconds"); - expect(yield* Queue.take(writes)).toContain("vp i"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("setup-ready"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -271,6 +275,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const { writes, outputLines, emit, completion } = yield* setup({ command }); yield* emit({ ...event, type: "output", data: "\x1b[?2004h" }); const submitted = yield* Queue.take(writes); + const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", ""); const cwd = yield* HostProcess.WorkingDirectory; const env = yield* HostProcess.Environment; @@ -281,7 +286,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const handle = yield* spawner.spawn( ChildProcess.make( "/bin/bash", - ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")], + ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")], { cwd, env: { PATH: env.PATH }, @@ -302,6 +307,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { yield* emit({ ...event, type: "closed" }); return { submitted, + shellInput, lines: yield* Queue.clear(outputLines), exitCode: (yield* completion).exitCode, }; @@ -347,9 +353,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup co assert.deepEqual(result.lines, expected); assert.equal(result.exitCode, 0); assert.equal(result.submitted.at(-1), "\r"); - assert.notInclude(result.submitted, "\n"); - // The runner can write before the shell switches the terminal out of canonical mode. - for (const line of result.submitted.slice(0, -1).split("\r")) { + assert.isTrue(result.submitted.startsWith(" \x1b[200~")); + assert.isTrue(result.submitted.endsWith("\x1b[201~\r")); + assert.notInclude(result.submitted.slice(0, -1), "\r"); + for (const line of result.shellInput.slice(0, -1).split("\n")) { assert.isBelow(utf8.encode(line).byteLength, 1_024); } }), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 1c94a3f118757..667aa33c6dcde 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -412,7 +412,7 @@ export const make = Effect.gen(function* () { const seen = activity; yield* Effect.sleep(SHELL_QUIET_FALLBACK); if (activity !== seen) continue; - if (!busy) return "ready" as const; + if (!busy) return "quiet" as const; yield* input.onStartupPrompt; } }); @@ -603,7 +603,12 @@ export const make = Effect.gen(function* () { : terminalManager.write({ threadId: input.threadId, terminalId, - data: projectScriptTerminalInput(commandLine), + // macOS zsh garbles long typed-ahead multiline input; a live line editor takes it as one paste. + data: projectScriptTerminalInput( + shell === "ready" && completionShell === "posix" && commandLine.includes("\r") + ? `\x1b[200~${commandLine.replaceAll("\r", "\n")}\x1b[201~` + : commandLine, + ), }), ), Effect.catchCause((cause) => From c6fe23dd2871126cd189cf197761849e7ef0f91d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 04:52:01 -0800 Subject: [PATCH 100/288] fix(server): preview type sends key events to the page (#41432) --- apps/server/src/preview/ServerBrowser.test.ts | 28 ++++++++ apps/server/src/preview/ServerBrowser.ts | 12 ++-- .../src/preview/ServerBrowserPage.test.ts | 56 ++++++++++++++- apps/server/src/preview/ServerBrowserPage.ts | 68 ++++++++++++++++--- 4 files changed, 149 insertions(+), 15 deletions(-) diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index d8e5f0622241c..f0841ca2556d3 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -1735,6 +1735,34 @@ it.effect( ).pipe(Effect.provide(layer)), ); +it.effect("stops typing long text at the request's deadline and says how far it got", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + page.evaluate.mockImplementation(async () => true as never); + let now = 1_700_000_000_000; + const clock = vi.spyOn(Date, "now").mockImplementation(() => now); + yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore())); + // Each piece of keys takes 10 seconds here: over the request's 5, under the 15-second default. + const type = vi.fn(async (_text: string) => void (now += 10_000)); + Object.assign(page, { keyboard: { type } }); + const failure = yield* broker + .invoke({ + scope, + tabId, + operation: "type", + input: { text: "a".repeat(200) }, + timeoutMs: 5_000, + }) + .pipe(Effect.flip); + expect(failure._tag).toBe("PreviewAutomationTimeoutError"); + expect(failure.message).toMatch(/after 64 of 200 characters/); + expect(type.mock.calls).toEqual([["a".repeat(64)]]); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("reports a pending dialog without evaluating the page and resolves it explicitly", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 9fd94232a5e23..8adba6ba3e478 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -2945,10 +2945,14 @@ const make = Effect.gen(function* () { return recordAction(tab, "upload", () => uploadFiles(tab, input as PreviewAutomationUploadInput), ); - case "type": - return recordAction(tab, "type", () => - ServerBrowserPage.type(tab.page, input as PreviewAutomationTypeInput), - ); + case "type": { + // As for click: typing stops at the broker's deadline instead of running on after the reply. + const typeInput = { + ...(input as PreviewAutomationTypeInput), + timeoutMs: Math.max(1, Math.floor(deadlineMs - performance.now())), + }; + return recordAction(tab, "type", () => ServerBrowserPage.type(tab.page, typeInput)); + } case "press": return recordAction(tab, "press", () => ServerBrowserPage.press(tab.page, input as PreviewAutomationPressInput), diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 9afe924dabc4c..544e4d81d01ab 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -410,6 +410,36 @@ describe("server browser element refs", () => { expect(await inner.inputValue()).toBe(""); }); + it("types into a field that builds its value from keydown, with and without clear", async () => { + await page.setContent( + ``, + ); + const keys = (selector: string) => + page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys); + await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" }); + expect(await keys("#a")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true }); + expect(await keys("#b")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true }); + expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`); + + await page.setContent( + `
`, + ); + await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true }); + expect(await page.locator("#e").inputValue()).toBe("a@b.c"); + await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true }); + expect(await page.locator("#d").inputValue()).toBe("2026-01-31"); + await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true }); + expect(await page.locator("#c").inputValue()).toBe("#ff0000"); + await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true }); + expect(await page.locator("#r").inputValue()).toBe("70"); + await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" }); + await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" }); + expect(await page.locator("#t").inputValue()).toBe("one\ntwo"); + expect(await page.locator("#sent").inputValue()).toBe(""); + }); + it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => { await page.setContent(`
password:
@@ -973,7 +1003,7 @@ describe("server browser type", () => { ({ locator: () => ({ last: () => ({ count: () => new Promise(() => {}) }) }), evaluate: focusAnswer, - keyboard: { insertText: async (text: string) => void typed.push(text) }, + keyboard: { type: async (text: string) => void typed.push(text) }, }) as unknown as Page; it("types into the focused field when Playwright's utility world never answers", async () => { @@ -1010,6 +1040,30 @@ describe("server browser type", () => { detail: { timeoutMs: 300 }, }); expect(typed).toEqual([]); + + // A target whose element is found but whose page then stops answering. + const fill = vi.fn(async () => {}); + const hung = { + locator: () => ({ evaluate: () => new Promise(() => {}), fill }), + keyboard: { type: async (text: string) => void typed.push(text) }, + } as unknown as Page; + void ServerBrowserPage.type(hung, { + locator: "#field", + text: "hello", + clear: true, + timeoutMs: 300, + }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + outcome = "pending"; + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toMatchObject({ + tag: "PreviewAutomationTimeoutError", + detail: { timeoutMs: 300 }, + }); + expect(fill).not.toHaveBeenCalled(); + expect(typed).toEqual([]); } finally { vi.useRealTimers(); } diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index f5eed496da5fe..a633f4328d163 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -941,8 +941,8 @@ const focusTextTarget = (target: FocusCandidate | null) => { return active != null && (active === element || element.contains(active)); }; -// A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. -const focusedTextField = async (page: Page, timeout: number) => { +// Playwright's own timeout covers finding the element, not a page that stops answering the evaluation. +const pageAnswer = async
(answer: Promise, timeout: number) => { let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { timer = setTimeout( @@ -950,29 +950,77 @@ const focusedTextField = async (page: Page, timeout: number) => { reject( new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: `The page did not report its focused element within ${timeout}ms, so no text was typed.`, + message: `The page did not answer within ${timeout}ms, so no text was typed.`, detail: { timeoutMs: timeout }, }), ), timeout, ); }); - return await Promise.race([page.evaluate(focusTextTarget, null), expired]).finally(() => - clearTimeout(timer), + return await Promise.race([answer, expired]).finally(() => clearTimeout(timer)); +}; + +// Serialized into the page's main world, so it must not reference module scope. +const valueOnlyInput = ( + target: FocusCandidate & { + closest(selector: string): { readonly control: FocusCandidate | null } | null; + }, +) => { + // As fill does, a target that is not a control stands for its label's control. + const element = target.tagName === "INPUT" ? target : target.closest("label")?.control; + return ( + element?.tagName === "INPUT" && + ["color", "date", "datetime-local", "month", "range", "time", "week"].includes( + element.type ?? "", + ) ); }; +// Keys reach pages that build their value from keydown. Line breaks stay text: Enter would submit the form. +const typeKeys = async (page: Page, text: string, timeoutMs: number, deadline: number) => { + let typed = 0; + for (const [index, part] of text.split(/([\r\n]+)/u).entries()) { + // Keys cost about a millisecond each, so long text is sent in pieces that stop at the deadline. + const pieces = index % 2 === 1 ? [part] : (part.match(/[^]{1,64}/gu) ?? []); + for (const piece of pieces) { + if (Date.now() >= deadline) { + const reason = `Typing stopped after ${typed} of ${text.length} characters, which the field now holds. Type the rest in another call or raise timeoutMs.`; + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: reason, + detail: { timeoutMs, reason }, + }); + } + if (index % 2 === 1) await page.keyboard.insertText(piece); + else await page.keyboard.type(piece); + typed += piece.length; + } + } +}; + export const type = async (page: Page, input: PreviewAutomationTypeInput) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); if (locator !== null && input.clear) { - await locator.fill(input.text, { timeout }); + // Pickers and sliders take a value such as 2026-01-31 only from fill, and some reject an empty one. + const timeout = remaining(); + if (await pageAnswer(locator.evaluate(valueOnlyInput, undefined, { timeout }), timeout)) { + await locator.fill(input.text, { timeout: remaining() }); + return; + } + // fill follows a label to its control and leaves that control focused for the keys. + await locator.fill("", { timeout: remaining() }); + await typeKeys(page, input.text, timeoutMs, deadline); return; } const focused = locator === null - ? await focusedTextField(page, timeout) - : await locator.evaluate(focusTextTarget, undefined, { timeout }); + ? // A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. + await pageAnswer(page.evaluate(focusTextTarget, null), remaining()) + : await locator.evaluate(focusTextTarget, undefined, { timeout: remaining() }); if (focused !== true) { throw new ServerBrowserOperationError({ tag: "PreviewAutomationTargetNotEditableError", @@ -983,7 +1031,7 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { await page.keyboard.press("ControlOrMeta+A"); await page.keyboard.press("Delete"); } - await page.keyboard.insertText(input.text); + await typeKeys(page, input.text, timeoutMs, deadline); }; export const hover = async ( From e6e863c0452d1d9e103123fc1315729a71eb2998 Mon Sep 17 00:00:00 2001 From: Martin Zeman Date: Mon, 23 Nov 2026 14:03:30 +0100 Subject: [PATCH 101/288] fix(shared): Open in Cursor skips a broken cursor on PATH (#38212) Co-authored-by: abominable-intelligence Co-authored-by: Julius Marminge --- .../src/process/externalLauncher.test.ts | 69 ++++++++++++++++++- packages/shared/src/editor.ts | 25 ++++--- 2 files changed, 81 insertions(+), 13 deletions(-) diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 4246baf39179c..83e140161a499 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -900,6 +900,67 @@ for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12 ); } +// Stand-ins for a `--version` check. The Cursor Agent CLI installs a cursor script that fails +// when no IDE is behind it, and a slow first start stays silent for longer than the check waits. +const scripts = { works: "", fails: "exit 1", stalls: "exec sleep 30" }; +// Each row: title, editor, script first on PATH, extra install, result on darwin, result on linux. +for (const [title, id, first, extra, onDarwin, onLinux = onDarwin] of [ + ["keeps a working cursor on PATH ahead of the bundle", "cursor", "works", "bundle", "cursor"], + ["keeps a cursor that never answers --version", "cursor", "stalls", "none", "cursor"], + ["skips a failing cursor for a later cursor on PATH", "cursor", "fails", "later", "later"], + ["skips a failing cursor for the Cursor bundle", "cursor", "fails", "bundle", "bundle", "none"], + ["rejects a zed that never answers --version", "zed", "stalls", "none", "none"], +] as const) { + for (const platform of ["darwin", "linux"] as const) { + it.effect.skipIf(windowsHost)(`${title} on ${platform}`, () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-check-" }); + const commands = { + cursor: "cursor", + none: undefined, + first: path.join(home, "bin", id), + later: path.join(home, "later-bin", id), + bundle: path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/cursor"), + }; + for (const key of ["first", extra] as const) { + if (key === "none") continue; + yield* fs.makeDirectory(path.dirname(commands[key]), { recursive: true }); + const script = key === "first" ? scripts[first] : scripts.works; + yield* fs.writeFileString(commands[key], `#!/bin/sh\n${script}\n`); + yield* fs.chmod(commands[key], 0o755); + } + const editor = EDITORS.find((editor) => editor.id === id)!; + const env = { HOME: home, PATH: `${home}/bin:${home}/later-bin` }; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const started = yield* Deferred.make(); + // Signal that the `--version` check has a running process. + const signal = Deferred.succeed(started, undefined); + const [resolved] = yield* Effect.all( + [ + resolveEditorCommand(editor, env).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(Path.Path, withSystemBin(path, path.join(home, "system-bin"))), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((cmd) => spawner.spawn(cmd).pipe(Effect.tap(signal))), + ), + ), + // The check runs on the test clock, so its timeout passes only when the clock moves. + first === "stalls" + ? Deferred.await(started).pipe(Effect.andThen(TestClock.adjust("2 seconds"))) + : Effect.void, + ], + { concurrency: "unbounded" }, + ); + const expected = commands[platform === "darwin" ? onDarwin : onLinux]; + assert.equal(Option.getOrUndefined(resolved)?.command, expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + } +} + for (const { layout, pathNames, fallbackNames, expected } of [ { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" }, { @@ -959,14 +1020,16 @@ for (const { layout, pathNames, fallbackNames, expected } of [ ); } -// Linux editor discovery also probes fixed system directories; tests point them at a temp -// directory so an editor installed on the host cannot satisfy the lookup. +// Editor discovery also probes fixed system directories (Linux bin folders, macOS /Applications); +// tests point them at a temp directory so an editor installed on the host cannot satisfy the lookup. const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({ ...path, join: (...parts) => path.join( ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ["/Applications", "/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) + ? systemBin + : part, ), ), }); diff --git a/packages/shared/src/editor.ts b/packages/shared/src/editor.ts index 902e06bd7f986..544da3d67e98b 100644 --- a/packages/shared/src/editor.ts +++ b/packages/shared/src/editor.ts @@ -37,9 +37,10 @@ const isVersionedBundle = (entry: string, name: string) => { return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length)); }; -// OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting. -const isZedEditor = Effect.fn("editor.isZedEditor")( - function* (command: string) { +// OpenZFS's event daemon is also named zed, and the Cursor Agent CLI installs a cursor script +// that fails without an IDE behind it; both reject `--version` instead of starting. +const isEditorCommand = Effect.fn("editor.isEditorCommand")( + function* (command: string, isZed: boolean) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const handle = yield* spawner.spawn( ChildProcess.make(command, ["--version"], { @@ -52,10 +53,12 @@ const isZedEditor = Effect.fn("editor.isZedEditor")( [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode], { concurrency: "unbounded" }, ); - return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed"); + return exitCode === 0 && (!isZed || Option.getOrElse(stdout, () => "").startsWith("Zed")); }, Effect.scoped, - Effect.timeout("2 seconds"), + // A slow first start after an update must not hide a working Cursor. + (probe, _command, isZed) => + Effect.timeoutOrElse(probe, { duration: "2 seconds", orElse: () => Effect.succeed(!isZed) }), Effect.catchCause(() => Effect.succeed(false)), ); @@ -69,6 +72,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable. const preferBundle = platform === "darwin" && editor.id === "zed"; const preferZeditor = platform === "linux" && editor.id === "zed"; + const probeCursor = editor.id === "cursor" && platform !== "win32"; if (platform === "win32" && editor.id === "zed") { const isStable = (resolved: string) => !isPrereleaseZedPath(resolved); let firstCommand: string | undefined; @@ -83,7 +87,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun if (firstCommand === undefined && matches.length > 0) firstCommand = command; } if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs }); - } else if (!preferBundle && !preferZeditor) { + } else if (!preferBundle && !preferZeditor && !probeCursor) { for (const command of editor.commands) { if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs }); } @@ -95,7 +99,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const names = installNames[editor.id] ?? [editor.label]; const command = editor.commands[0]; const jetbrains = editor.launchStyle === "line-column"; - const candidates: string[] = []; + const candidates: string[] = probeCursor ? [...editor.commands] : []; let toolbox: { dir: string; suffix: string } | undefined; if (platform === "darwin") { @@ -216,14 +220,15 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const probeZed = editor.id === "zed" && platform !== "win32"; const rejected = new Set(); for (const candidate of candidates) { - // OpenZFS zed can shadow the editor's zed in an earlier PATH entry. + // An earlier PATH entry can hold OpenZFS zed or the Cursor Agent CLI's cursor script. const matches = - probeZed && candidate === "zed" + (probeZed || probeCursor) && candidate === command ? yield* resolveCommandPaths(candidate, { env, until: () => false }) : [yield* resolveCommandPath(candidate, { env })]; for (const resolved of matches) { if (resolved === null || rejected.has(resolved)) continue; - if (probeZed && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) { + const probed = probeCursor || (probeZed && path.basename(candidate) === "zed"); + if (probed && !(yield* isEditorCommand(resolved, probeZed))) { rejected.add(resolved); continue; } From 5e128576b52e16a528650afea0e0c02460d12011 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 15:03:42 +0200 Subject: [PATCH 102/288] fix(cli): expand ~ in t3 policy templates --policy (#41438) Co-authored-by: Julius Marminge --- apps/server/src/cli/policy.test.ts | 37 +++++++++++++++++++++++++++--- apps/server/src/cli/policy.ts | 6 +++-- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index 7066cceebcd0f..d06998ff42882 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -1,12 +1,16 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { Command } from "effect/cli"; +import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { makePersistedServerRuntimeState, @@ -16,7 +20,7 @@ import { describeRunningServer } from "./policy.ts"; const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState)); -it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { it.effect("tells whether the running server loaded the installed policy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -53,5 +57,32 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => assert.include(yield* running(null, null), "runs without a policy, as installed"); assert.include(yield* running(undefined), "does not report which policy it loaded"); }), - ), -); + ); + + it.effect("templates reads a ~/ --policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-templates-" }); + yield* fs.writeFileString( + path.join(home, "policy.json"), + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "policy", + "templates", + home, + "--policy=~/policy.json", + ]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include( + yield* fs.readFileString(path.join(home, "macos", "t3code.mobileconfig")), + "Tilde Corp", + ); + }), + ); +}); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index dafc5352166f0..c48e2bc535a6f 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -13,6 +13,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { listManageableSettings } from "../policy/managedSettings.ts"; import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts"; +import { expandHomePath } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -132,13 +133,14 @@ const templatesCommand = Command.make("templates", { const path = yield* Path.Path; let document = SAMPLE_POLICY; if (Option.isSome(policy)) { - if (!(yield* fs.exists(policy.value))) { + const file = yield* expandHomePath(policy.value); + if (!(yield* fs.exists(file))) { return yield* new CliError.UserError({ cause: policy.value, userMessage: `No policy file at ${policy.value}.`, }); } - const loaded = (yield* ManagedPolicy.load(policy.value)).document; + const loaded = (yield* ManagedPolicy.load(file)).document; if (loaded !== undefined) document = loaded; } const random = yield* SecureRandom.SecureRandom; From 43115666546509f4ea2a804773a6f47715dcc353 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 14:15:34 +0100 Subject: [PATCH 103/288] fix(server): read relocated shared strings in XLSX attachments (#41441) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 18 +++++++++++------- .../src/provider/userInputAttachments.test.ts | 4 ++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index cc675a539591d..a381ede3cc138 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -631,7 +631,7 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.TargetMode !== "External") - .map((rel) => [rel.attrs.Id, rel.attrs.Target]), + .map((rel) => [rel.attrs.Id, rel.attrs]), ); if (extension === ".docx") { // The package relationship names the main part; Word for the web saves word/document2.xml. @@ -682,14 +682,18 @@ async function* document(path: string, extension: string): AsyncGenerator + rel.Type?.endsWith("/sharedStrings"), + )?.Target; + const sharedPath = sharedTarget + ? NodePath.posix.resolve("/xl", sharedTarget).slice(1) + : "xl/sharedStrings.xml"; + const strings = files.has(sharedPath) ? [...all(read(sharedPath), "si")] : []; + const populatedStrings = strings.map(hasCellText); for (const sheet of all(workbook, "sheet")) { yield `\n## Sheet: ${sheet.attrs.name}\n`; - const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id); + const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target; if (!target) { skip(`sheet relationship ${sheet.attrs.name}`); continue; @@ -764,7 +768,7 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id); + const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id)?.Target; if (!target) { skip(`slide relationship ${index}`); continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 640a491af0bc0..e81c404c4aef1 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -933,8 +933,8 @@ describe("question answer paths", () => { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', - "xl/sharedStrings.xml": "Lantern", + '', + "catalog/items.xml": "Lantern", "xl/styles.xml": '', "xl/worksheets/second.xml": From 2bc7878fff064f9d874bf3d8584f1bd1b20b2879 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 05:17:03 -0800 Subject: [PATCH 104/288] fix(server): import Claude sessions whose first prompt carries a large image (#41446) --- apps/server/src/project/AgentSessionJson.ts | 14 ++- .../src/project/AgentSessionScanner.test.ts | 57 +++++++++++ .../server/src/project/AgentSessionScanner.ts | 97 ++++++++++++++----- 3 files changed, 140 insertions(+), 28 deletions(-) diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index c9dc6baa5f5e6..35b2ac9fad1b0 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -49,7 +49,11 @@ export class TranscriptJsonLimitError extends Schema.TaggedError void, selectPath: (path: JsonPath) => boolean, - options?: { readonly maxDepth?: number }, + options?: { + readonly maxDepth?: number; + // Reports each selected top-level string field as soon as it ends, before the record does. + readonly onTopLevelString?: (key: string, value: string) => void; + }, ) { // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator. const { jsonParser } = StreamJson as typeof StreamJson & { @@ -133,7 +137,13 @@ export function createTranscriptJsonReader( return; case "endString": case "endNumber": - if (selectedValue) assemble(token); + if (selectedValue) { + const parent = stack[0]; + if (token.name === "endString" && stack.length === 1 && typeof parent?.key === "string") { + options?.onTopLevelString?.(parent.key, value); + } + assemble(token); + } endValue(); return; case "nullValue": diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index fc76fc150a1d2..09a7a396a294f 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2327,6 +2327,63 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a Claude session whose first prompt carries an image over 1 MiB", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-large-image-claude-"); + const codexHomePath = yield* makeTempDir("t3code-large-image-codex-"); + const workspace = yield* makeTempDir("t3code-large-image-workspace-"); + const sessionId = "large-image-session"; + const contents = [ + { type: "queue-operation", operation: "enqueue", sessionId }, + { type: "queue-operation", operation: "dequeue", sessionId }, + { + type: "user", + cwd: workspace, + sessionId, + timestamp: "2026-08-24T10:00:00.000Z", + message: { + role: "user", + content: [ + { type: "text", text: "Look at this screenshot" }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "A".repeat(1_100 * 1024), + }, + }, + ], + }, + }, + { + type: "assistant", + sessionId, + timestamp: "2026-08-24T10:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + }, + ] + .map((record) => encodeTranscriptRecord(record)) + .join("\n"); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-large-image", `${sessionId}.jsonl`), + contents, + mtimeMs: nowMs - 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(threads.map((thread) => thread.providerSessionId)).toEqual([sessionId]); + }), + ); + it.effect("imports every transcript that fits the per-file record limit", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 9bd4b5cebd276..b9029b8746b46 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -169,6 +169,17 @@ const decodePiEntryLinks = Schema.decodeUnknownOption( }), ); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); +// Only the fields extractCwd reads, so a cwd record carrying a large image stays small in memory. +const selectCwdPath = createTranscriptJsonSelector( + Schema.Struct({ + cwd: Schema.String, + type: Schema.String, + payload: Schema.Struct({ + cwd: Schema.String, + source: Schema.Struct({ subagent: Schema.Null, subAgent: Schema.Null }), + }), + }), +); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( Schema.Struct({ @@ -832,13 +843,7 @@ function isT3ManagedWorktree( } // false stops metadata scanning for an excluded rollout, even if later records contain a cwd. -function extractCwd(line: string, source: AgentSessionSource): string | null | false { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - return null; - } +function extractCwd(parsed: unknown, source: AgentSessionSource): string | null | false { if (typeof parsed !== "object" || parsed === null) return null; const record = parsed as Record; @@ -1220,11 +1225,28 @@ export const make = Effect.gen(function* () { const size = isCompressedTranscript(transcript.filePath) ? Number.POSITIVE_INFINITY : transcript.identity.size; - const decoder = new TextDecoder(); - let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); + let selectedBytes = 0; + const reserveSelected = (bytes: number) => { + selectedBytes += bytes; + if (selectedBytes > MAX_TRANSCRIPT_SCAN_BYTES) { + throw new TranscriptJsonLimitError({ + message: "Transcript cwd fields exceed the scan limit", + }); + } + }; + // Claude writes cwd before message, so a record with a large image need not be read to its end. + let topLevelCwd: string | null = null; + const createReader = () => + createTranscriptJsonReader(reserveSelected, selectCwdPath, { + onTopLevelString: (key, value) => { + if (key === "cwd" && value.trim().length > 0) topLevelCwd ??= value; + }, + }); + let reader = createReader(); + let decoder = new TextDecoder(); + let recordStarted = false; const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1237,13 +1259,43 @@ export const make = Effect.gen(function* () { budget.recordsRemaining -= 1; return true; }; - const readLastRecord = () => { - const record = remaining + decoder.decode(); - return record.length === 0 || !reserveRecord() - ? null - : extractCwd(record.trim(), source); + const finishRecord = () => { + reader.write(decoder.decode()); + const value = reader.finish(); + reader = createReader(); + decoder = new TextDecoder(); + recordStarted = false; + selectedBytes = 0; + return extractCwd(value, source); }; + const scanChunk = (chunk: Uint8Array): string | false | null | undefined => { + let start = 0; + while (start < chunk.byteLength) { + const newline = chunk.indexOf(10, start); + const end = newline === -1 ? chunk.byteLength : newline; + if (end > start) { + recordStarted = true; + reader.write(decoder.decode(chunk.subarray(start, end), { stream: true })); + if (topLevelCwd !== null) return reserveRecord() ? topLevelCwd : null; + } + if (newline === -1) return undefined; + if (!reserveRecord()) return null; + const cwd = finishRecord(); + if (cwd !== null) return cwd; + start = newline + 1; + } + return undefined; + }; + const parse = (f: () => A) => + Effect.try({ + try: f, + catch: (cause) => + new TranscriptParseError({ filePath: transcript.filePath, cause }), + }); + const readLastRecord = () => + !recordStarted || !reserveRecord() ? null : finishRecord(); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); while (bytesRead < maxBytes) { if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) { budget.truncated = true; @@ -1258,26 +1310,19 @@ export const make = Effect.gen(function* () { budget.bytesRemaining -= readSize; const next = yield* readChunk(readSize); if (Option.isNone(next)) { - return readLastRecord(); + return yield* parse(readLastRecord); } bytesRead += next.value.byteLength; - remaining += decoder.decode(next.value, { stream: true }); - const lines = remaining.split("\n"); - remaining = lines.pop() ?? ""; - - for (const line of lines) { - if (!reserveRecord()) return null; - const cwd = extractCwd(line.trim(), source); - if (cwd !== null) return cwd; - } + const result = yield* parse(() => scanChunk(next.value)); + if (result !== undefined) return result; } if (bytesRead < size) { budget.truncated = true; return null; } - return readLastRecord(); + return yield* parse(readLastRecord); }), ), ), From d1a6c35f7382beead7fb3125e530baf50a60786d Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 14:42:29 +0100 Subject: [PATCH 105/288] fix(server): keep PowerPoint slides with alternate relationship prefixes (#41454) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 17 ++++++++++++++++- .../src/provider/userInputAttachments.test.ts | 4 +++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index a381ede3cc138..47e9b2a57f107 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -149,6 +149,20 @@ function xml(source: string, extension: string): XmlNode { const children = (node: XmlNode | undefined) => node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; +function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) { + for (const [name, value] of Object.entries(slide.attrs)) { + if (!name.endsWith(":id")) continue; + const binding = `xmlns:${name.slice(0, -3)}`; + const namespace = slide.attrs[binding] ?? inheritedAttributes[binding]; + if ( + namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" || + namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships" + ) + return value; + } + return slide.attrs["r:id"] ?? slide.attrs.id; +} + function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean { // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. // Keep one when no Choice carries text, such as a chart with a VML caption. @@ -765,10 +779,11 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst"); + const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs }; let index = 0; for (const slide of children(slideList).filter((node) => node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id)?.Target; + const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target; if (!target) { skip(`slide relationship ${index}`); continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index e81c404c4aef1..67c4b1f785b1f 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1021,7 +1021,9 @@ describe("question answer paths", () => { "ppt/presentation.xml": ` - + + + From 06f513d50fe926a04b77a0b4d76f613adb32b717 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:01:45 -0800 Subject: [PATCH 106/288] fix(server): another agent's queued message no longer holds back an auto send (#41461) --- .../src/orchestration-v2/Orchestrator.ts | 9 +++- .../SteeringCompletion.integration.test.ts | 50 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b95f618d8c1df..6c499c3ea32a7 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7571,7 +7571,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // An agent's automatic send must not overtake an earlier agent message still queued + // An agent's automatic send must not overtake its own earlier message still queued // (e.g. behind /compact), or the agent receives them out of send order. if ( command.deliveryIntent === "auto" && @@ -7588,7 +7588,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRuns.map((run) => run.userMessageId), ) .pipe(mapDispatchError(command)); - if ([...queuedMessages.values()].some((message) => message.createdBy === "agent")) { + if ( + [...queuedMessages.values()].some( + (message) => + message.createdBy === "agent" && message.senderThreadId === command.senderThreadId, + ) + ) { dispatchMode = { type: "queue_after_active" }; } } diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index d199eea71440b..229fb66ff8791 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1920,6 +1920,56 @@ it.effect("delivers agent messages queued behind /compact before a later one ste }), ); +// regression: #41455 one sender's queued message holds back another sender's automatic steer +it.effect("an agent's automatic send steers past another sender's queued message", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "agent-steer-past-other-sender", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const active = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "running", + )!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-first"), + threadId, + messageId: MessageId.make("message:queued-first"), + text: "queued first", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-a"), + }); + yield* worker.drain(); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-urgent"), + threadId, + messageId: MessageId.make("message:urgent"), + text: "urgent", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: active.id }, + deliveryIntent: "auto", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-c"), + }); + yield* worker.drain(); + + assert.lengthOf(started, 1); + assert.deepEqual( + steered.map((text) => text.split("\n").at(-1)), + ["urgent"], + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #33454 a steer that restarts a completion wake run left its cohort claimed forever const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( harness: Pick< From c977a70fd63be83281fb637ff2a502721f9d6ffd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:19:57 -0800 Subject: [PATCH 107/288] feat(scripts): server metrics record machine load and derive noise floors from A/A runs (#41370) Co-authored-by: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 292 ++++++++++++++++++++++++++----- scripts/server-metrics.test.ts | 156 ++++++++++++++++- scripts/server-metrics.ts | 170 +++++++++++++++++- 3 files changed, 565 insertions(+), 53 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c11cfca1589a7..0cd34b23935e9 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -39,8 +39,19 @@ const Soak = Schema.Struct({ rssMBPerHour: Schema.Number, }); +const MachineState = Schema.Struct({ + /** The highest 1-minute load average read through the run; none on Windows. */ + load1: Schema.NullOr(Schema.Number), + /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */ + otherCpuCores: Schema.NullOr(Schema.Number), + minutes: Schema.Number, +}); +export type MachineState = typeof MachineState.Type; + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ + /** What else the machine was doing during the pass; never compared, only warned about. */ + machine: Schema.optional(MachineState), startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), rest: Schema.optional(Window), firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), @@ -202,20 +213,103 @@ export function flatten(measured: Measured): Map { return values; } -function noiseFloor(metric: string) { - if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; - if (metric.startsWith("soak.")) return 20; - if (metric.endsWith("cpuPct")) return 1; - if (metric.endsWith("wakeupsPerSec")) return 20; - if (metric.endsWith("MB")) return 15; - if (metric.endsWith("KB")) return 20; - if (metric.includes(".shellMs.") || metric.includes(".openMs.")) return 50; - if (metric.endsWith("loopDelayP50Ms")) return 2; - if (metric.endsWith("loopDelayP99Ms")) return 5; - if (metric.endsWith("loopDelayMaxMs")) return 20; - if (metric.endsWith("gcPauseMs")) return 10; - if (metric.endsWith("gcCount")) return 20; - return 300; +/** + * How far a metric moves between runs of the same commit, and whether it moves little enough to + * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see + * docs/internals/performance-regressions.md for the runs these came from. + */ +export interface NoiseRule { + readonly pattern: RegExp; + /** Absolute change a metric must clear on top of the relative threshold. */ + readonly floor: number; + /** False for metrics an A/A run moves too far to gate on: shown, never counted. */ + readonly gate: boolean; +} + +/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */ +const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false }); + +// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the +// agent scope, rounded up and taking the larger of the two. +// busy and soak had no A/A run and keep the earlier floors. +export const NOISE_RULES: ReadonlyArray = [ + informational(/loopDelayP50Ms$/), + informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), + informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), + informational(/^(streaming|pipeline)\.gcPauseMs$/), + informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), + informational(/^scaling\.(cpuPct|wakeups)PerThread$/), + informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), + informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), + { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^soak\./, floor: 20, gate: true }, + { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, + { pattern: /^firstWord\./, floor: 600, gate: true }, + { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, + { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, + { pattern: /^clients\.storm\.resubscribedMs$/, floor: 200, gate: true }, + { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, + { pattern: /cpuPct$/, floor: 3.5, gate: true }, + { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 110, gate: true }, + { pattern: /rssPeakMB$/, floor: 16, gate: true }, + { pattern: /rssMB$/, floor: 4, gate: true }, + { pattern: /heapAfterGcMB$/, floor: 1, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /KB$/, floor: 20, gate: true }, + { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 3, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 22, gate: true }, + { pattern: /gcPauseMs$/, floor: 55, gate: true }, + { pattern: /gcCount$/, floor: 6, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + +export function noiseRule(metric: string, rules: ReadonlyArray = NOISE_RULES) { + return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; +} + +/** Fields that describe a run rather than measure it. */ +const isMetric = (metric: string) => + !( + metric === "soak.minutes" || + metric.startsWith("machine.") || + metric.endsWith("loopSamples") || + metric === "busy.projects" || + metric === "busy.ballastMB" || + metric.endsWith(".clients") || + metric.endsWith(".threads") || + metric === "busy.largeThread.messages" || + metric.startsWith("scaling.points") + ); + +/** + * A run is loaded when other node, T3 and agent processes kept this share of the cores busy, or, + * where that is unknown, when the 1-minute load passed this much per CPU. The load counts the + * run's own agents too, so it is only the fallback. + */ +export const HEAVY_LOAD_PER_CPU = 0.75; +export const HEAVY_OTHER_CPU_SHARE = 0.25; + +/** One line per side whose runs shared the machine with heavy load, so its numbers are suspect. */ +export function loadWarnings(side: string, metrics: ServerMetrics) { + const cpus = typeof metrics.meta.cpus === "number" ? metrics.meta.cpus : null; + if (cpus === null) return []; + const loaded = metrics.runs.flatMap(({ machine }) => + machine && + (machine.otherCpuCores === null + ? (machine.load1 ?? 0) >= cpus * HEAVY_LOAD_PER_CPU + : machine.otherCpuCores >= cpus * HEAVY_OTHER_CPU_SHARE) + ? [machine] + : [], + ); + if (loaded.length === 0) return []; + const worstLoad = Math.max(...loaded.map(({ load1 }) => load1 ?? 0)); + const worstOther = Math.max(...loaded.map(({ otherCpuCores }) => otherCpuCores ?? 0)); + return [ + `${side} ran under heavy load in ${loaded.length} of ${metrics.runs.length} runs (load up to ${worstLoad} on ${cpus} CPUs, other node/T3/agent processes up to ${worstOther} cores); rerun on a quieter machine before trusting a change`, + ]; } const median = (values: ReadonlyArray) => { @@ -241,16 +335,133 @@ export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyA return [differences[49]!, differences[1_949]!] as const; } -export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const collect = (metrics: ServerMetrics) => { - const values = new Map(); - for (const run of metrics.runs) { - for (const [metric, value] of flatten(run)) { - values.set(metric, [...(values.get(metric) ?? []), value]); - } +/** + * False for a wakeup count where only one side had the delay sampler: wakeups include the + * sampler's only when `loopSamples` sits beside them, so the two measured different things. The + * per-thread fit comes from the quiet windows, so it follows their method. + */ +function sameWakeupMethod( + metric: string, + a: ReadonlyMap, + b: ReadonlyMap, +) { + const window = + metric === "scaling.wakeupsPerThread" + ? "quiet." + : metric.endsWith("wakeupsPerSec") + ? metric.slice(0, -"wakeupsPerSec".length) + : ""; + return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`); +} + +/** CPU seconds spent between two reads keyed by pid and start time; a process that exited is lost. */ +export function competingBetween( + before: ReadonlyMap, + after: ReadonlyMap, +) { + return [...after].reduce((total, [key, seconds]) => total + seconds - (before.get(key) ?? 0), 0); +} + +/** Why a directory is not an A/A pair: its files must record one and the same commit. */ +export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) { + const commits = [a.meta.commit, b.meta.commit]; + if (commits.some((commit) => typeof commit !== "string" || commit === "")) { + return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`; + } + return commits[0] === commits[1] + ? undefined + : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`; +} + +/** Every metric's values across a file's runs. */ +const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); } - return values; - }; + } + return values; +}; + +/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */ +const ceilSignificant = (value: number) => { + if (value <= 0) return 0; + const step = 10 ** (Math.floor(Math.log10(value)) - 1); + return round(Math.ceil(value / step) * step, 6); +}; + +/** An A/A interval wider than this share of a metric's median makes it informational. */ +export const NOISY_SHARE = 0.5; + +export interface NoiseRow { + readonly metric: string; + readonly median: number; + /** The widest half-width of an A/A pair's 95% interval of the median difference. */ + readonly halfWidth: number; + /** The largest |median(A) - median(B)| over the A/A pairs. */ + readonly aaDifference: number; + readonly floor: number; + readonly suggestedFloor: number; + readonly gate: boolean; + readonly suggestedGate: boolean; +} + +/** + * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The + * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far + * an A/A interval must miss zero to flag. It is an estimate, not a bound. + */ +export function noiseReport( + pairs: ReadonlyArray, + rules: ReadonlyArray = NOISE_RULES, +) { + const found = new Map(); + for (const [before, after] of pairs) { + const a = collect(before); + const b = collect(after); + for (const [metric, x] of a) { + const y = b.get(metric); + if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue; + const [low, high] = bootstrapMedianDifference(x, y); + const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 }; + entry.medians.push(median([...x, ...y])); + entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2); + entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x))); + found.set(metric, entry); + } + } + const rows: NoiseRow[] = [...found].map(([metric, entry]) => { + const middle = median(entry.medians); + const rule = noiseRule(metric, rules); + return { + metric, + median: round(middle, 2), + halfWidth: round(entry.halfWidth, 2), + aaDifference: round(entry.aaDifference, 2), + floor: rule.floor, + suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)), + gate: rule.gate, + suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE, + }; + }); + const lines = [ + "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |", + "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", + ...rows.map( + (row) => + `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, + ), + ]; + return { rows, table: lines.join("\n") }; +} + +export function compareMetrics( + before: ServerMetrics, + after: ServerMetrics, + threshold = 10, + rules: ReadonlyArray = NOISE_RULES, +) { const a = collect(before); const b = collect(after); const lines = [ @@ -264,18 +475,9 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const regressed: string[] = []; const improved: string[] = []; let compared = 0; + const informational: string[] = []; for (const metric of new Set([...a.keys(), ...b.keys()])) { - if ( - metric === "soak.minutes" || - metric.endsWith("loopSamples") || - metric === "busy.projects" || - metric === "busy.ballastMB" || - metric === "clients.storm.clients" || - metric === "busy.largeThread.messages" || - metric.startsWith("scaling.points") - ) { - continue; - } + if (!isMetric(metric)) continue; const x = a.get(metric); const y = b.get(metric); if (!x || !y) { @@ -285,13 +487,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file // from before the sampler and one from after measured different things. The per-thread fit // comes from the quiet windows. - const window = - metric === "scaling.wakeupsPerThread" - ? "quiet." - : metric.endsWith("wakeupsPerSec") - ? metric.slice(0, -"wakeupsPerSec".length) - : ""; - if (window && a.has(`${window}loopSamples`) !== b.has(`${window}loopSamples`)) { + if (!sameWakeupMethod(metric, a, b)) { lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`); continue; } @@ -299,12 +495,15 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const mx = median(x); const my = median(y); // A change counts only past both the relative threshold and the absolute noise floor. - const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const rule = noiseRule(metric, rules); + const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; - if (verdict === "worse") regressed.push(metric); - if (verdict === "better") improved.push(metric); + const moved = low > limit ? "worse" : high < -limit ? "better" : ""; + if (moved && !rule.gate) informational.push(metric); + else if (moved === "worse") regressed.push(metric); + else if (moved === "better") improved.push(metric); + const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy"; const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; const shown = Number.isFinite(percent) ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` @@ -314,7 +513,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, ); } - return { table: lines.join("\n"), regressed, improved, compared }; + const warnings = [...loadWarnings("before", before), ...loadWarnings("after", after)]; + return { table: lines.join("\n"), regressed, improved, informational, compared, warnings }; } const CallFrame = Schema.Struct({ diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 760c850dbbbea..de3237d3c0d23 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,9 +3,13 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + competingBetween, activityRenewalMissed, heapGrowth, + loadWarnings, nextActivityReport, + noiseReport, + noisePairProblem, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -43,6 +47,17 @@ const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; const cpuRuns = (...values: number[]) => quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); +// Fixed floors, so these cases test how compare gates rather than the calibrated table. +const gatedRules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, + { pattern: /gcPauseMs$/, floor: 10, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + describe("compareMetrics", () => { it.each([ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], @@ -60,7 +75,12 @@ describe("compareMetrics", () => { ["quiet.rssPeakMB"], ], ])("one run each: %s", (_name, change, regressed, improved) => { - const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + const result = compareMetrics( + quietRuns(base), + quietRuns({ ...base, ...change }), + 10, + gatedRules, + ); expect(result.regressed).toEqual(regressed); expect(result.improved).toEqual(improved); }); @@ -75,10 +95,10 @@ describe("compareMetrics", () => { it("flags repeated runs only when the whole interval clears the limit", () => { const steady = cpuRuns(26.1, 27.4, 25.8); const fixed = cpuRuns(2.2, 2.5, 2.1); - expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); - expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + expect(compareMetrics(steady, fixed, 10, gatedRules).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady, 10, gatedRules).regressed).toContain("quiet.cpuPct"); // The medians differ by 2.8 points, past the floor, but a resampled median can match. - expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); it("reads a file written before loop delay and GC were recorded", () => { @@ -129,6 +149,134 @@ describe("compareMetrics", () => { }); }); +describe("compareMetrics with noise rules", () => { + const rules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: false }, + { pattern: /./, floor: 1_000, gate: true }, + ]; + it.each([ + ["a gated metric past its floor", { cpuPct: 5 }, ["quiet.cpuPct"], []], + ["an ungated metric far past its floor", { loopDelayMaxMs: 300 }, [], ["quiet.loopDelayMaxMs"]], + ["an ungated metric under its floor", { loopDelayMaxMs: 20 }, [], []], + ])("%s", (_name, change, regressed, informational) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change }), 10, rules); + expect(result.regressed).toEqual(regressed); + expect(result.informational).toEqual(informational); + }); + + it("marks an ungated metric in the table either way", () => { + const result = compareMetrics(quietRuns(base), quietRuns(base), 10, rules); + expect(result.table).toContain("| quiet.loopDelayMaxMs | 8 | 8 | 0% | | noisy |"); + }); +}); + +describe("noisePairProblem", () => { + const at = (commit: string | null): ServerMetrics => ({ meta: { ...meta, commit }, runs: [] }); + it.each([ + ["one commit against itself", at("abc"), at("abc"), undefined], + [ + "an A/B directory", + at("abc"), + at("def"), + "ab-out: a.json is abc and b.json def; noise floors need one commit against itself", + ], + [ + "a file with no commit", + at(null), + at(null), + "ab-out: a.json or b.json records no commit, so it cannot be shown to be an A/A run", + ], + ])("%s", (_name, a, b, problem) => { + expect(noisePairProblem("ab-out", a, b)).toBe(problem); + }); +}); + +describe("competingBetween", () => { + it.each([ + ["a process that kept running", [["10:500", 900]], [["10:500", 960]], 60], + ["a new process, counted whole", [], [["11:700", 30]], 30], + ["a reused pid is a new process", [["10:500", 900]], [["10:800", 300]], 300], + ["a process that exited is lost", [["10:500", 900]], [], 0], + ] as const)("%s", (_name, before, after, seconds) => { + expect(competingBetween(new Map(before), new Map(after))).toBe(seconds); + }); +}); + +describe("loadWarnings", () => { + const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) => + ({ + meta: { ...meta, cpus }, + runs: machines.map(([load1, otherCpuCores]) => ({ + machine: { load1, otherCpuCores, minutes: 10 }, + })), + }) satisfies ServerMetrics; + it.each([ + ["a quiet machine", loaded(16, [4, 1], [5, 2]), 0], + ["load past 0.75 per CPU with other processes unknown", loaded(16, [4, null], [12.5, null]), 1], + ["high load from the run's own agents", loaded(16, [21, 1]), 0], + ["other processes on a quarter of the cores", loaded(16, [4, 4.1]), 1], + ["no CPU count", loaded(null, [40, 40]), 0], + ["no machine state, as in older files", { meta: { ...meta, cpus: 16 }, runs: [{}] }, 0], + ])("%s", (_name, metrics, count) => { + expect(loadWarnings("before", metrics)).toHaveLength(count); + }); + + it("names the worst run", () => { + expect(loadWarnings("after", loaded(16, [13, 4.5], [14.2, 5]))[0]).toContain( + "after ran under heavy load in 2 of 2 runs (load up to 14.2 on 16 CPUs, other node/T3/agent processes up to 5 cores)", + ); + }); + + it("is reported by compareMetrics", () => { + expect(compareMetrics(quietRuns(base), loaded(16, [20, null])).warnings).toHaveLength(1); + }); +}); + +describe("noiseReport", () => { + it.each([ + // Resampled medians differ by -0.3 to 1.1: half-width 0.7, so the floor is 0.35. + ["the A/A interval", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.7, 0.1, 0.35], + // Constant sides: no interval, and medians 2 and 3.25 differ by 1.25. + ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0, 1.25, 1.3], + ])("estimates a floor from %s, rounded up", (_name, a, b, halfWidth, aaDifference, floor) => { + const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row).toMatchObject({ halfWidth, aaDifference, suggestedFloor: floor }); + }); + + it("leaves out wakeups counted with the delay sampler on one side only", () => { + const sampled: ServerMetrics = { + meta, + runs: quietRuns({ ...base, wakeupsPerSec: 160 }).runs.map((run) => ({ + quiet: { ...run.quiet, loopSamples: 2_900 }, + })), + }; + const metrics = noiseReport([[quietRuns(base), sampled]]).rows.map(({ metric }) => metric); + expect(metrics).not.toContain("quiet.wakeupsPerSec"); + expect(metrics).toContain("quiet.cpuPct"); + }); + + it("takes the widest pair, and calls a metric noisy when its interval passes half its median", () => { + const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const; + const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const; + const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row?.halfWidth).toBe(1.5); + expect(row?.suggestedGate).toBe(false); + }); + + it("leaves out fields that describe a run", () => { + const withMachine = (metrics: ServerMetrics): ServerMetrics => ({ + ...metrics, + runs: metrics.runs.map((run) => ({ + ...run, + machine: { load1: 3, otherCpuCores: 1, minutes: 9 }, + })), + }); + const rows = noiseReport([[withMachine(cpuRuns(1)), withMachine(cpuRuns(1))]]).rows; + expect(rows.some(({ metric }) => metric.startsWith("machine."))).toBe(false); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 8ab475f38a5ad..7b814efcbdbf5 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -28,6 +28,7 @@ import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; @@ -58,6 +59,10 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + competingBetween, + loadWarnings, + noiseReport, + noisePairProblem, round, ServerMetrics, slope, @@ -70,6 +75,7 @@ import { parseRunSelection, summarizeProfiles, type FirstWord, + type MachineState, type Measured, type ProfileSummary, type Window, @@ -1333,6 +1339,7 @@ interface RunOptions { const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); const api = yield* serveFakeAnthropic(); const environment: Environment = { @@ -1619,6 +1626,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + measured.machine = yield* machine; return { measured: measured as Measured, profiles, soakHeapGrowth }; }, Effect.scoped); @@ -1641,6 +1649,110 @@ const machineLoad = Effect.gen(function* () { ), ); +/** Comm names of the processes that compete with a measured server on a developer's machine. */ +const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/; + +/** + * CPU seconds of every node, T3, claude or codex process outside this script's own tree, keyed by + * pid and start time so a reused pid is a new process. Linux only; elsewhere none, and the run + * records only the load average. + */ +const competingCpuSeconds = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return Option.none>(); + const fs = yield* FileSystem.FileSystem; + const self = Number(yield* fs.readLink("/proc/self")); + const parents = new Map(); + const cpu = new Map(); + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const open = stat.indexOf(" ("); + const close = stat.lastIndexOf(") "); + if (open < 0 || close < 0) continue; + const fields = stat.slice(close + 2).split(" "); + const pid = Number(entry); + parents.set(pid, Number(fields[1])); + if (COMPETING.test(stat.slice(open + 2, close))) { + // Fields after the name start at the state, field 3: utime 14, stime 15, starttime 22. + cpu.set(pid, { + key: `${pid}:${fields[19]}`, + seconds: (Number(fields[11]) + Number(fields[12])) / 100, + }); + } + } + const ours = (pid: number) => { + for (let at: number | undefined = pid; at !== undefined && at > 1; at = parents.get(at)) { + if (at === self) return true; + } + return false; + }; + return Option.some( + new Map([...cpu].filter(([pid]) => !ours(pid)).map(([, { key, seconds }]) => [key, seconds])), + ); +}).pipe(Effect.orElseSucceed(() => Option.none>())); + +/** How often the machine watcher reads competing CPU; a process that exits loses at most this. */ +const MACHINE_SAMPLE_SECONDS = 10; + +const load1 = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") return Option.none(); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(text, (value) => Number(value.split(" ")[0])); + } + const text = yield* output("sysctl", ["-n", "vm.loadavg"]); + return Option.map(text, (value) => Number(value.replace(/[{}]/g, "").trim().split(/\s+/)[0])); +}).pipe(Effect.map(Option.filter(Number.isFinite))); + +/** + * Starts watching the machine for one run; the returned effect reads what competed with it: the + * highest 1-minute load seen and the cores other T3, node and agent processes kept busy. + */ +const watchMachine = Effect.gen(function* () { + const startedAt = yield* nowMs; + const loads: number[] = []; + // Unknown (none) once any read fails, so a partial sum never passes for the whole run. + let competing: Option.Option = Option.some(0); + let previous = yield* competingCpuSeconds; + if (Option.isNone(previous)) competing = Option.none(); + // The periodic and final reads would otherwise interleave across the await below. + const reading = yield* Semaphore.make(1); + const read = Effect.gen(function* () { + loads.push(...Option.toArray(yield* load1)); + if (Option.isNone(previous) || Option.isNone(competing)) return; + const next = yield* competingCpuSeconds; + if (Option.isNone(next)) { + competing = Option.none(); + return; + } + competing = Option.some(competing.value + competingBetween(previous.value, next.value)); + previous = next; + }).pipe(reading.withPermits(1)); + yield* read; + // Reading through the run, not only at its ends, keeps a busy process that exits mid-run. + yield* read.pipe( + Effect.delay(Duration.seconds(MACHINE_SAMPLE_SECONDS)), + Effect.forever, + Effect.forkScoped, + ); + return Effect.gen(function* () { + yield* read; + const elapsed = ((yield* nowMs) - startedAt) / 1_000; + const machine: MachineState = { + load1: loads.length ? round(Math.max(...loads), 2) : null, + otherCpuCores: + Option.isSome(competing) && elapsed > 0 ? round(competing.value / elapsed, 2) : null, + minutes: round(elapsed / 60, 1), + }; + return machine; + }); +}); + const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; @@ -1694,13 +1806,21 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { - const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + const { table, regressed, improved, informational, compared, warnings } = compareMetrics( + before, + after, + threshold, + ); yield* Console.log(table); + for (const warning of warnings) yield* Console.error(`Warning: ${warning}`); if (compared === 0) { return yield* new MetricsError({ message: "the two files share no metric, so nothing was compared", }); } + if (informational.length) { + yield* Console.error(`Moved, but too noisy to gate on: ${informational.join(", ")}`); + } if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); if (regressed.length === 0) return; yield* Console.error(`Worse: ${regressed.join(", ")}`); @@ -1937,7 +2057,51 @@ const compareCommand = Command.make( }), ).pipe( Command.withDescription( - "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor, measured from A/A runs (see `noise`). Metrics too noisy to gate on are shown but never counted. Warns when either side ran under heavy machine load. Exits 1 on a regression.", + ), +); + +const noiseCommand = Command.make( + "noise", + { + dirs: Argument.String("dir").pipe( + Argument.withDescription("An `ab` out dir (a.json and b.json) of one commit against itself."), + Argument.atLeast(1), + ), + }, + Effect.fn("serverMetrics.noise")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + const pairs = yield* Effect.forEach(input.dirs, (dir) => + Effect.gen(function* () { + const a = yield* read(path.join(dir, "a.json")); + const b = yield* read(path.join(dir, "b.json")); + const problem = noisePairProblem(dir, a, b); + if (problem !== undefined) return yield* new MetricsError({ message: problem }); + for (const [file, metrics] of [ + ["a.json", a], + ["b.json", b], + ] as const) { + for (const warning of loadWarnings(path.join(dir, file), metrics)) { + yield* Console.error(`Warning: ${warning}`); + } + } + return [a, b] as const; + }), + ); + const { rows, table } = noiseReport(pairs); + if (rows.length === 0) { + return yield* new MetricsError({ + message: "no metric was measured on both sides of any pair, so nothing was calibrated", + }); + } + yield* Console.log(table); + }), +).pipe( + Command.withDescription( + "Spread of every metric over A/A runs (`ab `), an estimated floor covering the half ranges and median differences these runs showed, and which metrics are too noisy to gate on. ⚠ marks a current floor under the estimate. Refuses directories whose two files record different commits.", ), ); @@ -1945,7 +2109,7 @@ const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", ), - Command.withSubcommands([runCommand, abCommand, compareCommand]), + Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); if (import.meta.main) { From 20419366c39daca3238c65b1c9018772e2f914a0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:22:43 -0800 Subject: [PATCH 108/288] feat(scripts): server metrics measure many threads working at once with one client (#41371) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 3 + scripts/server-metrics-report.ts | 54 +++- scripts/server-metrics.test.ts | 41 +++ scripts/server-metrics.ts | 259 ++++++++++++++++++- 4 files changed, 343 insertions(+), 14 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 0e42c0fa09f3c..135fb95ea6905 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -37,6 +37,9 @@ heap, and first-request latency against a fake Anthropic API and the real `claud isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to spot rising heap slopes (leaks). +- Steer server work by `working`: many worktree threads editing files at once with one client + subscribed to all of them. Turns per minute that stay flat as threads are added mean the + server, not the agents, is the bottleneck. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 0cd34b23935e9..70a6e52ec73c4 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -48,6 +48,19 @@ const MachineState = Schema.Struct({ }); export type MachineState = typeof MachineState.Type; +const WorkingPoint = Schema.Struct({ + ...Window.fields, + /** Turns finished inside the window, per minute; higher is better. */ + turnsPerMin: Schema.Number, + /** Send to the agent's first API request. */ + toRequestMs: Spread, + /** The turn's last reply byte to the client seeing the run end. */ + turnEndMs: Spread, + /** Send to the client seeing the run end. */ + turnMs: Spread, +}); +export type WorkingPoint = typeof WorkingPoint.Type; + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ /** What else the machine was doing during the pass; never compared, only warned about. */ @@ -73,6 +86,21 @@ export const Measured = Schema.Struct({ }), }), ), + /** + * N threads in worktrees of their own run editing turns back to back, all at once, with one + * web-like client subscribed to all of them. The scenario to steer server performance by. + */ + working: Schema.optional( + Schema.Struct({ + /** Each window by the number of threads working in it. */ + active: Schema.Record(Schema.String, WorkingPoint), + /** Fits over the windows: what each additional working thread costs. */ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + loopDelayP99MsPerThread: Schema.Number, + }), + ), /** 50 short turns back to back on one thread. */ pipeline: Schema.optional( Schema.Struct({ @@ -244,6 +272,24 @@ export const NOISE_RULES: ReadonlyArray = [ { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, { pattern: /^soak\./, floor: 20, gate: true }, + informational(/^working\.(cpuPct|loopDelayP99Ms)PerThread$/), + informational(/^working\.active\.\d+\.(wakeupsPerSec|loopDelayMaxMs|gcPauseMs)$/), + { pattern: /^working\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^working\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^working\.active\.\d+\.turnsPerMin$/, floor: 4, gate: true }, + { pattern: /^working\.active\.\d+\.toRequestMs\.median$/, floor: 1_100, gate: true }, + { pattern: /^working\.active\.\d+\.turnEndMs\.median$/, floor: 1_700, gate: true }, + { + pattern: /^working\.active\.\d+\.(toRequestMs\.p90|turnMs\.median)$/, + floor: 1_900, + gate: true, + }, + { pattern: /^working\.active\.\d+\.turnEndMs\.p90$/, floor: 2_200, gate: true }, + { pattern: /^working\.active\.\d+\.turnMs\.p90$/, floor: 2_800, gate: true }, + // Peak RSS while 20 agents run swings by a checkpoint's git children; the settled RSS does not. + { pattern: /^working\.active\.\d+\.rssPeakMB$/, floor: 170, gate: true }, + { pattern: /^working\.active\.\d+\.(cpuPct|loopDelayP99Ms)$/, floor: 5, gate: true }, + { pattern: /^working\.active\.\d+\.gcCount$/, floor: 8, gate: true }, { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, { pattern: /^firstWord\./, floor: 600, gate: true }, { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, @@ -270,6 +316,9 @@ export function noiseRule(metric: string, rules: ReadonlyArray = NOIS return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; } +/** Throughput, where a drop is the regression. */ +export const higherIsBetter = (metric: string) => metric.endsWith("PerMin"); + /** Fields that describe a run rather than measure it. */ const isMetric = (metric: string) => !( @@ -465,7 +514,7 @@ export function compareMetrics( const a = collect(before); const b = collect(after); const lines = [ - "### Server metrics (lower is better)", + "### Server metrics (lower is better, except throughput per minute)", "", `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, "", @@ -499,7 +548,8 @@ export function compareMetrics( const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const moved = low > limit ? "worse" : high < -limit ? "better" : ""; + const up = low > limit ? "worse" : high < -limit ? "better" : ""; + const moved = higherIsBetter(metric) ? { worse: "better", better: "worse", "": "" }[up] : up; if (moved && !rule.gate) informational.push(metric); else if (moved === "worse") regressed.push(metric); else if (moved === "better") improved.push(metric); diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index de3237d3c0d23..adc86fddce588 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -277,6 +277,47 @@ describe("noiseReport", () => { }); }); +describe("compareMetrics on working throughput", () => { + const working = (turnsPerMin: number) => + ({ + meta, + runs: [ + { + working: { + active: { + "20": { + ...loopAtRest, + cpuPct: 90, + wakeupsPerSec: 1_600, + rssPeakMB: 700, + rssMB: 560, + heapAfterGcMB: 218, + turnsPerMin, + toRequestMs: { median: 4_000, p90: 9_000 }, + turnEndMs: { median: 16_000, p90: 25_000 }, + turnMs: { median: 24_000, p90: 36_000 }, + }, + }, + heapMBPerThread: 0.2, + rssMBPerThread: 0.8, + cpuPctPerThread: 0, + loopDelayP99MsPerThread: 0, + }, + }, + ], + }) satisfies ServerMetrics; + const rules = [{ pattern: /turnsPerMin$/, floor: 2, gate: true }]; + it.each([ + ["fewer turns a minute", 20, ["working.active.20.turnsPerMin"], []], + ["more turns a minute", 45, [], ["working.active.20.turnsPerMin"]], + ["a move under the floor", 34, [], []], + ])("%s", (_name, turnsPerMin, regressed, improved) => { + const result = compareMetrics(working(33), working(turnsPerMin), 5, rules); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 7b814efcbdbf5..54fc28693b3fd 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -33,6 +34,9 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; import { + CommandId, + MessageId, + type OrchestrationV2ThreadStreamItem, ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_VERSION_TEXT, @@ -77,6 +81,7 @@ import { type FirstWord, type MachineState, type Measured, + type WorkingPoint, type ProfileSummary, type Window, } from "./server-metrics-report.ts"; @@ -84,8 +89,12 @@ import { const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; +/** A prompt holding this streams a reply that ends in a Write tool call, then a short answer. */ +const EDIT_MARKER = "[[edit-files]]"; /** Sequential turns in the pipeline scenario. */ const PIPELINE_TURNS = 50; +/** Threads working at once in each window of the working scenario. */ +const WORKING_THREADS = [5, 10, 20]; /** Clients that drop and reconnect at once in the clients scenario. */ const STORM_CLIENTS = 20; /** Event-loop delay sampling interval; each sample wakes the loop once. */ @@ -128,6 +137,8 @@ interface ApiRequest { readonly agent: boolean; readonly stream: boolean; readonly marker: string | undefined; + /** The request carries a tool result, so it is a turn's follow-up rather than its start. */ + readonly toolResult: boolean; /** When the reply's last event was produced; streamed replies only. */ endedAt?: number; } @@ -136,8 +147,26 @@ const MessagesRequest = Schema.Struct({ stream: Schema.optional(Schema.Boolean), model: Schema.optional(Schema.String), tools: Schema.optional(Schema.Array(Schema.Unknown)), + messages: Schema.optional( + Schema.Array(Schema.Struct({ role: Schema.String, content: Schema.Unknown })), + ), }); +/** Whether the newest message hands back a tool's result. */ +const endsInToolResult = (messages: typeof MessagesRequest.Type.messages) => { + const content = messages?.at(-1)?.content; + return ( + Array.isArray(content) && + content.some( + (block: unknown) => + typeof block === "object" && + block !== null && + "type" in block && + block.type === "tool_result", + ) + ); +}; + /** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { const requests: ApiRequest[] = []; @@ -157,7 +186,9 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), ); const streamed = body.stream === true; + const toolResult = endsInToolResult(body.messages); const entry: ApiRequest = { + toolResult, at: yield* nowMs, stream: streamed, // Title and branch-name jobs carry only their structured-output tool; the agent carries many. @@ -183,10 +214,13 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio const event = (name: string, data: object) => `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; const slow = raw.includes(SLOW_MARKER); - const words = slow ? 2_000 : 40; + // An editing turn streams a longer first reply, then writes a file in the agent's directory. + const cwd = /Primary working directory: ([^\\"\n]+)/.exec(raw)?.[1]?.trim(); + const edit = entry.agent && raw.includes(EDIT_MARKER) && !toolResult && cwd !== undefined; + const words = slow ? 2_000 : edit ? 150 : 40; const deltas = Stream.range(0, words - 1).pipe( Stream.mapEffect((word) => - Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.sleep(Duration.millis(slow ? 50 : edit ? 10 : 5)).pipe( Effect.as( event("content_block_delta", { index: 0, @@ -196,6 +230,43 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio ), ), ); + const toolCall = edit + ? Stream.make( + event("content_block_stop", { index: 0 }), + event("content_block_start", { + index: 1, + content_block: { + type: "tool_use", + id: `toolu_bench_${requests.length}`, + name: "Write", + input: {}, + }, + }), + event("content_block_delta", { + index: 1, + delta: { + type: "input_json_delta", + partial_json: encodeJson({ + file_path: `${cwd}/bench/${entry.marker ?? `turn-${requests.length}`}.md`, + content: Array.from({ length: 40 }, (_, line) => `line ${line} of ${id}`).join( + "\n", + ), + }), + }, + }), + event("content_block_stop", { index: 1 }), + event("message_delta", { + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ) + : Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ); const events = Stream.make( event("message_start", { message: { @@ -212,15 +283,7 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), ).pipe( Stream.concat(deltas), - Stream.concat( - Stream.make( - event("content_block_stop", { index: 0 }), - event("message_delta", { - delta: { stop_reason: "end_turn", stop_sequence: null }, - usage: { output_tokens: words }, - }), - ), - ), + Stream.concat(toolCall), // Stamped as the last event is produced, so it is set before any client can see the end. Stream.concat( Stream.fromEffect( @@ -1128,6 +1191,11 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( server: Server, token: string, threadIds: ReadonlyArray, + /** Sees every item a thread subscription delivers, the snapshot included. */ + onThreadItem: ( + threadId: string, + item: OrchestrationV2ThreadStreamItem, + ) => Effect.Effect = () => Effect.void, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1162,6 +1230,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const ready = Effect.fn("serverMetrics.subscription")(function* ( stream: Stream.Stream, isReady: (item: A) => boolean, + onItem: (item: A) => Effect.Effect = () => Effect.void, ) { const synchronized = yield* Deferred.make(); const lose = (message: string) => @@ -1170,7 +1239,9 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); yield* stream.pipe( Stream.runForEach((item) => - isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void, + onItem(item).pipe( + Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), + ), ), Effect.andThen(lose("a subscription ended")), Effect.catchCause(() => lose("a subscription failed")), @@ -1244,6 +1315,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( acceptDedupedBodies: true, }), synchronized, + (item) => onThreadItem(threadId, item), ), )), ]; @@ -1254,6 +1326,19 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), ); return { + /** Sends a message the way the composer does, starting a turn at once. */ + send: (threadId: string, messageId: string, text: string) => + client["orchestration.dispatchCommand"]({ + type: "message.dispatch", + commandId: CommandId.make(messageId), + threadId: ThreadId.make(threadId), + messageId: MessageId.make(messageId), + text, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }), /** Fails if any of this client's subscriptions or reports was lost since it attached. */ healthy: Effect.flatMap(Ref.get(lost), (message) => message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), @@ -1308,6 +1393,126 @@ const pipelineTurns = Effect.fn("serverMetrics.pipelineTurns")(function* ( }; }); +const TERMINAL_RUN = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + +/** Threads that each answered once in a worktree of their own, by id. */ +const openWorktreeThreads = Effect.fn("serverMetrics.openWorktreeThreads")(function* ( + server: Server, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait", "--worktree", "main"]), + { concurrency: 5 }, + ); + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + const failed = answers.find((answer, index) => answer.exitCode !== 0 || !ids[index]); + if (failed) { + return yield* new MetricsError({ + message: `a worktree thread failed to start: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + return ids.filter((id) => id !== undefined); +}); + +/** + * Every given thread runs editing turns back to back, all at once, sent and watched by one client + * subscribed to all of them, as the web client is. Each turn streams a reply, writes a file in the + * thread's worktree through the agent's Write tool, and ends in a checkpoint of that change. The + * window is measured while every thread is working; turns finished inside it are timed. + */ +const workingWindow = Effect.fn("serverMetrics.workingWindow")(function* ( + environment: Environment, + server: Server, + token: string, + threadIds: ReadonlyArray, + timing: { readonly warmupSeconds: number; readonly windowSeconds: number }, + /** The first turn's marker number; each window needs its own range, as ids never repeat. */ + firstMarker: number, +) { + // One pending turn per thread: its message id and when the run's end reached the client. + const pending = new Map }>(); + const client = yield* attachClient(server, token, threadIds, (threadId, item) => { + if (item.kind !== "event" || item.event.type !== "run.updated") return Effect.void; + const run = item.event.payload; + const turn = pending.get(threadId); + if (!turn || run.userMessageId !== turn.messageId || !TERMINAL_RUN.has(run.status)) { + return Effect.void; + } + return Deferred.succeed(turn.done, run.status).pipe(Effect.asVoid); + }); + const turns: Array<{ endedAt: number; toRequest: number; turnEnd: number; turnMs: number }> = []; + let stopping = false; + let sequence = 0; + const work = Effect.fn("serverMetrics.workingThread")(function* (threadId: string) { + while (!stopping) { + const marker = `bench-run-${firstMarker + sequence++}`; + const messageId = `bench-message-${marker}`; + const done = yield* Deferred.make(); + pending.set(threadId, { messageId, done }); + const sentAt = yield* nowMs; + yield* client.send(threadId, messageId, `Edit a file. ${EDIT_MARKER} ${marker}`); + const status = yield* Deferred.await(done).pipe( + Effect.timeoutOrElse({ + duration: Duration.seconds(120), + orElse: () => new MetricsError({ message: `turn ${marker} never ended` }), + }), + ); + const endedAt = yield* nowMs; + if (status !== "completed") { + return yield* new MetricsError({ message: `turn ${marker} ended ${status}` }); + } + const forTurn = environment.requests.filter( + (request) => request.agent && request.marker === marker && request.at >= sentAt, + ); + const first = forTurn.find((request) => !request.toolResult); + const last = forTurn.findLast((request) => request.toolResult); + if (first === undefined || last?.endedAt === undefined) { + return yield* new MetricsError({ + message: `turn ${marker} never called its Write tool; is the Claude CLI's tool set unchanged?`, + }); + } + turns.push({ + endedAt, + toRequest: first.at - sentAt, + turnEnd: endedAt - last.endedAt, + turnMs: endedAt - sentAt, + }); + } + }); + const workers = yield* Effect.forEach(threadIds, (threadId) => Effect.forkScoped(work(threadId))); + // A failed turn ends the window at once instead of thinning it. + const failed = Effect.forEach(workers, Fiber.join, { + concurrency: "unbounded", + discard: true, + }).pipe(Effect.andThen(Effect.never)); + return yield* Effect.raceFirst( + Effect.gen(function* () { + yield* Effect.sleep(Duration.seconds(timing.warmupSeconds)); + const from = yield* nowMs; + const window = yield* server.measure(timing.windowSeconds); + const to = yield* nowMs; + // Every thread finishes the turn it is on, so the next window starts from idle threads. + stopping = true; + yield* Effect.forEach(workers, Fiber.join, { discard: true }); + yield* client.healthy; + const inside = turns.filter((turn) => turn.endedAt >= from && turn.endedAt <= to); + if (inside.length === 0) { + return yield* new MetricsError({ message: "no turn finished inside the window" }); + } + const point: WorkingPoint = { + ...window, + turnsPerMin: round((inside.length / (to - from)) * 60_000), + toRequestMs: spread(inside.map((turn) => turn.toRequest)), + turnEndMs: spread(inside.map((turn) => turn.turnEnd)), + turnMs: spread(inside.map((turn) => turn.turnMs)), + }; + return point; + }), + failed, + ); +}, Effect.scoped); + const SCENARIOS = [ "startup", "rest", @@ -1316,6 +1521,7 @@ const SCENARIOS = [ "streaming", "clients", "pipeline", + "working", "busy", ] as const; /** Scenarios that read the developer's real database, so they run only when named. */ @@ -1494,6 +1700,35 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + if (wanted("working")) { + yield* withServer("working", (server) => + Effect.gen(function* () { + const token = yield* server.issueToken; + const counts = WORKING_THREADS; + const threads = yield* openWorktreeThreads(server, Math.max(...counts)); + const active: Record = {}; + for (const [index, count] of counts.entries()) { + active[`${count}`] = yield* workingWindow( + environment, + server, + token, + threads.slice(0, count), + { warmupSeconds: 10, windowSeconds: 30 }, + 30_000 + index * 10_000, + ); + } + const fit = (pick: (point: WorkingPoint) => number) => + round(slope(counts.map((count) => [count, pick(active[`${count}`]!)] as const)), 3); + measured.working = { + active, + heapMBPerThread: fit((point) => point.heapAfterGcMB), + rssMBPerThread: fit((point) => point.rssMB), + cpuPctPerThread: fit((point) => point.cpuPct), + loopDelayP99MsPerThread: fit((point) => point.loopDelayP99Ms ?? 0), + }; + }), + ); + } if (wanted("pipeline")) { yield* withServer("pipeline", (server) => Effect.gen(function* () { From 059d1bdeb9d7c0358e8a39dadd812d14a97e4580 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:05 -0800 Subject: [PATCH 109/288] docs: point provider setup at ACP Registry agents like GitHub Copilot (#41478) --- docs/user/install.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/user/install.md b/docs/user/install.md index 60d2d12f01c90..60ee758a0e656 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -195,18 +195,19 @@ and enable the provider you want. Installation, login, and configuration belong to that environment's machine, even when you connect from a phone or another computer. -| Provider | Install and authenticate | -| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | -| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | -| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | -| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | -| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | -| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | -| Antigravity | Install and sign in with Google from T3 Code's provider settings. | -| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | -| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | -| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| Provider | Install and authenticate | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | +| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | +| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | +| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | +| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | +| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | +| Antigravity | Install and sign in with Google from T3 Code's provider settings. | +| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | +| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | +| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| ACP Registry agents | Add GitHub Copilot and other [ACP agents](./providers-acp.md#add-an-agent) from **Settings → Providers → Add provider → Show more**. | Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its **Binary path** in provider settings, especially when using a version manager. @@ -246,7 +247,8 @@ their original values. For provider-specific setup and accounts, see [Codex](./providers-codex.md), [Claude](./providers-claude.md), [OpenCode](./providers-opencode.md), [Antigravity](./providers-antigravity.md), [Kiro](./providers-kiro.md), -[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), and [fx](./providers-fx.md). +[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), [fx](./providers-fx.md), and +[ACP Registry agents](./providers-acp.md). ### Provider check timeouts From 8f724d6329ad37bfb1eb5ca1eccc1d26ca1fab77 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Mon, 23 Nov 2026 15:24:18 +0100 Subject: [PATCH 110/288] fix: treat empty PATH entries as the working directory in launcher and CLI lookups (#41393) Co-authored-by: Julius Marminge --- apps/server/src/cli/invocation.test.ts | 35 ++++++++++ apps/server/src/cli/invocation.ts | 11 ++- apps/server/src/cli/triage.test.ts | 48 +++++++++++++ apps/server/src/cli/triage.ts | 12 +++- apps/server/src/cloud/pinnedRuntime.test.ts | 67 +++++++++++++++++++ apps/server/src/cloud/pinnedRuntime.ts | 19 +++--- .../src/cloud/serviceLauncherClient.test.ts | 67 +++++++++++++++++++ .../server/src/cloud/serviceLauncherClient.ts | 18 ++++- packages/shared/src/relayClient.test.ts | 39 +++++++++++ packages/shared/src/relayClient.ts | 14 +++- 10 files changed, 313 insertions(+), 17 deletions(-) diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 8310649aa77cb..928e97dc69246 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; import { posixLauncherScript } from "../cloud/pinnedRuntime.ts"; import { + hostShellWord, resolveHostCliCommand, resolveRootCliCommand, resolveServerInstallation, @@ -187,6 +188,40 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { ); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "names the absolute path of a t3 found through a relative PATH entry", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(bin, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + const hostCommand = (searchPath: string) => + resolveHostCliCommand("doctor").pipe( + Effect.provideService(HostProcess.ExecutablePath, "/usr/bin/node"), + Effect.provideService(HostProcess.Arguments, [ + "/usr/bin/node", + "/opt/t3/lib/node_modules/t3/dist/bin.mjs", + ]), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + ); + + // A relative entry was searched from this process's directory, unlike the user's shell. + expect(yield* hostCommand(path.relative(process.cwd(), bin))).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + // An empty entry makes the shell search its own directory first, wherever that is. + expect(yield* hostCommand(`:${bin}`)).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + expect(yield* hostCommand(bin)).toEqual({ command: "t3 doctor", launcher: false }); + }), + ); }); it.layer(NodeServices.layer)("manual server installation ownership", (it) => { diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 4804d44f0e324..69a3a5815bbd6 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -205,7 +205,16 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand ) : null; if (own === null || own === (yield* real(onPath))) { - return { command: withArgs(command), launcher: false }; + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + // With an empty or relative PATH entry, plain `t3` depends on the directory it runs from. + const cwdDependent = + platform !== "win32" && + searchPath.length > 0 && + searchPath.split(":").some((entry) => !path.isAbsolute(entry)); + if (!cwdDependent) return { command: withArgs(command), launcher: false }; + const quoted = hostShellWord(platform, path.resolve(onPath)); + return { command: withArgs(`${quoted} ${subcommand}`), launcher: false }; } } const launcher = yield* resolveInstallLauncher; diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 25f7baeb3211e..41f4241fade68 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -190,3 +190,51 @@ it.live("a failed agent launch points at the prompt it could not run", () => ), ), ); + +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "starts an agent found through a relative PATH entry from the session directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + // Relative to this process, as an entry like "." is to the server that checked it. + const relativeBinDir = NodePath.relative(process.cwd(), binDir); + // Nested deeper than the entry climbs, so from the session directory it leads nowhere. + const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length; + const baseDir = NodePath.join( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }), + ...Array.from({ length: climbs }, () => "nested"), + ); + NodeFS.mkdirSync(baseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.stubEnv("PATH", relativeBinDir); + vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home")); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + + // The fake agent ran and exited 1, rather than failing to start. + assert.equal(process.exitCode, 1); + assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1."); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index cb0f94b254589..df73347cd9fe4 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -4,7 +4,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; -import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; @@ -220,7 +221,14 @@ export const triageCommand = Command.make("triage", { const model = Option.getOrUndefined(flags.model); const launchPrompt = buildTriageLaunchPrompt(promptFilePath); - const spawnSpec = yield* resolveSpawnCommand(selected.command, [ + // The agent starts in the session directory, so a PATH match relative to this one would + // be searched from there. Windows keeps the bare name for its .cmd shim handling. + const onPath = + (yield* HostProcess.Platform) === "win32" + ? null + : yield* resolveCommandPath(selected.command); + const command = onPath === null ? selected.command : NodePath.resolve(onPath); + const spawnSpec = yield* resolveSpawnCommand(command, [ ...(model === undefined ? [] : ["--model", model]), ...(selected.promptArgs ?? []), launchPrompt, diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 28a7d720c525f..d5f15cd1b4591 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -18,6 +18,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; import { + findPosixLauncher, isVersionExecutable, ensurePinnedRuntimeInstalled, isUnpublishedRelease, @@ -25,7 +26,9 @@ import { pinnedRuntimePaths, PinnedRuntimeInstallError, type PinnedRuntimeProgress, + posixLauncherScript, prunePinnedRuntimes, + resolveLauncherPath, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -987,3 +990,67 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); }); + +// NTFS reports no exec bits, and these lookups pass over files without them. +const posixHost = HostProcess.Platform.defaultValue() !== "win32"; + +it.layer(NodeServices.layer)("launcher lookup on PATH", (it) => { + it.effect.skipIf(!posixHost)( + "resolves an empty entry of a nonempty PATH against the working directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const launcher = path.join(root, "t3"); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); + const missing = path.join(root, "missing"); + const lookup = (platform: NodeJS.Platform, searchPath: string) => + resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + Effect.provideService(HostProcess.WorkingDirectory, root), + ); + + assert.equal(yield* lookup("linux", `:${missing}`), launcher); + assert.equal(yield* lookup("linux", `${missing}:`), launcher); + assert.equal(yield* lookup("linux", `${missing}::${missing}`), launcher); + // An empty PATH searches nothing, and Windows has no such rule. + assert.isUndefined(yield* lookup("linux", "")); + assert.isUndefined(yield* lookup("win32", `;${missing}`)); + }), + ); + + it.effect.skipIf(!posixHost)("finds a launcher script through an empty PATH entry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const versionsDir = path.join(root, ".t3", "runtime", "versions"); + const executable = path.join(versionsDir, "1.0.0", "t3"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString(path.join(bin, "t3"), posixLauncherScript(executable), { + mode: 0o755, + }); + const script = yield* fs.realPath(path.join(bin, "t3")); + const missing = path.join(root, "missing"); + const lookup = (searchPath: string) => + findPosixLauncher({ launchedAs: executable, versionsDir }).pipe( + Effect.provideService(HostProcess.Environment, { + PATH: searchPath, + T3CODE_INSTALL_BIN_DIR: missing, + }), + Effect.provideService(HostProcess.WorkingDirectory, bin), + ); + + assert.equal(yield* lookup(`:${missing}`), script); + assert.equal(yield* lookup(`${missing}:`), script); + // An empty PATH searches nothing, not even the working directory. + assert.isUndefined(yield* lookup("")); + }), + ); +}); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 13c8f251c93b6..e544852ef3dcc 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -537,9 +537,11 @@ export const resolveLauncherPath = Effect.gen(function* () { return path.resolve(cwd, invokedAs); } const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.resolve(cwd, directory, invokedAs); + const searchPath = environment["PATH"] ?? ""; + for (const directory of searchPath.split(delimiter)) { + // POSIX shells search the working directory for an empty entry of a nonempty PATH. + if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue; + const candidate = path.resolve(cwd, directory || ".", invokedAs); const info = yield* fs.stat(candidate).pipe(Effect.option); // Like the shell, pass over directories and non-executable files named the same. if ( @@ -645,12 +647,13 @@ export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_laun .readFileString(path.join(path.dirname(input.versionsDir), "launchers")) .pipe(Effect.orElseSucceed(() => "")); const cwd = yield* HostProcess.WorkingDirectory; + const searchPath = environment["PATH"] ?? ""; const candidates = [ - // PATH first, resolved like the shell does: it decides which t3 the user runs. - ...(environment["PATH"] ?? "") - .split(":") - .filter((directory) => directory.length > 0) - .map((directory) => path.resolve(cwd, directory, "t3")), + // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty + // entry of a nonempty PATH is the working directory; an empty PATH searches nothing. + ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) => + path.resolve(cwd, directory || ".", "t3"), + ), path.join( environment["T3CODE_INSTALL_BIN_DIR"] || path.join(yield* HostProcess.HomeDirectory, ".local", "bin"), diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 338ff32a3c16e..85661360020f6 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -325,4 +325,71 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(onPath), foreign); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); + + it.effect.each([ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + { name: "whole", searchPath: () => "", moved: false }, + ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const inCwd = path.join(cwd, "t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + yield* fs.makeDirectory(cwd); + yield* fs.symlink(exe("1.0.0"), inCwd); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: searchPath(path.join(root, "missing")), + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + // A nonempty PATH searches the working directory there; an empty PATH searches nothing. + if (moved) { + assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0"))); + } else { + assert.equal(yield* fs.readLink(inCwd), exe("1.0.0")); + } + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("passes over a working-directory t3 the shell cannot run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + // A directory named t3 in the working directory, which the shell skips. + yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true }); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: `:${path.dirname(onPath)}`, + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0"))); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); }); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index e8f8941f3f9e8..3e7f4abfc2d57 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -163,9 +163,21 @@ export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); const candidates = new Set(); if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); - for (const directory of (environment["PATH"] ?? "").split(":")) { - if (directory.length === 0) continue; - const candidate = path.join(directory, "t3"); + const searchPath = environment["PATH"] ?? ""; + const cwd = yield* HostProcess.WorkingDirectory; + for (const directory of searchPath.split(":")) { + // Like the shell, an empty entry of a nonempty PATH is the working directory. + if (directory.length === 0 && searchPath.length === 0) continue; + const candidate = path.join(directory || cwd, "t3"); + if (directory.length === 0) { + // The shell passes over a working-directory entry it cannot run and keeps searching. + const info = yield* fs.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) { + continue; + } + candidates.add(candidate); + break; + } if ( yield* fs.exists(candidate).pipe( Effect.catch((cause) => diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 594d5ad215b1a..f317cc22b3565 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -717,6 +717,45 @@ describe("RelayClient", () => { ); }); + it.effect.skipIf(windowsHost)( + "finds a PATH binary through an empty entry by its absolute path", + () => + run((baseDir) => + Effect.gen(function* () { + const cwd = `${baseDir}/work`; + const inCwd = `${cwd}/cloudflared`; + yield* writeExecutable(inCwd); + const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); + const resolveWith = (searchPath: string) => { + const env = { PATH: searchPath }; + return manager.resolve.pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env }), + ), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + }; + const found = { + status: "available", + executablePath: inCwd, + source: "path", + version: RelayClient.CLOUDFLARED_VERSION, + }; + + expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found); + expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found); + const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION }; + // An empty PATH searches nothing, not even the working directory. + expect(yield* resolveWith("")).toEqual(missing); + // A whitespace entry is not an empty one. + expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing); + expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing); + }), + ), + ); + it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => { const versions: Record = {}; return run( diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 19e42955ea554..81838ea4f65a0 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -374,13 +374,21 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const resolvePathExecutable = Effect.gen(function* () { // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath. - const pathValue = (yield* HostProcess.Environment).PATH?.trim(); + const rawPathValue = (yield* HostProcess.Environment).PATH; + // POSIX keeps the raw value, so trimming never turns " :/bin" into an empty entry. + const pathValue = platform === "win32" ? rawPathValue?.trim() : rawPathValue; if (!pathValue) return null; const delimiter = platform === "win32" ? ";" : ":"; + const cwd = yield* HostProcess.WorkingDirectory; for (const directory of pathValue.split(delimiter)) { + // POSIX shells search the working directory for an empty entry. Resolve it now: the + // connector may be launched from elsewhere. + const workingDirectoryEntry = directory === "" && platform !== "win32"; const trimmed = directory.trim().replace(/^"|"$/gu, ""); - if (trimmed.length === 0) continue; - const candidate = path.join(trimmed, executableFileName(platform)); + if (trimmed.length === 0 && !workingDirectoryEntry) continue; + const candidate = workingDirectoryEntry + ? path.resolve(cwd, executableFileName(platform)) + : path.join(trimmed, executableFileName(platform)); if (!(yield* isExecutableFile(candidate))) continue; const available = yield* compatibleCandidate(candidate, "path"); if (available) return available; From 962bda2eb7580496c4d5a4459288ead92d9e829e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:28 -0800 Subject: [PATCH 111/288] test(web): open history documents without reloading the app in iframes (#41489) --- .../src/browserHistoryStore.browser.test.ts | 79 ++++++++----------- 1 file changed, 34 insertions(+), 45 deletions(-) diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index c0c22fc2558a4..92e16d76243e6 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -2,6 +2,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; +import { randomUUID } from "./lib/utils"; const storageKey = "t3code:browser-history:v1"; const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; @@ -117,8 +118,7 @@ it("refreshes the open history when another document adds a visit", async () => JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); - using documents = new DisposableStack(); - const otherStore = await openHistoryDocument(documents); + const otherStore = await openHistoryDocument(); await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); @@ -164,29 +164,15 @@ it("bounds saved thread mappings while keeping live registrations", async () => } }); -async function openHistoryDocument( - disposables: DisposableStack, - { withoutIndexedDB = false } = {}, -) { - const source = new URL(import.meta.url); - source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); - source.search = ""; - const frame = document.createElement("iframe"); - disposables.defer(() => frame.remove()); - frame.srcdoc = `${withoutIndexedDB ? '' : ""} - `; - await new Promise((resolve) => { - frame.onload = () => resolve(); - document.body.append(frame); - }); - const store = ( - frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null - )?.historyStore; - if (!store) throw new Error("The history document did not load."); - return store; +// A fresh module instance stands in for another tab: it gets its own store, IndexedDB connection +// and BroadcastChannel without an iframe reloading the app's whole module graph. +async function openHistoryDocument() { + const source = new URL("./browserHistoryStore.ts", import.meta.url); + source.searchParams.set("document", randomUUID()); + const module: typeof import("./browserHistoryStore") = await import( + /* @vite-ignore */ source.href + ); + return module.useBrowserHistoryStore; } function deleteHistoryDatabase() { @@ -210,14 +196,13 @@ it("moves the legacy snapshot into the shared database", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); expect(localStorage.getItem(storageKey)).toBeNull(); first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); @@ -233,8 +218,7 @@ it("persists new visits from an open document after its history database is dele JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); first.getState().removeUrl("a", page.url); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); @@ -243,7 +227,7 @@ it("persists new visits from an open document after its history database is dele first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); } finally { await resetHistoryFixture(); @@ -257,11 +241,7 @@ it("keeps overlapping visits from independent documents", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const [first, second] = await Promise.all([ - openHistoryDocument(documents), - openHistoryDocument(documents), - ]); + const [first, second] = await Promise.all([openHistoryDocument(), openHistoryDocument()]); first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); const expected = { a: [page, oldEntry], b: [otherEntry] }; @@ -272,7 +252,7 @@ it("keeps overlapping visits from independent documents", async () => { // A fresh document should read the committed visits even after the legacy seed is gone. localStorage.removeItem(storageKey); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); } finally { await resetHistoryFixture(); @@ -282,16 +262,25 @@ it("keeps overlapping visits from independent documents", async () => { it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); try { - using documents = new DisposableStack(); - const db = await openHistoryFixture(documents); + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); - const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); - offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); - await vi.waitFor(() => - expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), - ); + vi.stubGlobal("indexedDB", { + open() { + throw new Error("blocked"); + }, + }); + try { + const offline = await openHistoryDocument(); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + } finally { + vi.unstubAllGlobals(); + } - const online = await openHistoryDocument(documents); + const online = await openHistoryDocument(); await vi.waitFor(() => expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); From f1e390665a119c59ca01492713fa161a5e07200b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:42 -0800 Subject: [PATCH 112/288] feat(scripts): server metrics reconnect a user's devices by default and keep the 20-client storm behind --stress (#41372) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 2 + scripts/server-metrics-report.ts | 28 +++-- scripts/server-metrics.ts | 117 ++++++++++++------- 3 files changed, 98 insertions(+), 49 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 135fb95ea6905..befd6fa1c2dbb 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -40,6 +40,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud - Steer server work by `working`: many worktree threads editing files at once with one client subscribed to all of them. Turns per minute that stay flat as threads are added mean the server, not the agents, is the bottleneck. +- Upper bounds no user hits daily, such as 20 clients reconnecting at once, run only with + `--stress`; the default reconnect is a user's 3 devices holding 10 threads each. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 70a6e52ec73c4..c0edb68319994 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -61,6 +61,15 @@ const WorkingPoint = Schema.Struct({ }); export type WorkingPoint = typeof WorkingPoint.Type; +const Reconnect = Schema.Struct({ + clients: Schema.Number, + threadsPerClient: Schema.optional(Schema.Number), + /** Drop to every subscription delivering its snapshot again. */ + resubscribedMs: Schema.Number, + loopDelayP99Ms: Schema.Number, + loopDelayMaxMs: Schema.Number, +}); + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ /** What else the machine was doing during the pass; never compared, only warned about. */ @@ -77,13 +86,10 @@ export const Measured = Schema.Struct({ Schema.Struct({ /** The quiet window by subscribed thread count. */ attached: Schema.Record(Schema.String, Window), - /** Every client drops and reconnects at once. */ - storm: Schema.Struct({ - clients: Schema.Number, - resubscribedMs: Schema.Number, - loopDelayP99Ms: Schema.Number, - loopDelayMaxMs: Schema.Number, - }), + /** A user's few devices, each holding the shell, VCS status and threads, drop and reconnect. */ + reconnect: Schema.optional(Reconnect), + /** With --stress: 20 clients holding one thread each drop and reconnect at once. */ + storm: Schema.optional(Reconnect), }), ), /** @@ -265,7 +271,9 @@ export const NOISE_RULES: ReadonlyArray = [ informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), informational(/^(streaming|pipeline)\.gcPauseMs$/), - informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), + informational( + /^(pipeline\.loopDelayMaxMs|clients\.(storm|reconnect)\.loopDelayP99Ms|quiet\.cpuPct)$/, + ), informational(/^scaling\.(cpuPct|wakeups)PerThread$/), informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), @@ -294,7 +302,8 @@ export const NOISE_RULES: ReadonlyArray = [ { pattern: /^firstWord\./, floor: 600, gate: true }, { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, - { pattern: /^clients\.storm\.resubscribedMs$/, floor: 200, gate: true }, + // The reconnect had no A/A run yet and takes the storm's floors. + { pattern: /^clients\.(storm|reconnect)\.resubscribedMs$/, floor: 200, gate: true }, { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, { pattern: /cpuPct$/, floor: 3.5, gate: true }, { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, @@ -328,6 +337,7 @@ const isMetric = (metric: string) => metric === "busy.projects" || metric === "busy.ballastMB" || metric.endsWith(".clients") || + metric.endsWith(".threadsPerClient") || metric.endsWith(".threads") || metric === "busy.largeThread.messages" || metric.startsWith("scaling.points") diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 54fc28693b3fd..cf8b85fa4e146 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -95,7 +95,10 @@ const EDIT_MARKER = "[[edit-files]]"; const PIPELINE_TURNS = 50; /** Threads working at once in each window of the working scenario. */ const WORKING_THREADS = [5, 10, 20]; -/** Clients that drop and reconnect at once in the clients scenario. */ +/** A user's devices: clients that drop and reconnect at once, each holding this many threads. */ +const RECONNECT_CLIENTS = 3; +const RECONNECT_THREADS = 10; +/** Clients that drop and reconnect at once in the opt-in storm, each holding one thread. */ const STORM_CLIENTS = 20; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; @@ -1346,6 +1349,48 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }; }); +/** + * Attaches one client per entry, each holding the shell, VCS status and its threads, lets them + * settle, then drops all of them at once and reconnects them: the time until every subscription + * delivered its snapshot again, and the loop delay across it. + */ +const reconnectAll = Effect.fn("serverMetrics.reconnectAll")(function* ( + server: Server, + token: string, + clientThreads: ReadonlyArray>, +) { + // Each client gets its own scope so they can be dropped on cue; the server's scope still closes + // any left open when a step fails or is interrupted. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + const attachAll = (scopes: ReadonlyArray) => + Effect.forEach( + scopes, + (scope, index) => + attachClient(server, token, clientThreads[index] ?? []).pipe(Scope.provide(scope)), + { concurrency: "unbounded" }, + ); + const clients = yield* Effect.forEach(clientThreads, () => clientScope); + const first = yield* attachAll(clients); + yield* Effect.sleep(Duration.seconds(10)); + yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); + yield* server.loopStart; + const dropped = yield* nowMs; + yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { + concurrency: "unbounded", + discard: true, + }); + const reopened = yield* Effect.forEach(clientThreads, () => clientScope); + const second = yield* attachAll(reopened); + const resubscribedMs = Math.round((yield* nowMs) - dropped); + const loop = yield* server.loopRead; + // The first cohort again: a loss between its check and the drop happened in the reconnect. + yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); + yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { discard: true }); + return { resubscribedMs, loopDelayP99Ms: round(loop.p99), loopDelayMaxMs: round(loop.max) }; +}); + /** * Short turns back to back on one thread: how long a send takes to reach the API, how long the * end of the reply takes to become a finished run the CLI sees (turn end and checkpoint), the time @@ -1537,6 +1582,8 @@ interface RunOptions { /** A seeded base dir for the busy scenario. */ readonly seed: string | undefined; readonly ballastMB: number; + /** Also runs the upper-bound stress cases, such as the 20-client reconnect storm. */ + readonly stress: boolean; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -1640,7 +1687,11 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* withServer("clients", (server) => Effect.gen(function* () { const token = yield* server.issueToken; - const most = Math.max(STORM_CLIENTS, ...options.threads); + const most = Math.max( + RECONNECT_THREADS, + options.stress ? STORM_CLIENTS : 0, + ...options.threads, + ); const threads = yield* openThreads(server, 0, most); const attached: Record = {}; for (const count of options.threads) { @@ -1653,49 +1704,27 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } - // Each client gets its own scope so the storm can drop them on cue; the server's scope - // still closes any left open when a step fails or is interrupted. - const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => - Scope.close(scope, exit), + const reconnect = yield* reconnectAll( + server, + token, + Array.from({ length: RECONNECT_CLIENTS }, () => threads.slice(0, RECONNECT_THREADS)), ); // Every client holds the shell, VCS status and one thread, then all drop and come back. - const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope); - const first = yield* Effect.forEach( - clients, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - yield* Effect.sleep(Duration.seconds(10)); - yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); - yield* server.loopStart; - const dropped = yield* nowMs; - yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { - concurrency: "unbounded", - discard: true, - }); - const reopened = yield* Effect.forEach(clients, () => clientScope); - const second = yield* Effect.forEach( - reopened, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - const resubscribedMs = Math.round((yield* nowMs) - dropped); - const loop = yield* server.loopRead; - // The first cohort again: a loss between its check and the drop happened in the storm. - yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); - yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { - discard: true, - }); + const storm = options.stress + ? yield* reconnectAll( + server, + token, + threads.slice(0, STORM_CLIENTS).map((thread) => [thread]), + ) + : undefined; measured.clients = { attached, - storm: { - clients: STORM_CLIENTS, - resubscribedMs, - loopDelayP99Ms: round(loop.p99), - loopDelayMaxMs: round(loop.max), + reconnect: { + clients: RECONNECT_CLIENTS, + threadsPerClient: RECONNECT_THREADS, + ...reconnect, }, + ...(storm ? { storm: { clients: STORM_CLIENTS, ...storm } } : {}), }; }), ); @@ -2112,6 +2141,12 @@ const runFlags = { ), Flag.withDefault(768), ), + stress: Flag.Boolean("stress").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Also run upper bounds no user hits daily: clients drops 20 clients at once and reconnects them. Compare stress numbers only with stress numbers.", + ), + ), soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( @@ -2130,6 +2165,7 @@ interface RunFlags { readonly busyProjects: number; readonly busyThreads: number; readonly busyBallast: number; + readonly stress: boolean; } const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( @@ -2156,6 +2192,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir, seed: undefined, ballastMB: flags.busyBallast, + stress: flags.stress, }; return options; }); From 4280147f58227ec88a5113edf46731ba9ff85adc Mon Sep 17 00:00:00 2001 From: nettee Date: Mon, 23 Nov 2026 22:26:18 +0800 Subject: [PATCH 113/288] fix(cli): clarify provider-specific model option examples (#41484) --- apps/server/src/cli/thread.ts | 2 +- docs/user/outside-agents.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 7ae729b391edb..fc3476739d1b0 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -934,7 +934,7 @@ const threadStartCommand = Command.make("start", { ), option: Flag.String("option").pipe( Flag.withDescription( - "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.", + "Model option as id=value (Codex: reasoningEffort=high; Claude: effort=high). Ids depend on the model. Repeat for more. Needs --provider and --model.", ), Flag.atLeast(0), ), diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 30c8aba13ffb1..c322becf88531 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -173,9 +173,10 @@ started in the app are. `send` never interrupts: a busy thread gets the message as its next turn. Pass `-` as the message to read it from stdin. To choose the model, pass `--provider --model `. Add -`--option id=value` for each model option, such as `--option effort=high`. -Option ids and values depend on the model; `true` and `false` set on/off -options. +`--option id=value` for each model option. For reasoning effort, Codex uses +`--option reasoningEffort=high`, while Claude uses `--option effort=high`. +Option ids and allowed values depend on the provider and model; use those +reported by `orchestrator_capabilities`. `true` and `false` set on/off options. `--wait` prints the agent's reply. It exits 1 when the run fails or stops, and 2 when the agent waits for an answer you give in the app. Add `--json` for a From 36413ad9f668356db9eeb825711d58ece6c2aeb5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:26:34 -0800 Subject: [PATCH 114/288] feat(scripts): server metrics get a --quick profile, one-line failures and a guide to the scenarios (#41373) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 2 + scripts/server-metrics-report.ts | 27 ++++ scripts/server-metrics.test.ts | 37 +++++ scripts/server-metrics.ts | 151 +++++++++++++++---- 4 files changed, 186 insertions(+), 31 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index befd6fa1c2dbb..863ccc0c7b697 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -42,6 +42,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud server, not the agents, is the bottleneck. - Upper bounds no user hits daily, such as 20 clients reconnecting at once, run only with `--stress`; the default reconnect is a user's 3 devices holding 10 threads each. +- `--quick` shortens every window for a per-PR or nightly check; `compare` refuses to mix quick + and full runs. `server-metrics --help` says which scenario to trust for what. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c0edb68319994..296320bbc1e2a 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -325,6 +325,33 @@ export function noiseRule(metric: string, rules: ReadonlyArray = NOIS return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; } +/** An error and the errors it wraps as one line, outermost first, repeats left out. */ +export function describeFailure(error: unknown): string { + const parts: string[] = []; + const seen = new Set(); + for (let at = error; at !== undefined && at !== null && !seen.has(at);) { + seen.add(at); + if (typeof at !== "object") { + parts.push(String(at)); + break; + } + const tag = "_tag" in at && typeof at._tag === "string" ? at._tag : undefined; + const message = "message" in at && typeof at.message === "string" ? at.message.trim() : ""; + const text = message || tag || String(at); + if (!parts.some((part) => part.includes(text))) parts.push(text); + at = "cause" in at ? at.cause : undefined; + } + return parts.join(": "); +} + +/** Why two files cannot be compared at all: a quick run measures shorter windows than a full one. */ +export function profileMismatch(before: ServerMetrics, after: ServerMetrics) { + const profile = (metrics: ServerMetrics) => metrics.meta.profile ?? "full"; + return profile(before) === profile(after) + ? undefined + : `before is a ${profile(before)} run and after a ${profile(after)} one; compare quick runs only with quick runs`; +} + /** Throughput, where a drop is the regression. */ export const higherIsBetter = (metric: string) => metric.endsWith("PerMin"); diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index adc86fddce588..d45e4d5c613a6 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -5,12 +5,14 @@ import { compareMetrics, competingBetween, activityRenewalMissed, + describeFailure, heapGrowth, loadWarnings, nextActivityReport, noiseReport, noisePairProblem, parsePsCpuTime, + profileMismatch, parseRunSelection, pathRewrites, pathSpellings, @@ -347,6 +349,41 @@ describe("compareMetrics on the busy shell snapshot", () => { }); }); +describe("describeFailure", () => { + it.each([ + ["a plain error", new Error("boom"), "boom"], + [ + "an RPC error wrapping the server's", + new Error("RpcClientError", { cause: new Error("Command x was already handled") }), + "RpcClientError: Command x was already handled", + ], + ["a tagged error with no message", { _tag: "TimeoutError" }, "TimeoutError"], + [ + "a cause that repeats its wrapper", + new Error("lost: gone", { cause: new Error("gone") }), + "lost: gone", + ], + ["a string", "exit 1", "exit 1"], + ])("%s", (_name, error, expected) => { + expect(describeFailure(error)).toBe(expected); + }); +}); + +describe("profileMismatch", () => { + const withProfile = (profile?: string): ServerMetrics => ({ + meta: profile === undefined ? meta : { ...meta, profile }, + runs: [], + }); + it.each([ + ["two full runs", withProfile("full"), withProfile("full"), false], + ["a file from before profiles, against a full run", withProfile(), withProfile("full"), false], + ["two quick runs", withProfile("quick"), withProfile("quick"), false], + ["a full run against a quick one", withProfile(), withProfile("quick"), true], + ])("%s", (_name, before, after, refused) => { + expect(profileMismatch(before, after) !== undefined).toBe(refused); + }); +}); + describe("heapGrowth", () => { it("lists only constructors that grew, small growth included", () => { const before = new Map([ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index cf8b85fa4e146..ef2b091607ce7 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Clock from "effect/Clock"; +import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -59,6 +60,7 @@ import { run } from "./scenarios/shell.ts"; import { compareMetrics, CpuProfile, + describeFailure, HeapProfile, HeapSnapshot, heapByConstructor, @@ -67,6 +69,7 @@ import { loadWarnings, noiseReport, noisePairProblem, + profileMismatch, round, ServerMetrics, slope, @@ -91,10 +94,41 @@ const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; /** A prompt holding this streams a reply that ends in a Write tool call, then a short answer. */ const EDIT_MARKER = "[[edit-files]]"; -/** Sequential turns in the pipeline scenario. */ -const PIPELINE_TURNS = 50; -/** Threads working at once in each window of the working scenario. */ -const WORKING_THREADS = [5, 10, 20]; +/** + * How long each scenario measures. `quick` keeps every scenario but shortens its windows, for a + * per-PR or nightly check; its numbers compare only with other quick runs. + */ +const PROFILES = { + full: { + /** Idle time before a quiet window, so startup and thread setup work has drained. */ + settleSeconds: 15, + windowSeconds: 30, + streamingSeconds: 60, + profileSeconds: 20, + /** Sequential turns in the pipeline scenario. */ + pipelineTurns: 50, + /** Threads working at once in each window of the working scenario. */ + workingThreads: [5, 10, 20], + workingWarmupSeconds: 10, + /** Long enough that most threads finish a turn inside it even at 20 working. */ + workingSeconds: 30, + threads: "0,5,10,20", + runs: 5, + }, + quick: { + settleSeconds: 5, + windowSeconds: 10, + streamingSeconds: 20, + profileSeconds: 5, + pipelineTurns: 15, + workingThreads: [5, 20], + workingWarmupSeconds: 5, + workingSeconds: 20, + threads: "0,10", + runs: 3, + }, +} as const; +type Profile = (typeof PROFILES)[keyof typeof PROFILES]; /** A user's devices: clients that drop and reconnect at once, each holding this many threads. */ const RECONNECT_CLIENTS = 3; const RECONNECT_THREADS = 10; @@ -1584,6 +1618,7 @@ interface RunOptions { readonly ballastMB: number; /** Also runs the upper-bound stress cases, such as the 20-client reconnect storm. */ readonly stress: boolean; + readonly profile: Profile; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -1613,9 +1648,21 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption name: string, body: (server: Server) => Effect.Effect, serverOptions: ServerOptions = {}, - ) => Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)); + ) => + Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)).pipe( + // Names the scenario and its cause in one line, instead of a stack from deep in the RPC client. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.fail( + new MetricsError({ + message: `the ${name} scenario failed: ${describeFailure(Cause.squash(cause))}`, + }), + ), + ), + ); const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { - const { summary, raw } = yield* server.profile(20); + const { summary, raw } = yield* server.profile(options.profile.profileSeconds); profiles[name] = summary; if (options.profileDir === undefined) return; yield* fs.makeDirectory(options.profileDir, { recursive: true }); @@ -1634,8 +1681,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption Effect.gen(function* () { measured.startup = { readyMs: server.readyMs }; if (wanted("rest")) { - yield* Effect.sleep(Duration.seconds(15)); - measured.rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + measured.rest = yield* server.measure(options.profile.windowSeconds); } if (wanted("firstWord")) { measured.firstWord = { @@ -1654,8 +1701,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption for (const threads of options.threads) { if (threads > open) yield* openThreads(server, open, threads - open); open = Math.max(open, threads); - yield* Effect.sleep(Duration.seconds(15)); - points.push({ threads, window: yield* server.measure(30) }); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + points.push({ threads, window: yield* server.measure(options.profile.windowSeconds) }); } const last = points.at(-1); if (last) measured.quiet = last.window; @@ -1698,8 +1745,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* Effect.scoped( Effect.gen(function* () { const client = yield* attachClient(server, token, threads.slice(0, count)); - yield* Effect.sleep(Duration.seconds(10)); - attached[`${count}`] = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + attached[`${count}`] = yield* server.measure(options.profile.windowSeconds); yield* client.healthy; }), ); @@ -1733,7 +1780,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* withServer("working", (server) => Effect.gen(function* () { const token = yield* server.issueToken; - const counts = WORKING_THREADS; + const counts = options.profile.workingThreads; const threads = yield* openWorktreeThreads(server, Math.max(...counts)); const active: Record = {}; for (const [index, count] of counts.entries()) { @@ -1742,7 +1789,10 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption server, token, threads.slice(0, count), - { warmupSeconds: 10, windowSeconds: 30 }, + { + warmupSeconds: options.profile.workingWarmupSeconds, + windowSeconds: options.profile.workingSeconds, + }, 30_000 + index * 10_000, ); } @@ -1761,7 +1811,11 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption if (wanted("pipeline")) { yield* withServer("pipeline", (server) => Effect.gen(function* () { - measured.pipeline = yield* pipelineTurns(environment, server, PIPELINE_TURNS); + measured.pipeline = yield* pipelineTurns( + environment, + server, + options.profile.pipelineTurns, + ); }), ); } @@ -1793,7 +1847,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); } yield* Effect.sleep(Duration.seconds(5)); - measured.streaming = yield* server.measure(60); + measured.streaming = yield* server.measure(options.profile.streamingSeconds); yield* profile(server, "streaming"); }), ); @@ -1807,8 +1861,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption (server) => Effect.gen(function* () { yield* server.ballast(options.ballastMB); - yield* Effect.sleep(Duration.seconds(30)); - const rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds * 2)); + const rest = yield* server.measure(options.profile.windowSeconds); yield* server.assertIdle(server.startedAt); const shell = yield* loadShell(server, 5); const largest = server.largest; @@ -1818,7 +1872,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const git = yield* Effect.raceFirst( Effect.gen(function* () { yield* Effect.sleep(Duration.seconds(5)); - const window = yield* server.measure(30); + const window = yield* server.measure(options.profile.windowSeconds); yield* profile(server, "busyGit"); return window; }), @@ -1866,8 +1920,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* takeSample; nextSample += 120_000; } - const threadId = - threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + // Round robin, so two soaks send the same turns to the same threads. + const threadId = threads[turn % threads.length]; if (threadId === undefined) return yield* new MetricsError({ message: "no soak threads" }); const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); @@ -2044,6 +2098,7 @@ const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOption yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), ), noAgentScope: options.noAgentScope, + profile: options.profile === PROFILES.quick ? "quick" : "full", agentScope: platform === "linux" && !options.noAgentScope && @@ -2070,6 +2125,8 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { + const mismatch = profileMismatch(before, after); + if (mismatch !== undefined) return yield* new MetricsError({ message: mismatch }); const { table, regressed, improved, informational, compared, warnings } = compareMetrics( before, after, @@ -2107,12 +2164,20 @@ const runFlags = { ), runs: Flag.Int("runs").pipe( Flag.withSchema(PositiveInt), - Flag.withDescription("firstWord runs in each variant."), - Flag.withDefault(5), + Flag.withDescription("firstWord runs in each variant. Default 5, 3 with --quick."), + Flag.optional, ), threads: Flag.String("threads").pipe( - Flag.withDescription("Open thread counts the quiet scenario measures."), - Flag.withDefault("0,5,10,20"), + Flag.withDescription( + "Open thread counts the quiet and clients scenarios measure. Default 0,5,10,20; 0,10 with --quick.", + ), + Flag.optional, + ), + quick: Flag.Boolean("quick").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Shorter windows, fewer turns and fewer points (about a third of the time), for a per-PR or nightly check. Compare quick runs only with quick runs.", + ), ), only: Flag.String("only").pipe( Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), @@ -2157,8 +2222,9 @@ const runFlags = { }; interface RunFlags { readonly noAgentScope: boolean; - readonly runs: number; - readonly threads: string; + readonly runs: Option.Option; + readonly threads: Option.Option; + readonly quick: boolean; readonly only: Option.Option; readonly soak: number; readonly seedDir: Option.Option; @@ -2174,9 +2240,10 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir: string | undefined, ) { const path = yield* Path.Path; + const profile = flags.quick ? PROFILES.quick : PROFILES.full; const selection = parseRunSelection({ only: Option.getOrElse(flags.only, () => ""), - threads: flags.threads, + threads: Option.getOrElse(flags.threads, () => profile.threads), soak: flags.soak, scenarios: SCENARIOS, }); @@ -2185,7 +2252,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( const options: RunOptions = { checkout: path.resolve(checkout), noAgentScope: flags.noAgentScope, - runs: flags.runs, + runs: Option.getOrElse(flags.runs, () => profile.runs), threads, only, soakMinutes: flags.soak, @@ -2193,6 +2260,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( seed: undefined, ballastMB: flags.busyBallast, stress: flags.stress, + profile, }; return options; }); @@ -2255,7 +2323,7 @@ const runCommand = Command.make( }, Effect.scoped), ).pipe( Command.withDescription( - "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), clients, many threads working, the turn pipeline, streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", ), ); @@ -2379,7 +2447,18 @@ const noiseCommand = Command.make( const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( - "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + `Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows. + +Which scenario answers what: + working Many threads editing files at once, one client watching all: steer performance work by its loop delay, turn end and turns per minute. + pipeline One thread's overhead per turn: send to API request, reply end to run end. + clients What an attached client costs, and a user's 3 devices reconnecting. --stress adds the 20-client storm, an upper bound. + quiet Idle cost per open thread (the scaling fit); rest is an idle server. + streaming CPU and loop delay while 5 replies stream. + firstWord A new thread's time to the API; startup is time to the first answer. Latency on a shared machine is noisy. + busy Opt-in: a copy of your real database, read-only, for costs an empty one hides. + +Trust a change only from \`ab\` on one machine. compare gates on floors measured from A/A runs (\`noise\`), shows metrics too noisy to gate on without counting them, and warns when other processes loaded the machine; rerun then. --quick suits a per-PR or nightly check; decide on full runs.`, ), Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); @@ -2393,6 +2472,16 @@ if (import.meta.main) { NodeSocket.layerWebSocketConstructor, ), ), + Effect.catchTags({ + MetricsError: (error) => + Console.error(`server-metrics: ${error.message}`).pipe( + Effect.andThen( + Effect.sync(() => { + process.exitCode = 1; + }), + ), + ), + }), NodeRuntime.runMain, ); } From 1bc44f2732ce0a24c0608626d59409f1a0893db4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 06:27:42 -0800 Subject: [PATCH 115/288] fix(server): analytics report every model name (#41237) Co-authored-by: Claude Opus 5.5 --- .../src/telemetry/ProviderDimensions.test.ts | 25 ++---- .../src/telemetry/ProviderDimensions.ts | 64 +++++---------- .../telemetry/ProviderUsageAnalytics.test.ts | 79 +++++-------------- .../src/telemetry/ProviderUsageAnalytics.ts | 8 +- docs/internals/08_product-analytics.md | 4 +- docs/user/telemetry.md | 8 +- 6 files changed, 57 insertions(+), 131 deletions(-) diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 3959d7dc78e4b..e24bb480d1e24 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -7,20 +7,15 @@ const provider = ( instanceId: string, driver: string, models: ReadonlyArray<{ slug: string; isCustom: boolean }>, - auth: Record = {}, ) => ({ instanceId: ProviderInstanceId.make(instanceId), driver, - auth: { status: "authenticated", ...auth }, models, }) as unknown as ServerProvider; const providers = [ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), - provider("azure-codex", "codex", [{ slug: "gpt-acme-finetune", isCustom: false }], { - endpoint: "https://acme.example.com", - }), provider("claudeAgent", "claudeAgent", [ { slug: "claude-opus-5-5", isCustom: false }, { slug: "my-private-finetune", isCustom: true }, @@ -42,17 +37,13 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, endpoint-served, and unknown models and instance names", () => { +it("reports every model name but never instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", providers, caller: thread("claudeAgent", "my-private-finetune"), - targets: [ - thread("opencode", "ollama/acme-internal"), - thread("removed-instance", "gpt-5.5"), - thread("azure-codex", "gpt-acme-finetune"), - ], + targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], outcome: { outcome: "ok" }, }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ callerProvider, @@ -63,22 +54,16 @@ it("omits custom, user-configured, endpoint-served, and unknown models and insta ).toEqual([ { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "opencode", - targetModel: undefined, + targetModel: "ollama/acme-internal", }, { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "unknown", targetModel: undefined, }, - { - callerProvider: "claudeAgent", - callerModel: undefined, - targetProvider: "codex", - targetModel: undefined, - }, ]); }); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 497f1e660131b..7aa44cd46727b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -13,8 +13,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are - * user-defined, so only the driver kind is reported. The model is reported - * only when the selected instance's vendor catalog lists it. + * user-defined, so only the driver kind is reported. */ export function providerDimensions( providers: ReadonlyArray, @@ -22,15 +21,16 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = vendorCatalogEntry(provider, [selection.model]); - return model === undefined - ? { provider: provider.driver } - : { provider: provider.driver, model: model.slug }; + return { provider: provider.driver, model: modelLabel(providers, selection.model) }; } const DATED_SNAPSHOT = /-\d{8}$/u; +// Absolute, home, relative, or Windows paths, such as a local GGUF file. Directories can name the user. +const FILE_PATH = /^(?:[/~]|\.{1,2}[/\\]|[A-Za-z]:[\\/])|\\/u; + +const fileName = (model: string) => + FILE_PATH.test(model) ? model.slice(model.search(/[^/\\]*$/u)) : model; -// The bundled manifest is reviewed in this repo. Vendor catalogs ship models before it does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -39,43 +39,17 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ); -// Drivers whose model lists come from the vendor. OpenCode, Pi, and ACP agents list the -// user's own configuration, such as local Ollama tags. Codex and Claude also list -// early-access code names, so only slugs in the vendor's public family vouch for them. -const VENDOR_CATALOGS: ReadonlyMap = new Map([ - ["cursor", undefined], - ["grok", undefined], - ["antigravity", undefined], - ["codex", /^gpt-/u], - ["claudeAgent", /^claude-/u], -]); - -// A custom endpoint or gateway serves whatever names its owner chose. -const isVendorRouted = (auth: ServerProvider["auth"]) => - auth.endpoint === undefined && auth.type !== "customEndpoint" && auth.type !== "bedrock"; - -function vendorCatalogEntry(provider: ServerProvider, candidates: ReadonlyArray) { - if (!VENDOR_CATALOGS.has(provider.driver) || !isVendorRouted(provider.auth)) return undefined; - const family = VENDOR_CATALOGS.get(provider.driver); - return provider.models.find( - (entry) => - !entry.isCustom && - (family === undefined || family.test(entry.slug)) && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), - ); -} - /** - * The vendor catalog slug that a native or routed model id names, such as - * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and vendor-routed provider catalogs, including user-added ones and - * names a custom endpoint serves, return undefined. + * The model name analytics reports. A routed id, alias, or dated snapshot that the + * bundled manifest or a provider's model list knows, such as `anthropic/claude-opus-5-5` + * or `antigravity-default`, maps to its catalog slug. A file path reports only its file + * name. Any other id is reported as is. */ -export function catalogModelLabel( - providers: ReadonlyArray, - model: string, -): string | undefined { +export function modelLabel(providers: ReadonlyArray, model: string): string { + return fileName(catalogSlug(providers, model) ?? model); +} + +function catalogSlug(providers: ReadonlyArray, model: string) { const leaf = model.slice(model.lastIndexOf("/") + 1); const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")]; for (const candidate of candidates) { @@ -83,7 +57,11 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - const match = vendorCatalogEntry(provider, candidates); + const match = provider.models.find( + (entry) => + candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true, + ); if (match !== undefined) return match.slug; } return undefined; diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 0ce417e9a2c8b..14e4a8b68633b 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -15,7 +15,7 @@ import * as Layer from "effect/Layer"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; import { ProviderTurnAnalytics, RequestUsageLedger, @@ -26,29 +26,9 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Vendor-routed Codex lists OpenAI's catalog, including early-access code names. - { - driver: "codex", - models: [{ slug: "gpt-6-sol" }, { slug: "gpt-6.2-sol" }, { slug: "nova-alpha" }], - }, - // A custom endpoint serves whatever its owner chose, including private deployments. - { - instanceId: "azure-codex", - driver: "codex", - auth: { endpoint: "https://acme.example.com" }, - models: [{ slug: "acme-azure-deployment" }, { slug: "gpt-acme-finetune" }], - }, - { - driver: "claudeAgent", - models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }, { slug: "claude-opus-6" }], - }, - { - instanceId: "claude-gateway", - driver: "claudeAgent", - auth: { type: "customEndpoint" }, - models: [{ slug: "claude-ops-internal" }], - }, - { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, + { driver: "codex", models: [{ slug: "gpt-6-sol" }] }, + { driver: "pi", models: [{ slug: "/Users/jane/models/llama.gguf", aliases: ["pi-local"] }] }, + { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, // Antigravity ships models before the bundled manifest lists them. { driver: "antigravity", @@ -58,25 +38,14 @@ const providers = [ ], }, ].map( - ({ - instanceId, - driver, - auth, - models, - }: { - instanceId?: string; - driver: string; - auth?: Record; - models: ReadonlyArray<{ slug: string; aliases?: ReadonlyArray }>; - }) => + ({ driver, models }) => ({ - instanceId: ProviderInstanceId.make(instanceId ?? driver), + instanceId: ProviderInstanceId.make(driver), driver, - auth: { status: "authenticated", ...auth }, models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); -const label = (model: string) => catalogModelLabel(providers, model); +const label = (model: string) => modelLabel(providers, model); const at = (ms: number) => DateTime.makeUnsafe(ms); const complete = (input: number, output: number, extra: Partial = {}) => @@ -335,7 +304,7 @@ describe("provider usage reporting", () => { }); }); - it("reports routed catalog models and closed efforts only", () => { + it("reports every model name and closed efforts only", () => { const routed = (model: string, variant: string) => providerTurnProperties( { @@ -356,30 +325,22 @@ describe("provider usage reporting", () => { observedModel: "claude-opus-5-5", effort: "high", }); - for (const local of [ - routed("ollama/acme-internal", "secret-variant"), - routed("acme-azure-deployment", "high"), - ]) { - expect(local).not.toHaveProperty("model"); - expect(local).not.toHaveProperty("observedModel"); - } - expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); + const local = routed("ollama/acme-internal", "secret-variant"); + expect(local).toMatchObject({ + model: "ollama/acme-internal", + observedModel: "ollama/acme-internal", + }); + expect(local).not.toHaveProperty("effort"); }); - it("reports vendor catalog models the bundled manifest does not list", () => { + it("maps provider catalog aliases to their slug and file paths to their file name", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); - expect(label("gemini-4-unlisted")).toBeUndefined(); - expect(label("gpt-6.2-sol")).toBe("gpt-6.2-sol"); - expect(label("claude-opus-6")).toBe("claude-opus-6"); - for (const hidden of [ - "nova-alpha", - "acme-azure-deployment", - "gpt-acme-finetune", - "claude-ops-internal", - ]) { - expect(label(hidden)).toBeUndefined(); - } + expect(label("/Users/jane/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("~/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("C:\\Users\\jane\\qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("../jane/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("pi-local")).toBe("llama.gguf"); }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d5..a281f40479b55 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -26,7 +26,7 @@ import { } from "@t3tools/shared/model"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; // Bump when a field changes meaning, so reports can split old and new rows. const REPORT_VERSION = 2; @@ -74,8 +74,8 @@ export interface RunSettledReport { } type Properties = Readonly>; -/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */ -export type ModelLabeler = (model: string) => string | undefined; +/** Maps a native model id to the name analytics reports. */ +export type ModelLabeler = (model: string) => string; const TERMINAL_STATUSES: ReadonlySet = new Set([ "completed", @@ -403,7 +403,7 @@ export const layer = Layer.effect( registry.getProviders, (providers): ModelLabeler => (model) => - catalogModelLabel(providers, model), + modelLabel(providers, model), ); return { runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) => diff --git a/docs/internals/08_product-analytics.md b/docs/internals/08_product-analytics.md index 24cb8b04e39f9..375f6be84b857 100644 --- a/docs/internals/08_product-analytics.md +++ b/docs/internals/08_product-analytics.md @@ -28,7 +28,9 @@ an authenticated connection does not count as product use. - Payloads stay strictly to product metadata, closed contract enums, and normalized measurements: never attach prompts, file paths, credentials, raw provider payloads, device names, conversation - IDs, user-named provider instance IDs, or non-vendor/custom model names. + IDs, or user-named provider instance IDs. Model IDs are reported as the provider used them, + including custom models; known aliases and routed IDs map to one catalog slug, and a model + that is a file path reports only its file name. - The sole exception is opt-in `agent.feedback`, which [`FeedbackService`](../../apps/server/src/feedback/FeedbackService.ts) scrubs of paths, private values, and secret-shaped strings, and only attaches bounded conversation traces when the user diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 4c6b3f20eaad5..be7fdd938ff06 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -6,8 +6,8 @@ uses, the server also sends hashed account identifiers: your T3 Connect account, Claude accounts when you are signed in, and a random identifier for each device that connects. The endpoint keeps a copy of each event and forwards events to PostHog. Events include the provider, model, reasoning effort, permission mode, turn and request results, duration, release channel, and token counts when -available. Child-agent token counts are reported separately from the main agent's. Model names -are sent only when they appear in a provider's public model list. +available. Child-agent token counts are reported separately from the main agent's. Events include +the model ID the provider used, including custom models and models served by a custom endpoint. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), @@ -52,8 +52,8 @@ Before anything is saved, T3 Code removes file paths (when text mentions one, th goes with it), your user name, machine name, project title, branch, and git remote, and anything that looks like a key, token, email address, or URL with a password. It cannot recognise your code or a name written in a sentence, so only include the conversation when it holds nothing you would -not send. Reports from agents also name the provider, and the model when it is from the provider's -public model list. No thread IDs or project IDs are sent. +not send. Reports from agents also name the provider and the model. No thread IDs or project IDs +are sent. Reports are saved on your machine first, and a declined one is not saved at all; its card keeps only what you would have sent without the conversation. When product usage From 5793cadee461914c83f714cd71d279330e21036b Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 16:47:17 +0200 Subject: [PATCH 116/288] fix(server): workflows find a project named by its Windows folder (#41456) Co-authored-by: Julius Marminge --- .../src/workflows/WorkflowAgentLinks.test.ts | 51 +++++++++++++++---- .../src/workflows/WorkflowAgentLinks.ts | 14 ++++- apps/server/src/workflows/WorkflowAgents.ts | 4 +- .../src/workflows/WorkflowForge.test.ts | 21 ++++++++ 4 files changed, 76 insertions(+), 14 deletions(-) diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index 92b7a4f7b2fff..8fcba6dc9f3f8 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -113,26 +113,55 @@ it.effect("starts a thread there by the project's folder, with the step's key as ); it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + for (const [project, title] of [ + [input.project, "app"], + ["/work/team\\api", "team\\api"], + ["C:\\work\\app", "app"], + ]) { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: project }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", title], + ["t3_thread_launch", "p-new"], + ], + ); + } + }), +); + +it.effect("finds a Windows folder there however its separators are written", () => Effect.gen(function* () { const there = peer({ - t3_project_list: [{ projects: [], nextCursor: null }], - t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_project_list: [ + { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null }, + ], t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], }); yield* Effect.provide( Effect.flatMap(WorkflowAgentLinks.make, (links) => - links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + links.start( + { ...input, project: "C:/work/app" }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), ), there.layer, ); - assert.deepStrictEqual( - there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), - [ - ["t3_project_list", undefined], - ["t3_project_create", "app"], - ["t3_thread_launch", "p-new"], - ], - ); + assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app"); }), ); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 6a0836fc0162c..8d0bdc1d0c672 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -7,6 +7,11 @@ import { OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; +import { + fileBasename, + isWindowsDrivePath, + normalizeProjectPathForComparison, +} from "@t3tools/shared/path"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -77,6 +82,7 @@ export const make = Effect.gen(function* () { environment: string, path: string, ) { + const target = normalizeProjectPathForComparison(path); let cursor: number | null = 0; while (cursor !== null) { const page: Schema.Schema.Type = @@ -86,7 +92,9 @@ export const make = Effect.gen(function* () { ProjectToolkit.tools.t3_project_list.successSchema, { cursor, limit: 100 }, ); - const found = page.projects.find((project) => project.workspaceRoot === path); + const found = page.projects.find( + (project) => normalizeProjectPathForComparison(project.workspaceRoot) === target, + ); if (found !== undefined) return found.id; cursor = page.nextCursor; } @@ -104,7 +112,9 @@ export const make = Effect.gen(function* () { ) { const known = yield* listed(environment, path); if (known !== undefined) return known; - const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const title = isWindowsDrivePath(path) + ? fileBasename(path) + : (path.split("/").findLast((part) => part.length > 0) ?? path); const created = yield* call( environment, "t3_project_create", diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts index 674b72c69aa3d..834a781340269 100644 --- a/apps/server/src/workflows/WorkflowAgents.ts +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -4,6 +4,7 @@ import type { ProviderInteractionMode, RuntimeMode, } from "@t3tools/contracts"; +import { isWindowsDrivePath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; import type * as Effect from "effect/Effect"; @@ -67,7 +68,8 @@ export const launchOnContinue = new WorkflowAgentError({ }); /** A project named by its folder instead of its id. */ -export const isProjectPath = (project: string) => project.startsWith("/"); +export const isProjectPath = (project: string) => + project.startsWith("/") || isWindowsDrivePath(project); /** Where agent steps run. The server implements it with threads; tests stand in for it. */ export class WorkflowAgents extends Context.Service< diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts index 58f9626423510..1d402227c57b4 100644 --- a/apps/server/src/workflows/WorkflowForge.test.ts +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -85,6 +85,27 @@ it.effect("what a step does through the forge is kept against it, one key per th }).pipe(Effect.provide(forge)), ); +it.effect("a step can name its project by a Windows folder", () => + Effect.gen(function* () { + const { pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + for (const project of ["C:\\Users\\me\\app", "C:/Users/me/app"]) { + yield* Effect.provideContext( + pullRequests.act({ project, url: "https://github.com/Me/App/pull/7" }, "merge"), + inStep, + ); + } + const address = { projectId, host: "github.com", repository: "me/app", number: 7 }; + assert.deepStrictEqual( + noted.map((reference) => reference.address), + [address, address], + ); + }).pipe(Effect.provide(forge)), +); + it("a step's pull requests are the ones its thread was linked to while it ran", () => { const link = (number: number, linkedAt: string, source = "agent") => ({ host: "github.com", From fd0331ca9b1596ed7018c80f52b7e6730014f593 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 16:48:20 +0200 Subject: [PATCH 117/288] fix(client-runtime): a workflow reply with no space before the limit is cut at the limit (#41488) Co-authored-by: Julius Marminge --- packages/client-runtime/src/workflows.test.ts | 3 +++ packages/client-runtime/src/workflows.ts | 10 +++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index 9fce777fd5642..14991a1c65438 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -298,6 +298,9 @@ describe("workflowSaidStart", () => { expect(workflowSaidStart(said, 200)).toBeNull(); expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5."); expect(workflowSaidStart(said, 10)).toBe("It is a real bug."); + const unspaced = "这个问题出现在解析器中。".repeat(60); + expect(workflowSaidStart(unspaced, 10)).toBe("这个问题出现在解析器…"); + expect(workflowSaidStart("😀".repeat(30), 9)).toBe(`${"😀".repeat(4)}…`); }); }); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts index 3808f94703237..2a4eac6c00b45 100644 --- a/packages/client-runtime/src/workflows.ts +++ b/packages/client-runtime/src/workflows.ts @@ -700,7 +700,15 @@ export function workflowSaidStart(said: string, limit: number): string | null { kept = `${kept}\n\n${paragraph}`; } // One paragraph that runs on is cut at a word, which can still split markup but not a word. - if (kept.length > limit * 2) kept = `${kept.slice(0, kept.lastIndexOf(" ", limit))}…`; + // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a + // surrogate pair. + if (kept.length > limit * 2) { + const space = kept.lastIndexOf(" ", limit); + const before = kept.charCodeAt(limit - 1); + const highSurrogateLast = before >= 0xd800 && before <= 0xdbff; + const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit; + kept = `${kept.slice(0, end)}…`; + } return kept === said ? null : kept; } From 9d6c750a75ba9d6763e9632b8b820b17f5ee9078 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:49:01 -0800 Subject: [PATCH 118/288] test(web): load history documents without re-evaluating the app graph (#41497) From 28c58b19b58b6e4f129da288190befa9fefe9192 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:52:35 -0800 Subject: [PATCH 119/288] fix(server): an unfinished control sequence no longer delays terminal output (#41420) Co-authored-by: viktorce --- apps/server/src/terminal/Manager.test.ts | 126 +++++++++++++++++++++++ apps/server/src/terminal/Manager.ts | 92 +++++++++++++---- 2 files changed, 197 insertions(+), 21 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 8af803db1fd8c..aa0953142aac9 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -3,6 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_TERMINAL_ID, ProjectId, ThreadId, @@ -488,6 +489,98 @@ it("restores bounded history across append compaction, clears and split Unicode" expect(persisted).toBe("z".repeat(maxBytes)); }); +it("stops holding a control sequence that outgrows its limit", () => { + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + // No final byte for a CSI and no terminator for a string. + const filler = "0123456789 123\r\n".repeat(64); + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + // The terminal runs the line breaks inside a CSI while it waits for the final byte. + const lineBreaks = fed.replaceAll(/[^\r\n]/g, ""); + for (const { name, open, end, history } of [ + { name: "OSC, BEL", open: ["\u001b]0;"], end: ["\u0007"], history: "\u001b\\" }, + { + name: "OSC, split ST", + open: ["\u001b]0;"], + end: ["\u001b", "\\\u001b[31m"], + history: "\u001b\\\u001b[31m", + }, + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends the DCS and replays as ESC E. + { + name: "DCS, split code point", + open: ["\u001bPstuck"], + end: ["\ud842", "\udc05"], + history: "\u001b\\\u001bE", + }, + // The dropped CSI's ESC ended the title, so history ends it too. Its final byte would have + // made it a query that the replay answers. + { + name: "CSI after a title its ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["\n6n"], + history: `\u001b]0;title\u001b\\${lineBreaks}\n`, + }, + { + name: "CSI, ESC", + open: ["\u001b["], + end: ["\n\u001b[31m"], + history: `\u001b\\${lineBreaks}\n\u001b[31m`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + + feed("before\n"); + for (const data of open) feed(data); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(3); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history}after\n`); + } + + // Held text of exactly the limit stays held, and a sequence that ends in the chunk where it + // passes the limit is kept whole. + for (const atLimit of ["\u001b]".padEnd(limit, "0"), "\u001b[".padEnd(limit, "0")]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", atLimit)).toEqual({ + visibleText: "", + pendingControlSequence: atLimit, + }); + const ended = `${atLimit}0${atLimit[1] === "]" ? "\u0007" : "m"}`; + expect(TerminalManager.sanitizeTerminalHistoryChunk("", ended)).toEqual({ + visibleText: ended, + pendingControlSequence: "", + }); + } + + // An escape sequence keeps its first four intermediates, the only ones libghostty reads. + const escape = '\u001b!"#$'; + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&")).toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&B")).toEqual({ + visibleText: `${escape}%&B`, + pendingControlSequence: "", + }); + + // A completed escape sequence stays when another ESC follows it at once. + for (const kept of ["OLD\u001bc\u001b[31mNEW", "abc\u001b7\u001b[2;5HB\u001b8Z"]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", kept)).toEqual({ + visibleText: kept, + pendingControlSequence: "", + }); + } +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1756,6 +1849,39 @@ it.layer( }), ); + it.effect("starts a snapshot inside the sequence the terminal has not finished", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputs = yield* Queue.unbounded(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Queue.offer(outputs, undefined).pipe(Effect.asVoid) : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const historyAfter = Effect.fnUntraced(function* (data: string) { + process.emitData(data); + yield* Queue.take(outputs); + return (yield* manager.open(openInput())).history; + }); + + expect(yield* historyAfter("A\u001b]0;ti")).toBe("A\u001b]0;ti"); + // A long string would push history out of the client's budget, so its payload is left out. + expect(yield* historyAfter("x".repeat(4_096))).toBe("A\u001b]"); + // Past the limit only the introducer is left to replay. + expect(yield* historyAfter("x".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES))).toBe( + "A\u001b\\\u001b]", + ); + expect(yield* historyAfter("\u0007B")).toBe("A\u001b\\B"); + + // Saved history has no live output to finish the sequence. + process.emitData("\u001b]0;open"); + yield* Queue.take(outputs); + yield* manager.close({ threadId: "thread-1" }); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("A\u001b\\B"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e87ba67cf5837..92600d0a326a8 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -415,7 +415,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: session.history.value() + unfinishedSequenceReplay(session), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -1394,7 +1394,32 @@ function findEscapeSequenceEndIndex(input: string, start: number): number | null const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); -function sanitizeTerminalHistoryChunk( +// Clients keep this much output and drop a sequence their trim cuts through, so none of them +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// ESC and four intermediates: libghostty ignores every intermediate past the fourth. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit and stays out of history. Only its +// introducer is still held, with a final ESC or high surrogate that may begin its end. Other held +// text starts with ESC. +const OVERSIZED_SEQUENCE = "\u0018"; +// Stands in for the ESC of an oversized sequence, which ended any string history left open. +const STRING_TERMINATOR = "\u001b\\"; + +// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the +// client's budget or add its size to every resync. +const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; + +// History leaves out the sequence the terminal is still inside. A client that starts from a +// snapshot needs it, or it prints the rest of the sequence as text. +function unfinishedSequenceReplay(session: TerminalSessionState): string { + const held = session.pendingHistoryControlSequence; + if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); + if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; + return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); +} + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1402,9 +1427,12 @@ function sanitizeTerminalHistoryChunk( return { visibleText: data, pendingControlSequence: "" }; } - const input = `${pendingControlSequence}${data}`; - // Only the pending prefix's final ESC can begin a terminator split across chunks. - const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); + const resumesOversized = pendingControlSequence.startsWith(OVERSIZED_SEQUENCE); + const held = resumesOversized ? pendingControlSequence.slice(1) : pendingControlSequence; + const input = `${held}${data}`; + // Only the held text's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, held.length - 1); let visibleText = ""; let index = 0; // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. @@ -1421,6 +1449,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const oversized = resumesOversized && index === 0; const contentStart = prefix.length > 0 ? index : index + 2; const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { @@ -1428,19 +1457,21 @@ function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has not ended, so only its last code unit is scanned again. + let cursor = index === 0 ? Math.max(contentStart, pendingScanStart) : contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. - let body = ""; - let executedControls = ""; + const executedControls = () => + input.slice(contentStart, cursor).replace(/[^\x00-\x0f]+/g, ""); while (cursor < input.length) { const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); + if (!oversized && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1452,10 +1483,10 @@ function sanitizeTerminalHistoryChunk( if (c1) { // The CSI ends here undispatched, so it is kept only when the terminal is back in // ground with nothing to answer. - if (c1.next.length === 0 && !c1.query) { + if (!oversized && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { - append(executedControls + c1.safe); + append(executedControls() + c1.safe); } c1Introducer = c1.next; index = end; @@ -1466,19 +1497,24 @@ function sanitizeTerminalHistoryChunk( } // An ESC abandons the CSI and starts the next sequence, which may be stripped. if (cursorCodePoint === 0x1b) { - append(executedControls); + append(executedControls()); index = cursor; break; } - if (cursorCodePoint < 0x10) { - executedControls += input[cursor]; - } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { - body += input[cursor]; - } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + // The terminal has run these controls already, so history takes them as they come. + append((oversized ? "" : STRING_TERMINATOR) + executedControls()); + const endStart = /[\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: `${OVERSIZED_SEQUENCE}\u001b[${endStart}`, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } continue; } @@ -1495,7 +1531,16 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + append(oversized ? "" : STRING_TERMINATOR); + const endStart = /[\u001b\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: OVERSIZED_SEQUENCE + unfinished.slice(0, 2) + endStart, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( @@ -1505,6 +1550,7 @@ function sanitizeTerminalHistoryChunk( // has its own terminator. Without one, the query ends at the next ESC, which history may // strip, so ST would not replay the same and the query stays. if ( + !oversized && nextCodePoint === 0x5d && isOscPaletteQuery(content) && /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) @@ -1514,6 +1560,7 @@ function sanitizeTerminalHistoryChunk( continue; } const strip = + oversized || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1532,7 +1579,10 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) { From fab237d62629925f271f4b48f2ffa4eedc95a271 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:56:56 -0800 Subject: [PATCH 120/288] fix(server): service commands no longer stop systemd-oomd watching the user manager (#41495) --- apps/server/src/cloud/bootService.test.ts | 2 + apps/server/src/cloud/bootService.ts | 20 +++--- .../src/cloud/serviceLauncherClient.test.ts | 36 +++++++++- .../server/src/cloud/serviceLauncherClient.ts | 64 +++++++++++------ apps/server/src/cloud/serviceProtection.ts | 11 +-- apps/server/src/cloud/userManagerOom.test.ts | 72 +++++++++++++++++++ apps/server/src/cloud/userManagerOom.ts | 22 ++++++ apps/server/src/serviceLauncher.test.ts | 2 +- apps/server/src/serviceLauncher.ts | 16 ++++- 9 files changed, 206 insertions(+), 39 deletions(-) create mode 100644 apps/server/src/cloud/userManagerOom.test.ts create mode 100644 apps/server/src/cloud/userManagerOom.ts diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154d..8e69e7cdcd7af 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { decodeServiceUnit, disabledServiceTask, @@ -1406,6 +1407,7 @@ process.disconnect(); const outcome = yield* inside.restart; expect(commands).toEqual([ "systemctl --user daemon-reload", + `/bin/sh -c ${RESTORE_OOMD_WATCH_SCRIPT}`, "systemctl --user enable t3code.service", "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec8641931..3a930f02dabc1 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -19,6 +19,7 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { serviceLauncherIsRunning, serviceLauncherLockPath, @@ -329,12 +330,21 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], }; - const prepareActivation = [ + const reload = [ { step: "reloading systemd user units", command: "systemctl", args: ["--user", "daemon-reload"], }, + { + step: "restoring systemd-oomd's watch on the user manager", + optional: true, + command: "/bin/sh", + args: ["-c", RESTORE_OOMD_WATCH_SCRIPT], + }, + ]; + const prepareActivation = [ + ...reload, { step: "enabling the service", command: "systemctl", @@ -388,13 +398,7 @@ function systemdManager(input: { timeout: STOP_STEP_TIMEOUT, }, ], - finalize: [ - { - step: "reloading systemd user units", - command: "systemctl", - args: ["--user", "daemon-reload"], - }, - ], + finalize: reload, }; } diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 85661360020f6..8c52725dd8a3c 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -6,6 +6,7 @@ import * as PlatformError from "effect/PlatformError"; import { assert, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import { @@ -83,11 +84,42 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); host.env["HOME"] = root; - const client = yield* makeClient(host, "1.1.0"); + // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored. + const bin = path.join(root, "bin"); + const calls = path.join(root, "systemctl-calls"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + [ + "#!/bin/sh", + `echo "$*" >>'${calls}'`, + 'case "$*" in', + " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;", + " *ManagedOOMMemoryPressureLimit*) echo 0 ;;", + " *ManagedOOMMemoryPressure\\ *) echo kill ;;", + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + host.env["PATH"] = `${bin}:/usr/bin:/bin`; + const sentPrepared = yield* Deferred.make(); + const send = host.send; + host.send = (message, callback) => { + Deferred.doneUnsafe(sentPrepared, Effect.void); + return send(message, callback); + }; + const client = yield* makeClient(host, "1.1.0").pipe( + Effect.provideService(HostProcess.Platform, "linux"), + ); const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { startImmediately: true, }); - yield* Effect.yieldNow; + yield* Deferred.await(sentPrepared); + // Nothing runs systemctl after "prepared", so the log is what ran before it. + expect(yield* fs.readFileString(calls)).toContain( + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill", + ); expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index 3e7f4abfc2d57..50b596b0e30d5 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -8,6 +8,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import packageJson from "../../package.json" with { type: "json" }; import { @@ -24,6 +26,7 @@ import { type ServiceLauncherParentMessage, type SupportedLauncherProtocol, } from "./serviceProtocol.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; export class ServiceLauncherClientError extends Schema.TaggedError()( "ServiceLauncherClientError", @@ -264,6 +267,22 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o const path = yield* Path.Path; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // The launcher that commits a remote update is the old one; its reload after commit + // keeps oomd's watch only if the policy is mirrored before it. + const keepOomdWatch = + platform === "linux" + ? spawner + .exitCode( + ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + env: environment, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.timeout("30 seconds"), Effect.ignore) + : Effect.void; const exchange = ( message: ServiceLauncherChildMessage, @@ -343,28 +362,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o : context.update; const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined - ? exchange( - { type: "prepared", updateId: pending.id }, - (reply) => reply.type === "committed" && reply.updateId === pending.id, - ).pipe( - Effect.flatMap((reply) => - reply.type !== "committed" - ? Effect.die("service launcher returned an impossible prepared response") - : repointLaunchers({ - baseDir: input.baseDir, - targetVersion: pending.targetVersion, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Path.Path, path), - Effect.provideService(HostProcess.Environment, environment), - Effect.provideService(HostProcess.Platform, platform), - Effect.as({ - id: pending.id, - fromVersion: pending.fromVersion, + ? Effect.andThen( + keepOomdWatch, + exchange( + { type: "prepared", updateId: pending.id }, + (reply) => reply.type === "committed" && reply.updateId === pending.id, + ).pipe( + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, targetVersion: pending.targetVersion, - status: "committed" as const, - }), - ), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index 48790bcf6cc05..a8952ce299fd9 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -8,6 +8,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; const PROTECT_DROP_IN = "90-t3code-protect.conf"; const SYSTEM_UNIT_DIR = "/etc/systemd/system"; @@ -210,10 +211,12 @@ export const detectRemoteAccessUnits = run("list remote-access services", "syste Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), ); -const reloadUserManager = run("reload systemd user units", "systemctl", [ - "--user", - "daemon-reload", -]); +const reloadUserManager = Effect.andThen( + run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]), + run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe( + Effect.ignore, + ), +); const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( dropIns: ReadonlyArray, diff --git a/apps/server/src/cloud/userManagerOom.test.ts b/apps/server/src/cloud/userManagerOom.test.ts new file mode 100644 index 0000000000000..67c0e51e11639 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; + +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; + +const userService = "/user.slice/user-1001.slice/user@1001.service"; + +it.each([ + [ + "mirrors the system manager's kill policy onto the user manager's root slice", + { cgroup: userService, mode: "kill", limit: "4252017622", duration: "" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=99.00%", + ], + [ + "keeps a custom duration and an unset limit", + { cgroup: userService, mode: "kill", limit: "0", duration: "20s" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=0.00% ManagedOOMMemoryPressureDurationSec=20s", + ], + [ + "leaves the slice alone when oomd is not told to kill", + { cgroup: userService, mode: "auto", limit: "0", duration: "infinity" }, + undefined, + ], + [ + "leaves the slice alone outside a user@ service", + { cgroup: "/system.slice/foo.service", mode: "kill", limit: "0", duration: "infinity" }, + undefined, + ], +])("%s", (_name, system, expected) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oomd-")); + try { + const calls = NodePath.join(root, "calls"); + NodeFS.writeFileSync( + NodePath.join(root, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *ControlGroup*) echo "$CGROUP" ;;', + ' *ManagedOOMMemoryPressureLimit*) echo "$LIMIT" ;;', + ' *ManagedOOMMemoryPressureDurationUSec*) echo "$DURATION" ;;', + ' *ManagedOOMMemoryPressure\\ *) echo "$MODE" ;;', + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + encoding: "utf8", + env: { + PATH: `${root}:/usr/bin:/bin`, + CALLS: calls, + CGROUP: system.cgroup, + MODE: system.mode, + LIMIT: system.limit, + DURATION: system.duration, + }, + }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + const setProperty = NodeFS.readFileSync(calls, "utf8") + .split("\n") + .find((call) => call.includes("set-property")); + expect(setProperty).toBe(expected); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/cloud/userManagerOom.ts b/apps/server/src/cloud/userManagerOom.ts new file mode 100644 index 0000000000000..6f23427b83999 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.ts @@ -0,0 +1,22 @@ +/** + * Run after `systemctl --user daemon-reload`. The user manager's -.slice shares the cgroup of + * user@.service and reports it to systemd-oomd as `auto` on reload, which drops the system + * manager's `kill` watch (systemd/systemd#43174). Mirroring that policy onto -.slice restores the + * watch and keeps it through later reloads. Best effort: exits 0 when there is nothing to mirror. + */ +export const RESTORE_OOMD_WATCH_SCRIPT = [ + "unit=$(systemctl --user show --property=ControlGroup --value -- -.slice) || exit 0", + "unit=${unit##*/}", + "case $unit in user@*.service) ;; *) exit 0 ;; esac", + 'show() { systemctl show --property="$1" --value "$unit"; }', + '[ "$(show ManagedOOMMemoryPressure)" = kill ] || exit 0', + "limit=$(show ManagedOOMMemoryPressureLimit)", + "case $limit in '' | *[!0-9]*) exit 0 ;; esac", + // The limit is a fraction of 2^32; set-property takes a percentage. + "p=$(( (limit * 10000 + 2147483648) / 4294967296 ))", + 'set -- ManagedOOMMemoryPressure=kill "ManagedOOMMemoryPressureLimit=$((p / 100)).$(printf %02d $((p % 100)))%"', + "duration=$(show ManagedOOMMemoryPressureDurationUSec)", + 'case $duration in "" | infinity) ;; *) set -- "$@" "ManagedOOMMemoryPressureDurationSec=$duration" ;; esac', + 'exec systemctl --user set-property --runtime -- -.slice "$@"', + "", +].join("\n"); diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index c7259b4bd84fb..0f51100fb368b 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -553,7 +553,7 @@ setInterval(() => {}, 1_000); ); yield* fs.writeFileString( path.join(bin, "systemctl"), - `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`, + `#!/bin/sh\n[ "$*" = "--user daemon-reload" ] && echo reload >> '${path.join(root, "reloads")}'\n`, ); yield* fs.chmod(path.join(bin, "busctl"), 0o755); yield* fs.chmod(path.join(bin, "systemctl"), 0o755); diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 8dcd7886fce51..3c6bdf6913187 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -224,8 +225,8 @@ async function serviceUnitFromEnvironment( ); return { path: NodePath.join(unitDir, unitName), - reload: () => - new Promise((resolve, reject) => { + reload: async () => { + await new Promise((resolve, reject) => { NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], { stdio: "ignore", timeout: 30_000, @@ -236,7 +237,16 @@ async function serviceUnitFromEnvironment( ? resolve() : reject(new Error(`systemctl --user daemon-reload exited with ${code ?? signal}`)), ); - }), + }); + await new Promise((resolve) => { + NodeChildProcess.spawn("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + stdio: "ignore", + timeout: 30_000, + }) + .once("error", () => resolve()) + .once("exit", () => resolve()); + }); + }, }; } From 0948100035d7710b3d5410fee975f8960c1824eb Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Mon, 23 Nov 2026 15:01:08 +0000 Subject: [PATCH 121/288] fix(server): a compaction or manual continuation keeps its session busy like a turn (#41490) Co-authored-by: Julius Marminge --- .../ProviderSessionManager.test.ts | 99 +++++++++++ .../ProviderSessionManager.ts | 164 ++++++++++-------- 2 files changed, 195 insertions(+), 68 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index f2f992d8f4ee9..e6652c5963905 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -611,6 +611,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( resumeCount: current.resumeCount + 1, })).pipe(Effect.as(threadInput.providerThread)), startTurn: () => options.startTurn ?? Effect.void, + resumeTurn: () => options.startTurn ?? Effect.void, + compactThread: () => options.startTurn ?? Effect.void, steerTurn: () => Effect.void, interruptTurn: () => Ref.update(state, (current) => ({ @@ -2137,6 +2139,103 @@ it.effect.each([ }), ); +const idleReleaseAroundRun = (start: "compactThread" | "resumeTurn") => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`thread-${start}-outlasts-idle-timeout`); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const subscriber = yield* runtime.subscribeEvents!; + const terminal = yield* subscriber.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + Effect.forkScoped, + ); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + const run = { + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + modelSelection, + runtimePolicy, + }; + const messageId = yield* idAllocator.allocate.message({ threadId, ordinal: 1 }); + yield* start === "compactThread" + ? runtime.compactThread!({ + ...run, + message: { + createdBy: "user", + creationSource: "web", + messageId, + text: "/compact", + attachments: [], + }, + }) + : runtime.resumeTurn!({ ...run, messageId }); + + // A running compaction or continuation can go minutes without a provider event. + yield* TestClock.adjust("2 seconds"); + assert.isTrue(yield* manager.isLive(providerSessionId)); + + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + yield* Queue.offer(queue!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${start}`, + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + // The event pump marks the run idle before it publishes the event. + yield* Fiber.join(terminal); + yield* TestClock.adjust("2 seconds"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 }))); + }); + +it.effect.each([ + { run: "compaction", start: "compactThread" }, + { run: "manual continuation", start: "resumeTurn" }, +] as const)( + "ProviderSessionManagerV2 keeps a session through a $run that outlasts the idle timeout", + ({ start }) => idleReleaseAroundRun(start), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dc1ae318a4c2a..291ac02272a26 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2532,6 +2532,80 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); + // A start, continuation or compaction keeps the session busy until its turn.terminal. + const busyTurn = ( + input: Pick< + ProviderAdapter.ProviderAdapterV2TurnInput, + "threadId" | "providerThread" | "runOrdinal" | "runId" + >, + run: () => Effect.Effect, + ) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. + Effect.andThen( + holdThreadLoaded({ + providerSessionId, + threadId: input.threadId, + providerThread: input.providerThread, + }), + ), + Effect.andThen( + Effect.acquireUseRelease( + markBusy( + providerSessionId, + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + // A release between attach and markBusy leaves nothing to mark: fail the + // start instead of running it on a runtime being torn down. + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: "The provider session was released while the turn started.", + }), + ), + ), + ), + run, + (_, exit) => + Exit.isFailure(exit) + ? observeActivity( + providerSessionId, + markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), + ).pipe( + // A failed start can leave its native thread gone (Claude rejecting a + // resume), so the next start must ask the adapter to resume it again. + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), + ) + : Effect.void, + ), + ), + ); return { ...runtime, // Pi replaces its session snapshot as metadata changes. @@ -2663,78 +2737,32 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), + busyTurn(input, () => + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), + turnMetrics("send", input.modelSelection.model), ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), + ), + ...(runtime.resumeTurn === undefined + ? {} + : { + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + busyTurn(input, () => + runtime.resumeTurn!(input).pipe( + turnMetrics("resume", input.modelSelection.model), ), ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), + }), + ...(runtime.compactThread === undefined + ? {} + : { + compactThread: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => + busyTurn(input, () => + runtime.compactThread!(input).pipe( + turnMetrics("compact", input.modelSelection.model), ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), - ), - ), + ), + }), steerTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))), From f0d901502a3b3cb961f9bfcb89a1d8f5233b78d9 Mon Sep 17 00:00:00 2001 From: 4dwaffle Date: Mon, 23 Nov 2026 16:07:09 +0100 Subject: [PATCH 122/288] fix(server): Azure DevOps PRs read by number get their full URL (#41472) Co-authored-by: Vaclav Berny Co-authored-by: Julius Marminge --- .../toolkits/pullRequests/handlers.test.ts | 34 +++++++++++++++++++ .../src/pullRequest/pullRequestTarget.ts | 19 +++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index f0b9db206bbb6..95f816f151b9d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -944,6 +944,40 @@ describe("source control tools", () => { }), ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + project: makeProject({ + canonicalKey: "dev.azure.com/contoso/project/_git/repo", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://contoso@dev.azure.com/contoso/project/_git/repo", + }, + provider: SourceControlProviderKind.make("azure-devops"), + displayName: "contoso/project/_git/repo", + owner: "contoso", + name: "repo", + }), + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { number: 123 }); + expect(result).toMatchObject({ + host: "dev.azure.com", + repository: "contoso/project/_git/repo", + number: 123, + url: "https://dev.azure.com/contoso/project/_git/repo/pullrequest/123", + }); + expect(asked).toMatchObject([ + { host: "dev.azure.com", repository: "contoso/project/_git/repo", number: 123 }, + ]); + }), + ); + it.effect("pages a long conversation and the PR list through the cursors they return", () => Effect.gen(function* () { const comment = (body: string) => diff --git a/apps/server/src/pullRequest/pullRequestTarget.ts b/apps/server/src/pullRequest/pullRequestTarget.ts index 52d9c3605b069..45312f8304634 100644 --- a/apps/server/src/pullRequest/pullRequestTarget.ts +++ b/apps/server/src/pullRequest/pullRequestTarget.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; +import { pullRequestSyncKey } from "./pullRequestSyncKey.ts"; export interface PullRequestTarget { readonly url?: string | undefined; @@ -102,12 +103,26 @@ export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(func if (input.repository === undefined || input.number === undefined) { return yield* new PullRequestTargetIncompleteError({}); } + // Azure DevOps tools name the project's repository by its bare name, which no URL can be built + // from, so it is read as the project's full repository path. + const own = + project?.repositoryIdentity == null || input.repository.includes("/") + ? null + : pullRequestSyncKey( + { + projectId: project.id, + host: input.host, + repository: input.repository, + number: input.number, + }, + project.repositoryIdentity, + ); const projectHost = projectHostAndProvider(project); - const host = (input.host ?? projectHost.host)?.toLowerCase(); + const host = (own?.host ?? input.host ?? projectHost.host)?.toLowerCase(); if (host === undefined) { return yield* new PullRequestHostRequiredError({}); } - const repository = input.repository.toLowerCase(); + const repository = (own?.repository ?? input.repository).toLowerCase(); // Without a URL, a public forge host says what shape its change request URLs take; // any other host is taken to run the project's own forge. const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; From 0359b044e99e9cf5bddea19c889e1dcbb8a161cd Mon Sep 17 00:00:00 2001 From: 3xcalibur <79220116+3xcalibur-tech@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:13:46 +0400 Subject: [PATCH 123/288] fix(desktop): agent screenshots and clicks work while T3 Code is hidden, minimized or covered (#40263) Co-authored-by: Julius Marminge --- .../src/preview/DesktopBrowserHost.test.ts | 97 +++++++++++++++++++ .../desktop/src/preview/DesktopBrowserHost.ts | 96 ++++++++++++++++-- 2 files changed, 187 insertions(+), 6 deletions(-) diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 8e96129293fc8..b086f67829181 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -50,6 +50,10 @@ const makeDebuggee = ( readonly deferFocus?: boolean; /** The guest is still loading its first page. */ readonly loading?: boolean; + /** Like a guest of a hidden window: it answers a capture only once Electron captures it. */ + readonly drawsOnlyWhenCaptured?: () => boolean; + /** Electron's capture of this guest never settles. */ + readonly capturesStall?: () => boolean; readonly refuse?: (method: string, sessionId: string | undefined) => boolean; } = {}, ) => { @@ -90,7 +94,14 @@ const makeDebuggee = ( }), }); let destroyed = false; + let nativeCaptures = 0; const webContents = Object.assign(new NodeEvents.EventEmitter(), { + capturePage: () => { + nativeCaptures += 1; + if (options.capturesStall?.()) return new Promise(() => {}); + if (options.drawsOnlyWhenCaptured?.()) pending.splice(0).forEach((resolve) => resolve()); + return Promise.resolve({}); + }, getURL: () => "http://localhost/", getTitle: () => "Page", getUserAgent: () => "Electron", @@ -117,6 +128,7 @@ const makeDebuggee = ( /** Refuses the pending command the debugger received with this id. */ refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, + nativeCaptures: () => nativeCaptures, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), releaseFirst: () => pending.shift()?.(), @@ -364,6 +376,91 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("prods a guest its window stopped drawing until what waits on it settles", () => + Effect.gen(function* () { + let drawsWhenCaptured = true; + let capturesStall = false; + const host = yield* makeDrawnHost; + const debuggee = makeDebuggee({ + drawsOnlyWhenCaptured: () => drawsWhenCaptured, + capturesStall: () => capturesStall, + }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const painting = yield* watchPainting(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("250 millis"); + expect(yield* Queue.take(replies)).toBe(1); + expect(debuggee.nativeCaptures()).toBe(1); + + // A wait that settles within a frame is never prodded. + yield* command(host, 3, "Page.captureScreenshot"); + yield* settle; + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(3); + yield* TestClock.adjust("1 second"); + expect(debuggee.nativeCaptures()).toBe(1); + + // A long wait is prodded less often as it goes on, once per tick though it holds focus too. + drawsWhenCaptured = false; + yield* command(host, 4, "Page.captureScreenshot"); + yield* settle; + for (const [wait, prods] of [ + ["250 millis", 2], + ["500 millis", 3], + ["1 second", 4], + ["2 seconds", 5], + ["2 seconds", 6], + ] as const) { + yield* TestClock.adjust(wait); + expect(debuggee.nativeCaptures()).toBe(prods); + } + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(4); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(6); + + // A command that outlasts its first prod is painted like a capture, which also unthrottles it. + // A wait the agent's turn gave up on is no longer prodded. + yield* command(host, 5, "Runtime.evaluate"); + yield* settle; + painting.length = 0; + yield* TestClock.adjust("250 millis"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true]); + yield* host.handleCommandLine( + encodeJson({ type: "turn", threadId: key.threadId, active: false }), + ); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true, false]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(5); + + // Captures Electron never settles pile up no further than two. + capturesStall = true; + yield* command(host, 6, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(6); + // Even across a reattach of the same guest, as when DevTools closes. + host.detach(key); + host.attach(key, debuggee.tab); + const reattached = yield* watchReplies(host); + yield* command(host, 7, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(reattached)).toBe(7); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index ce5d7074a786c..b3812e90d54bf 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -32,6 +32,12 @@ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; /** How long a screenshot waits for the client to draw its guest at full detail. */ const CAPTURE_DRAW_WAIT = "1 second"; +/** Most waits settle within a frame or two of this, so a quick one is never prodded. */ +const PAINT_NUDGE_FIRST_MS = 250; +/** A long wait, such as a page awaiting a timer, is prodded less often as it goes on. */ +const PAINT_NUDGE_LONGEST_MS = 2_000; +/** Electron's capture has no deadline and a cold guest can stall one, so a second may follow. */ +const PAINT_NUDGE_IN_FLIGHT = 2; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -73,6 +79,11 @@ interface AttachedTab { readonly focusPending: Map; /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */ readonly capturing: Set; + /** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */ + readonly frameWaits: Set<() => boolean>; + nudging: Fiber.Fiber | null; + /** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */ + frameStalled: boolean; /** Whether the client keeps the guest painting, as published on `painting`. */ painting: boolean; /** @@ -243,7 +254,7 @@ export const make = Effect.gen(function* () { }; /** - * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame + * Electron composites no offscreen guest, so a screenshot, screencast or stalled command waits for a frame * that never comes. The client paints the guest behind the app while one is pending; the * capture then finishes on its own, and the guest goes back offscreen once none is. */ @@ -252,12 +263,78 @@ export const make = Effect.gen(function* () { tabs.get(keyOf(tab.key)) === tab && (tab.screencasts.size > 0 || tab.capturing.size > 0 || + tab.frameStalled || tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; tab.painting = active; runFork(PubSub.publish(painting, { key: tab.key, active })); }; + /** By guest rather than attachment, since reopening DevTools reattaches the same guest. */ + const nativeCaptures = new WeakMap(); + const startNudging = (tab: AttachedTab) => { + tab.nudging ??= runFork(nudgePaint(tab, PAINT_NUDGE_FIRST_MS)); + }; + + const endNudging = (tab: AttachedTab) => { + tab.nudging = null; + if (!tab.frameStalled) return; + tab.frameStalled = false; + syncPainting(tab); + }; + + /** + * A hidden, minimized or covered window (which Electron reports as visible) stops drawing its + * guest, so a wait on its next frame never ends. Electron's own capture still draws one. + */ + const nudgePaint = (tab: AttachedTab, delayMs: number): Effect.Effect => + Effect.sleep(delayMs).pipe( + Effect.andThen( + Effect.suspend(() => { + const { webContents } = tab.debuggee; + for (const waits of tab.frameWaits) if (!waits()) tab.frameWaits.delete(waits); + if ( + tab.frameWaits.size === 0 || + tabs.get(keyOf(tab.key)) !== tab || + webContents.isDestroyed() + ) { + endNudging(tab); + return Effect.void; + } + // On Windows a hidden window's throttled guest draws nothing, and capturePage cannot wake it. + if (!tab.frameStalled) { + tab.frameStalled = true; + syncPainting(tab); + } + const inFlight = nativeCaptures.get(webContents) ?? 0; + if (inFlight < PAINT_NUDGE_IN_FLIGHT) { + nativeCaptures.set(webContents, inFlight + 1); + const settled = () => { + nativeCaptures.set(webContents, (nativeCaptures.get(webContents) ?? 1) - 1); + }; + webContents.capturePage().then(settled, settled); + } + return nudgePaint(tab, Math.min(delayMs * 2, PAINT_NUDGE_LONGEST_MS)); + }), + ), + ); + + /** Prods the guest while `work` is pending and `waits` holds; one loop serves all of a tab's waits. */ + const nudgedUntilSettled = ( + tab: AttachedTab, + waits: () => boolean, + work: () => Promise, + ) => { + tab.frameWaits.add(waits); + startNudging(tab); + return work().finally(() => { + tab.frameWaits.delete(waits); + if (tab.frameWaits.size > 0 || tab.nudging === null) return; + runFork(Fiber.interrupt(tab.nudging)); + endNudging(tab); + }); + }; + /** A command may wait on the page's next frame, so the guest stays focused until it settles. */ const holdFocus = (tab: AttachedTab, owner: string | undefined, work: () => Promise) => { const pending = {}; @@ -265,7 +342,8 @@ export const make = Effect.gen(function* () { tab.focusUses += 1; setFocusEmulation(tab, true); releaseFocusWhenIdle(tab); - return work().finally(() => { + // Dropping the hold, at a turn's end or a new document, stops the prods too. + return nudgedUntilSettled(tab, () => tab.focusPending.has(pending), work).finally(() => { if (!tab.focusPending.delete(pending)) return; tab.focusUses += 1; releaseFocusWhenIdle(tab); @@ -296,11 +374,14 @@ export const make = Effect.gen(function* () { const sent = {}; tab.capturing.add(sent); syncPainting(tab); + const sendNudged = () => nudgedUntilSettled(tab, () => tab.capturing.has(sent), send); // Sent at once when already drawn, so it keeps its place among the commands after it. - return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { - tab.capturing.delete(sent); - syncPainting(tab); - }); + return (drawnTabs.has(keyOf(tab.key)) ? sendNudged() : whenDrawn(tab).then(sendNudged)).finally( + () => { + tab.capturing.delete(sent); + syncPainting(tab); + }, + ); }; /** @@ -537,6 +618,9 @@ export const make = Effect.gen(function* () { focusUses: 0, focusPending: new Map(), capturing: new Set(), + frameWaits: new Set(), + nudging: null, + frameStalled: false, painting: false, agentUsed: false, focusReleasing: false, From 555512fbe16db3b2249be3cd7fee9d23f7dc7ef5 Mon Sep 17 00:00:00 2001 From: Michael Nemni Date: Mon, 23 Nov 2026 17:15:01 +0200 Subject: [PATCH 124/288] fix(server): a PR whose merge is refused for conflicts shows as conflicting (#41500) Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestService.test.ts | 41 +++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 8 ++++ 2 files changed, 49 insertions(+) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 26190320af16f..a2eb9c6486272 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -3090,6 +3090,47 @@ it.effect("close and reopen notify subscribed readers after invalidating their c }), ); +it.effect("a refused merge notifies readers so they re-read the conflicting state", () => + Effect.gen(function* () { + let mergeable = true; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ + ...changeRequest(1, "2026-09-16T00:00:00.000Z"), + mergeability: mergeable ? "mergeable" : "conflicting", + }), + runAction: () => + Effect.suspend(() => { + mergeable = false; + return Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "runAction", + reason: "failed", + detail: "Pull Request has merge conflicts", + }), + ); + }), + }), + ], + }); + + assert.strictEqual((yield* service.summary(reference)).mergeability, "mergeable"); + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.take(1), + Stream.mapEffect(() => service.summary(reference)), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.flip(service.runAction({ ...reference, action: "merge" })); + assert.strictEqual(Option.getOrThrow(yield* Fiber.join(refreshed)).mergeability, "conflicting"); + }), +); + it.effect("reads a host's repositories in one search, and files the rows back under each", () => Effect.gen(function* () { const asked: Array> = []; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index d0884ac6e7178..690b7c4153f98 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -3989,8 +3989,16 @@ export const make = Effect.gen(function* () { )(function* (input) { const ref = yield* canonicalRef(input); yield* readCache.invalidate(refScope(ref)); + // A refusal (e.g. a merge conflict) means readers hold stale state, so refresh them too. const { repository, summary } = yield* runAction(input).pipe( Effect.ensuring(readCache.invalidate(refScope(ref))), + Effect.tapError(() => + Effect.suspend(() => { + bumpRefEpoch(ref); + listingsEpoch = ++epochCounter; + return SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); + }), + ), ); bumpRefEpoch({ ...ref, repository }); listingsEpoch = ++epochCounter; From 593885bd5dfdc187513e41a54f39d55f8903e5e1 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 09:18:51 -0600 Subject: [PATCH 125/288] fix(cli): a symlinked spelling of the T3 home is the same home for service uninstall (#41464) Co-authored-by: Julius Marminge --- apps/server/src/cli/service.test.ts | 1 + apps/server/src/cli/service.ts | 13 ++----- apps/server/src/cli/uninstall.test.ts | 25 ++++++++++--- apps/server/src/cli/uninstall.ts | 10 ++--- apps/server/src/cli/update.ts | 4 +- apps/server/src/cloud/bootService.test.ts | 22 +++++++++++ apps/server/src/cloud/bootService.ts | 32 ++++++++-------- apps/server/src/serviceLauncher.test.ts | 45 +++++++++++++++++++++++ apps/server/src/serviceLauncher.ts | 3 +- 9 files changed, 117 insertions(+), 38 deletions(-) diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index ada548ba2bf39..70907ab446a09 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -288,6 +288,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands const { service, uninstalls } = makeTestService({ ...status, installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir, + ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}), }); vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889aa..4c55d1fa329da 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -325,19 +325,14 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags). flags, Effect.gen(function* () { const service = yield* BootService.BootService; - const path = yield* Path.Path; - const { baseDir } = yield* ServerConfig.ServerConfig; // An unreadable unit stays removable; only a unit known to serve another home is kept. - const installedBaseDir = yield* service.status.pipe( - Effect.map((status) => status.installedBaseDir), + const otherBaseDir = yield* service.status.pipe( + Effect.map((status) => status.otherBaseDir), Effect.orElseSucceed(() => undefined), ); - if ( - installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(baseDir) - ) { + if (otherBaseDir !== undefined) { yield* Console.log( - `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`, + `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`, ); return; } diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index 7bb1046199c4e..19093032fc3d3 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -89,23 +89,38 @@ it.live("reports failure when the Windows cleanup shell cannot start", () => ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { - it.effect("names another home's service it leaves installed", () => + it.effect.each([ + { + label: "names another home's service it leaves installed", + otherFromRead: 1, + removed: [], + output: "--base-dir '/home/me/.t3'", + }, + { + label: "leaves a service that serves another home by the time it is removed", + otherFromRead: 2, + removed: [], + output: "Left the background service: it now serves another T3 home.", + }, + ])("$label", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" }); const uninstalls: Array = []; + let reads = 0; vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( BootService.BootService, BootService.BootService.of({ - status: Effect.succeed({ + status: Effect.sync(() => ({ supported: true, installed: true, current: true, installedBaseDir: "/home/me/.t3", + ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}), unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", - }), + })), withStopped: (operation) => operation, restart: Effect.die("unexpected restart"), install: () => Effect.die("unexpected install"), @@ -133,8 +148,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall com ), ), ); - assert.deepStrictEqual(uninstalls, []); - assert.include(output, "--base-dir '/home/me/.t3'"); + assert.deepStrictEqual(uninstalls, input.removed); + assert.include(output, input.output); }), ); }); diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 5624e6c2a894c..ae884caa63fe7 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -155,9 +155,7 @@ const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: { const status = yield* service.status; const installedBaseDir = status.supported && status.installed ? status.installedBaseDir : undefined; - const servesThisHome = - installedBaseDir !== undefined && - path.resolve(installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined; const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); const runtimeDir = path.dirname(versionsDir); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; @@ -258,12 +256,14 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { } } - if (plan.service) { + // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile. + if (plan.service && (yield* service.status).otherBaseDir !== undefined) { + yield* Console.log("Left the background service: it now serves another T3 home."); + } else if (plan.service) { yield* service.uninstall; yield* Console.log("Removed the background service."); } for (const launcher of plan.launchers) { - // The prompt can wait a long time; never delete a file that replaced the launcher meanwhile. if (!(yield* ownsLauncher(launcher, plan.versionsDir))) { yield* Console.log(`Left ${launcher}: it no longer runs this t3.`); continue; diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b66..dc798afdaa4da 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -423,9 +423,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { const status = yield* service.status; // Service names are per user, so another home's unit belongs to a different install. - const servesThisHome = - status.installedBaseDir !== undefined && - path.resolve(status.installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined; const serviceInstalled = status.supported && status.installed && servesThisHome; const foreground = yield* findForegroundServer({ serverRuntimeStatePath: input.serverRuntimeStatePath, diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 8e69e7cdcd7af..c327464ddfa24 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -1308,6 +1308,28 @@ process.disconnect(); }), ); + it.effect("treats a symlinked T3 home path as the same home", () => + Effect.gen(function* () { + const { service, fs, baseDir, commands, makeService } = yield* makeHarness(); + yield* service.install(); + const path = yield* Path.Path; + const linkDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-symlink-home-" }); + const aliasDir = path.join(linkDir, "a$$b"); + yield* fs.symlink(baseDir, aliasDir); + + const alias = yield* makeService(undefined, "1.2.3", aliasDir); + expect(yield* alias.status).toMatchObject({ current: true }); + expect((yield* alias.status).otherBaseDir).toBeUndefined(); + expect(yield* alias.restart).toBe("restarted"); + commands.length = 0; + yield* alias.withStopped(Effect.void); + expect(commands).toContain("systemctl --user stop t3code.service"); + expect((yield* alias.install()).baseDir).toBe(aliasDir); + expect(yield* service.status).toMatchObject({ current: true }); + expect((yield* service.status).otherBaseDir).toBeUndefined(); + }), + ); + it.effect("hands the whole install to systemd without changing the running service", () => Effect.gen(function* () { const { fs, commands, invocations, control, makeService } = yield* makeHarness(); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 3a930f02dabc1..90d01b10526f3 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1024,12 +1024,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); + const canonicalPath = (dir: string) => + fs.realPath(dir).pipe(Effect.orElseSucceed(() => path.resolve(dir))); + const isThisHome = (dir: string) => + Effect.zipWith(canonicalPath(dir), canonicalPath(input.baseDir), (a, b) => a === b); const otherBaseDirOf = (unit: string) => { const installedBaseDir = bootServiceBaseDirOf(unit); - return installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ? installedBaseDir - : undefined; + return installedBaseDir === undefined + ? Effect.undefined + : Effect.map(isThisHome(installedBaseDir), (same) => (same ? undefined : installedBaseDir)); }; const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( @@ -1261,7 +1264,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const refuseOtherBaseDir = Effect.gen(function* () { const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) - ? otherBaseDirOf(existingUnit.value) + ? yield* otherBaseDirOf(existingUnit.value) : undefined; if (installedBaseDir !== undefined) { return yield* new BootServiceOtherBaseDirError({ @@ -1491,10 +1494,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return "skipped" as const; } // Writes no state, and the launcher lets an update transition in flight @@ -1524,10 +1524,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return yield* operation; } // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid. @@ -1607,7 +1604,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? serviceStateActiveVersion(stateText.value) : undefined; const installedBaseDir = bootServiceBaseDirOf(unit); - const otherBaseDir = otherBaseDirOf(unit); + const otherBaseDir = yield* otherBaseDirOf(unit); + // Another spelling of this home is current; repairing it would flip the unit between spellings. + const thisHomeUnit = + installedBaseDir !== undefined && otherBaseDir === undefined + ? unit.replaceAll(installedBaseDir, () => input.baseDir) + : unit; const normalizeUnit = (contents: string) => manager.kind === "launchd" ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") @@ -1629,7 +1631,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { current: problems.length === 0 && !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && - normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && + normalizeUnit(thisHomeUnit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 0f51100fb368b..86df5b092ac89 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -896,6 +896,51 @@ process.exit(0); }), ); + it.effect("repoints a unit that names this T3 home through a symlink", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-alias-" }); + const alias = path.join(root, "alias"); + yield* fs.symlink(root, alias); + const statePath = path.join(root, "runtime", "service-state.json"); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "setInterval(() => {}, 1_000);\n", + ); + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + const unit = yield* fakeServiceUnit(fs, path, alias, "1.0.0"); + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + serviceUnit: unit, + }, + ); + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + assert.equal( + yield* fs.readFileString(unit.path), + renderBootServiceUnit(unitPlan(alias, "1.1.0")), + ); + }), + ); + it.effect("waits without exiting and restarts once the other owner releases the T3 home", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 3c6bdf6913187..44220f2c4b148 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1416,9 +1416,10 @@ export class Launcher { } const contents = decodeServiceUnit(await NodeFSP.readFile(unit.path)); const installedBaseDir = serviceUnitBaseDirOf(contents); + const real = (dir: string) => NodeFSP.realpath(dir).catch(() => NodePath.resolve(dir)); if ( installedBaseDir === undefined || - NodePath.resolve(installedBaseDir) !== NodePath.resolve(this.#baseDir) + (await real(installedBaseDir)) !== (await real(this.#baseDir)) ) { return; } From 37a70fa0419db077d576fa44e2e381bacb4b1305 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 16:33:26 +0100 Subject: [PATCH 126/288] fix(server): preserve number formats when XLSX styles are relocated (#41486) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 34 ++++++++++++------- .../src/provider/userInputAttachments.test.ts | 4 +-- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 47e9b2a57f107..7dfd82f02f187 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -627,12 +627,19 @@ async function* document(path: string, extension: string): AsyncGenerator name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase()); + const folded = new Map(); + for (const name of files.keys()) + if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name); + const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name)); + const has = (name: string) => files.has(part(name)); const notes: string[] = []; const skip = (name: string) => notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`); const read = (name: string): XmlNode => { try { - const data = files.get(name); + const data = files.get(part(name)); if (!data) throw new Error("Missing document part"); return xml(data, extension); } catch (error) { @@ -649,14 +656,14 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External", )?.attrs.Target : undefined; const main = target && NodePath.posix.normalize(target).replace(/^\//, ""); - yield* paragraphs(read(main && files.has(main) ? main : "word/document.xml")); + yield* paragraphs(read(main && has(main) ? main : "word/document.xml")); } else if ([".odt", ".ods", ".odp"].includes(extension)) { const content = read("content.xml"); if (extension === ".odt") yield* paragraphs(content); @@ -683,12 +690,19 @@ async function* document(path: string, extension: string): AsyncGenerator { + const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target; + return target ? NodePath.posix.resolve("/xl", target).slice(1) : `xl/${part}.xml`; + }; const dateSystem = ["1", "true"].includes( all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "", ) ? "1904" : "1900"; - const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined; + const stylesPath = workbookPartPath("styles"); + const styles = has(stylesPath) ? read(stylesPath) : undefined; const customFormats = new Map( styles ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode]) @@ -696,14 +710,8 @@ async function* document(path: string, extension: string): AsyncGenerator - rel.Type?.endsWith("/sharedStrings"), - )?.Target; - const sharedPath = sharedTarget - ? NodePath.posix.resolve("/xl", sharedTarget).slice(1) - : "xl/sharedStrings.xml"; - const strings = files.has(sharedPath) ? [...all(read(sharedPath), "si")] : []; + const sharedPath = workbookPartPath("sharedStrings"); + const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : []; const populatedStrings = strings.map(hasCellText); for (const sheet of all(workbook, "sheet")) { yield `\n## Sheet: ${sheet.attrs.name}\n`; @@ -797,7 +805,7 @@ async function* document(path: string, extension: string): AsyncGenerator { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', + '', "catalog/items.xml": "Lantern", - "xl/styles.xml": + "formatting/cells.xml": '', "xl/worksheets/second.xml": '037', From 79979166731a3ed40dc467ced2dcb782233c22f2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 09:43:34 -0600 Subject: [PATCH 127/288] fix(web): Markdown previews load relative images in timestamped and root folders (#41505) Co-authored-by: Julius Marminge --- .../components/files/FileMarkdownPreview.tsx | 2 +- .../files/FilePreviewPanel.browser.test.tsx | 36 ++++++++++++++++--- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx index a4b4957201792..f3cc04bf6bf20 100644 --- a/apps/web/src/components/files/FileMarkdownPreview.tsx +++ b/apps/web/src/components/files/FileMarkdownPreview.tsx @@ -21,7 +21,7 @@ export function FileMarkdownPreview(props: { ); const imageBaseDir = lastSeparator >= 0 - ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator), props.cwd) + ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator + 1), props.cwd) : props.cwd; return ( diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 07e05010baab3..4a6e5da91b871 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -18,6 +18,7 @@ const state = vi.hoisted(() => ({ optimistic: null as ProjectReadFileResult | null, writeFile: vi.fn(), assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState, + assetResources: [] as Array, mintUrl: vi.fn<() => Promise>(), browserAssetMints: 0, openedBrowserUrls: [] as string[], @@ -65,7 +66,13 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ vi.mock(import("~/assets/assetUrls"), async (original) => ({ ...(await original()), useAssetUrlRefresh: () => state.mintUrl, - useAssetUrlState: () => state.assetUrl, + useAssetUrlState: ( + _environmentId: unknown, + resource: import("@t3tools/contracts").AssetResource | null, + ) => { + if (resource) state.assetResources.push(resource); + return state.assetUrl; + }, })); vi.mock(import("~/browser/previewRuntime"), async (original) => ({ ...(await original()), @@ -173,6 +180,7 @@ function setup() { state.file = null; state.optimistic = null; state.assetUrl = { _tag: "Loading" }; + state.assetResources = []; state.openedBrowserUrls = []; let mints = 0; state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`); @@ -188,14 +196,18 @@ function setup() { }; } -function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") { +function markdownPreview( + truncated: boolean, + contents = "- [ ] Keep the rest of this file\n", + relativePath = "tasks.md", +) { state.file = { - relativePath: "tasks.md", + relativePath, contents, byteLength: truncated ? 1_200_000 : contents.length, truncated, }; - return filePreview("tasks.md"); + return filePreview(relativePath); } function filePreview(relativePath: string, workspaceMutationId: string | null = null) { @@ -717,3 +729,19 @@ describe("rendered Markdown select all", () => { await expectFileOnlySelection(); }); }); + +describe("rendered Markdown relative images", () => { + it.each([ + ["2026-11-23T14:05/README.md", "/workspace/2026-11-23T14:05/diagram.png"], + ["/README.md", "/diagram.png"], + ])("resolves relative images in %s against its folder", async (relativePath, expectedPath) => { + using _settings = setup(); + await using _screen = await render( + markdownPreview(false, "![diagram](diagram.png)\n", relativePath), + ); + await vi.waitFor(() => expect(state.assetResources).not.toHaveLength(0)); + expect(state.assetResources).toContainEqual( + expect.objectContaining({ _tag: "media-file", path: expectedPath }), + ); + }); +}); From a2d64160430ab67486717b83d2cbe2f8161430d9 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 17:47:59 +0200 Subject: [PATCH 128/288] fix(server): RTF text in an ANSI font reads as code page 1252 under any document code page (#41508) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 31 +++++++++++++------ .../src/provider/userInputAttachments.test.ts | 20 ++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 7dfd82f02f187..cf25d9c2f40d2 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -463,6 +463,7 @@ function* notebook(source: string): Generator { // Per-byte decoding only supports the single-byte \fcharset values. const FONT_CODE_PAGES = new Map([ + [0, "windows-1252"], [77, "macintosh"], [161, "windows-1253"], [162, "windows-1254"], @@ -475,6 +476,18 @@ const FONT_CODE_PAGES = new Map([ [238, "windows-1250"], ]); +// Per-byte decoding only supports single-byte code pages. +const singleByteCodePage = (value: number) => + value === 0 + ? "windows-1252" + : value === 866 + ? "ibm866" + : value === 10000 + ? "macintosh" + : value === 874 || (value >= 1250 && value <= 1258) + ? `windows-${value}` + : undefined; + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); let state = { @@ -484,10 +497,12 @@ function* rtf(source: string): Generator { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; const stack: Array = []; - // A font's \fcharset, not the document code page, encodes the bytes written in that font. + // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in + // that font. A \cpg inside \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; @@ -561,6 +576,7 @@ function* rtf(source: string): Generator { ) state.skip = true; if (control === "fonttbl") state.fontTable = true; + else if (control === "fontfile") state.fontFile = true; else if (control === "deff") state.font = defaultFont = value; else if (control === "f") { state.font = value; @@ -568,6 +584,9 @@ function* rtf(source: string): Generator { } else if (control === "fcharset" && state.fontTable) { const codePage = FONT_CODE_PAGES.get(value); if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } else if (control === "cpg" && state.fontTable && !state.fontFile) { + const codePage = singleByteCodePage(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; else if (control === "v") state.hiddenText = value !== 0; @@ -579,15 +598,7 @@ function* rtf(source: string): Generator { if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { - // Per-byte decoding only supports single-byte code pages. - const label = - value === 0 - ? "windows-1252" - : value === 866 - ? "ibm866" - : value === 874 || (value >= 1250 && value <= 1258) - ? `windows-${value}` - : undefined; + const label = singleByteCodePage(value); if (!label) throw new Error("Unsupported RTF code page"); state.decoder = new TextDecoder(label, { fatal: true }); } else if (control === "uc") { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index ad0430804c63d..be2aab625142d 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -366,6 +366,26 @@ describe("question answer paths", () => { \f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, "ملاحظة: café, Ça", ], + [ + "ANSI font under another code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "€5 café", + ], + [ + "font code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "Привет", + ], + [ + "ANSI font in a Macintosh document", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "pridržana", + ], + [ + "Macintosh font code page", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0\cpg10000 Geneva;}\f0 Caf\'8e}`, + "Café", + ], [ "font character set outside the font table", String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, From 14c697c4f19dbd23d21c2e91c555859f0d482e39 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 17:51:04 +0200 Subject: [PATCH 129/288] fix(web): RTF previews read text in an ANSI font as code page 1252 under any document code page (#41514) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 12 ++++++ .../files/extendedDocumentPreview.ts | 43 ++++++++++++------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index d7242cc0ba587..8b72060d5d050 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -299,6 +299,18 @@ Third}`; for (const [rtf, expected] of [ [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "

Café

"], [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "

Привет

"], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "

€5 café

", + ], + [ + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "

pridržana

", + ], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "

Привет

", + ], ] as const) { const decoded = openRtf(bytes(rtf)); if (decoded.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 76c55283854af..f14b35fbbc80e 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,21 @@ const RTF_CHARACTERS = new Map([ ["rtlmark", "\u200f"], ]); +const rtfCodePageLabel = (codePage: number) => + ( + { + 0: "windows-1252", + 866: "ibm866", + 65001: "utf-8", + 932: "shift_jis", + 936: "gbk", + 949: "euc-kr", + 950: "big5", + 874: "windows-874", + 10000: "macintosh", + } as Record + )[codePage] ?? `windows-${codePage}`; + export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" }); // Keep byte offsets intact for binary destinations and multibyte code pages. @@ -556,8 +571,11 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; + // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside + // \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const stack: (typeof state)[] = []; @@ -668,7 +686,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "fcharset" && state.fontTable) { const label = ( { - 0: state.decoder.encoding, + 0: "windows-1252", 1: state.decoder.encoding, 77: "macintosh", 128: "shift_jis", @@ -688,6 +706,13 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { } as Record )[arg]; if (label) fonts.set(state.font, new TextDecoder(label)); + } else if (word === "fontfile") state.fontFile = true; + else if (word === "cpg" && state.fontTable && !state.fontFile) { + try { + fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg))); + } catch { + // An unknown font code page leaves the font on its \fcharset. + } } else if ( [ "colortbl", @@ -712,22 +737,8 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { state.skip = true; else if (word === "mac") state.decoder = new TextDecoder("macintosh"); else if (word === "ansicpg") { - const label = - ( - { - 0: "windows-1252", - 866: "ibm866", - 65001: "utf-8", - 932: "shift_jis", - 936: "gbk", - 949: "euc-kr", - 950: "big5", - 874: "windows-874", - 10000: "macintosh", - } as Record - )[arg] ?? `windows-${arg}`; try { - state.decoder = new TextDecoder(label); + state.decoder = new TextDecoder(rtfCodePageLabel(arg)); } catch { throw new PreviewError({ code: "rtf-code-page" }); } From 77c230e45650a5f5f3dcf45f538683eb2383e196 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:01:16 -0600 Subject: [PATCH 130/288] fix(web): notebook previews show errors saved without a traceback (#41511) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 20 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 16 +++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 8b72060d5d050..b32a64fd18373 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -438,6 +438,23 @@ Third}`; "final entry", ], }, + { + output_type: "error", + ename: "ZeroDivisionError", + evalue: "division by zero", + traceback: [], + }, + { + output_type: "error", + evalue: "\u001b[31mbad input\u001b[0m", + traceback: [], + }, + { + output_type: "error", + ename: "RuntimeError", + evalue: "kernel reset", + traceback: ["\u001b[31m\u001b[0m", " \n"], + }, ], }, ], @@ -458,6 +475,9 @@ Third}`; kind: "text", text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry", }, + { kind: "text", text: "ZeroDivisionError: division by zero" }, + { kind: "text", text: "bad input" }, + { kind: "text", text: "RuntimeError: kernel reset" }, ]); expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow( expect.objectContaining({ code: "notebook-unsupported" }), diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index f14b35fbbc80e..d04f1c9882ee9 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -501,12 +501,16 @@ export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult { } const html = notebookText(data["text/html"]); if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html }; - return { - kind: "text" as const, - text: terminalOutputPlainText( - notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), - ), - }; + const text = terminalOutputPlainText( + notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), + ); + if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text }; + const summary = [output.ename, output.evalue] + .filter((part) => typeof part === "string") + .map((part) => terminalOutputPlainText(notebookText(part))) + .filter((part) => part.trim().length > 0) + .join(": "); + return { kind: "text" as const, text: summary }; }) .filter((output) => output.text.trim().length > 0), }; From e6ba483403910c3b7597d4c2bb1ff117573cb8a8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 08:06:11 -0800 Subject: [PATCH 131/288] fix(server): a declined steer of a delegated completion still wakes the parent (#41521) --- .../src/orchestration-v2/Orchestrator.ts | 3 + .../SteeringCompletion.integration.test.ts | 143 ++++++++++++++++++ 2 files changed, 146 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6c499c3ea32a7..e93b794b7ad71 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7710,6 +7710,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio delivery.generation !== requestedCompletion.generation || delivery.messageId !== command.messageId || (projection.messages.some((candidate) => candidate.id === command.messageId) && + command.steerFollowUpOfRunId === undefined && !isUndeliveredMailboxSteer(projection, command.messageId)) ) { return yield* new OrchestratorDispatchError({ @@ -7786,6 +7787,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // A steer follow-up was declined by the active turn; steering it again loses it. + command.steerFollowUpOfRunId === undefined && // Steering refuses a command, so a notice that reads like one stays queued. !isSlashCommand(command) && (delegatedCompletion !== undefined diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 229fb66ff8791..0fc200d0c5715 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1723,6 +1723,149 @@ it.effect.each(declinedSteerTimings)( }), ); +// regression: #41509 a declined steer of a delegated completion wake must still queue the wake +it.effect("queues a delegated completion wake whose steer the provider declined", () => + Effect.gen(function* () { + const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "steering-declined-delegated-completion", + false, + true, + Effect.void, + true, + undefined, + (turn) => + Effect.fail( + new ProviderAdapter.ProviderAdapterSteerDeclinedError({ + driver, + providerThreadId: turn.providerThread.id, + providerTurnId: turn.providerTurnId, + }), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + const messageId = MessageId.make("message:declined-wake"); + const taskId = NodeId.make("task:declined-wake"); + const parentRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === first.runId, + )!; + const now = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:declined-wake:cohort"), + type: "run.updated", + threadId, + runId: first.runId, + occurredAt: now, + payload: { + ...parentRun, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { generation: 1, messageId, taskIds: [taskId] }, + }, + }, + }, + { + id: EventId.make("event:declined-wake:task"), + type: "subagent.updated", + threadId, + runId: first.runId, + nodeId: taskId, + occurredAt: now, + payload: { + id: taskId, + threadId, + runId: first.runId, + parentNodeId: first.rootNodeId, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId: instanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Do background work", + title: "Background test", + model: null, + completionWake: "always", + completionDelivery: { state: "claimed", observedByRunId: null }, + status: "completed", + result: "done", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("wake"), + threadId, + messageId, + text: "Delegated task completed", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { parentRunId: first.runId, generation: 1, taskIds: [taskId] }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId( + CommandId.make("wake"), + ); + assert.deepEqual( + effects.map((effect) => [effect.request.type, effect.status]), + [["provider-turn.steer", "succeeded"]], + "the declined steer's queue fallback was rejected", + ); + const pending = yield* orchestrator.getThreadProjection(threadId); + const queued = pending.runs.find( + (run) => run.userMessageId === messageId && run.id !== first.runId, + ); + assert.equal(queued?.status, "queued"); + + const turn = pending.providerTurns[0]!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + assert.equal(started[1]?.message.messageId, messageId, "the parent was never woken"); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #26695 cancelling a Copilot prompt to steer it kills its background agents it.effect("queues a steer until the turn ends when the provider cannot steer it", () => Effect.gen(function* () { From 856b105fa23f9cb9fdd49a8f102cb66a71b78265 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 08:13:01 -0800 Subject: [PATCH 132/288] test(server): HTML preview revision test no longer depends on a fine kernel clock (#40931) Co-authored-by: Claude Opus 5.5 --- apps/server/src/assets/AssetAccess.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 64831512a9ef7..0f3f8519bddc7 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1306,8 +1306,16 @@ describe("AssetAccess", () => { const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" }); const pages = path.join(root, "pages"); yield* fileSystem.makeDirectory(pages); + // Coarse kernel clocks can stamp two quick same-size writes alike, so each edit gets its own mtime. + let editedAt = 1_000; const write = (name: string, text: string) => - fileSystem.writeFileString(path.join(pages, name), text); + fileSystem + .writeFileString(path.join(pages, name), text) + .pipe( + Effect.andThen( + Effect.promise(() => NodeFSP.utimes(path.join(pages, name), ++editedAt, editedAt)), + ), + ); yield* write("a.html", ''); yield* write("a.css", "body { color: red; }"); yield* write("b.html", "

b

"); From ba70b56b14b0781d57beea439eae1c2282a03e30 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 08:19:10 -0800 Subject: [PATCH 133/288] test(server): PeerLinks refused-address test no longer reuses its closed port (#40415) Co-authored-by: Claude Opus 5.5 --- apps/server/src/peer/PeerLinks.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 8f1d6cc381d63..3861fbb97b074 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -859,9 +859,8 @@ it.effect("linking a picked machine that answers nowhere names it and links noth it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () => Effect.scoped( Effect.gen(function* () { - const closed = yield* Effect.scoped( - serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))), - ); + // Any test worker can reuse a closed ephemeral port; port 2 is privileged and outside that range. + const closed = "http://127.0.0.1:2"; const notT3 = yield* serveRaw(() => Effect.succeed( HttpServerResponse.text("

Not Found

", { status: 404, contentType: "text/html" }), From 3b08d975ab58ed19ff7c61b077f69c4bd818989f Mon Sep 17 00:00:00 2001 From: Shadman Taqi <61359614+iamshadmantaqi@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:20:14 +0600 Subject: [PATCH 134/288] fix(web): the desktop app plays thread sounds after a reload (#41518) Co-authored-by: Julius Marminge --- ...NotificationCoordinator.badge.browser.test.ts | 16 +++++++++++++++- .../components/ThreadNotificationCoordinator.tsx | 2 ++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 7da8504990fe6..6b2414dfaf38b 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({ shells: null as unknown as { set: (id: string, value: unknown) => void }, navigate: vi.fn(), sound: vi.fn(), + unlock: vi.fn(), badge: vi.fn(), settingsListeners: new Set<() => void>(), })); @@ -80,7 +81,7 @@ vi.mock(import("../hooks/useSettings"), async (original) => ({ vi.mock(import("../threadNotifications"), async (original) => ({ ...(await original()), playNotificationSound: state.sound, - unlockNotificationAudio: vi.fn(), + unlockNotificationAudio: state.unlock, setNotificationBadge: state.badge, })); @@ -293,6 +294,19 @@ it("presents completion notifications and sound as soon as the shell completes", expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function)); }); +it.each([ + { client: "desktop app", when: "at startup", bridge: {}, beforeGesture: 1 }, + { client: "browser", when: "on the first gesture", bridge: undefined, beforeGesture: 0 }, +])("readies notification sound in the $client $when", async ({ bridge, beforeGesture }) => { + await using app = setup(); + using _bridge = stubGlobal("desktopBridge", bridge); + state.mode = "sound"; + app.start(); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture); + document.dispatchEvent(new Event("pointerdown")); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture + 1); +}); + it.each([false, true])( "presents one completion when a monitor ends with a final wake (disconnected: %s)", async (disconnect) => { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index e2801c97d6e8d..7f91d48643bbf 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -408,6 +408,8 @@ export function startThreadNotifications( }); } if (hasNotificationSound(nextMode)) { + // Electron's default autoplay policy needs no gesture, unlike browsers. + if (window.desktopBridge) unlockNotificationAudio(); document.addEventListener("pointerdown", unlockNotificationAudio); document.addEventListener("keydown", unlockNotificationAudio); stops.push(() => { From 9fae2cc22888b391d1935716f44b1d7447aa2b6e Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:35:57 -0600 Subject: [PATCH 135/288] fix(web): accept TIFF Exif and GPS pointers stored as IFD type 13 (#41526) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 42 ++++++++++++++----- .../components/files/imageDecode.worker.ts | 3 +- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 77e339925c97e..10c013cc04723 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -514,14 +514,16 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs tags and rejects oversized metadata before decoding", async () => { + it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs and type-13 ExifIFD pointers and rejects invalid metadata before decoding", async () => { let bytes = new ArrayBuffer(0); + let exifEntry = 0; for (const { pixels, expected } of [ { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, ]) { const samples = pixels.length / 2; - const start = samples === 2 ? 158 : 146; + const start = samples === 2 ? 170 : 158; + const exif = start + pixels.length; const tags = [ [256, 2], [257, 1], @@ -535,8 +537,10 @@ describe("bounded binary previews", () => { [284, 1], [330, 0, 13], ...(samples === 2 ? [[338, 2]] : []), + [34665, exif, 13], ]; - bytes = new ArrayBuffer(start + pixels.length); + exifEntry = 10 + (tags.length - 1) * 12; + bytes = new ArrayBuffer(exif + 8); const view = new DataView(bytes); view.setUint16(0, 0x4949); view.setUint16(2, 42, true); @@ -563,14 +567,30 @@ describe("bounded binary previews", () => { URL.revokeObjectURL(src); } } - new DataView(bytes).setUint32(14, 1_000_000, true); - const invalid = URL.createObjectURL(new Blob([bytes])); - try { - await expect( - decodeImagePreview(invalid, false, new AbortController().signal), - ).rejects.toThrow("metadata"); - } finally { - URL.revokeObjectURL(invalid); + for (const [mutate, message] of [ + [ + (view: DataView) => view.setUint16(exifEntry + 2, 3, true), + "Invalid TIFF metadata pointer.", + ], + [ + (view: DataView) => view.setUint32(exifEntry + 4, 2, true), + "Invalid TIFF metadata pointer.", + ], + [ + (view: DataView) => view.setUint32(14, 1_000_000, true), + "This TIFF has too much or truncated metadata.", + ], + ] as const) { + const copy = bytes.slice(0); + mutate(new DataView(copy)); + const invalid = URL.createObjectURL(new Blob([copy])); + try { + await expect( + decodeImagePreview(invalid, false, new AbortController().signal), + ).rejects.toThrow(message); + } finally { + URL.revokeObjectURL(invalid); + } } }); }); diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index 9cd3140308612..a3661b22612fb 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -34,7 +34,8 @@ function validateTiffMetadata(bytes: ArrayBuffer) { if (start + length > bytes.byteLength || allocation > 8 * 1024 * 1024) throw new PreviewError({ code: "tiff-metadata-truncated" }); if (tag === 0x8769 || tag === 0x8825) { - if (type !== 4 || values !== 1) throw new PreviewError({ code: "tiff-metadata-pointer" }); + if ((type !== 4 && type !== 13) || values !== 1) + throw new PreviewError({ code: "tiff-metadata-pointer" }); inspect(view.getUint32(entry + 8, littleEndian), depth + 1); } } From f58085a1c2e5bea0b020ee2d4d69f8768b7b228d Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:38:17 -0600 Subject: [PATCH 136/288] fix(server): EPUBs with a percent-encoded package path extract their chapters (#41523) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 6 ++++- .../src/provider/userInputAttachments.test.ts | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index cf25d9c2f40d2..027029139a77e 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -838,7 +838,7 @@ async function* document(path: string, extension: string): AsyncGenerator [item.attrs.id, item.attrs.href]), diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index be2aab625142d..2e44f3501355c 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -741,6 +741,33 @@ describe("question answer paths", () => { ], absent: ["[Extracted text truncated"], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "My Book/book 1.opf": + '', + "My Book/ch1.xhtml": "

Percent-encoded rootfile chapter text.

", + }, + expected: ["Percent-encoded rootfile chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "OPS/book%201.opf": + '', + "ops/book 1.opf": + '', + "OPS/correct.xhtml": "

Correct primary chapter

", + "ops/other.xhtml": "

Wrong alternate chapter

", + }, + expected: ["Correct primary chapter"], + absent: ["Wrong alternate chapter", "[Skipped document part"], + }, ...[false, true].flatMap((bom) => [false, true].map((bigEndian) => { const encode = (source: string) => { From e2e8a49d972219e926f0940246208e82d129c87a Mon Sep 17 00:00:00 2001 From: Anton Metzner Rodriguez Date: Mon, 23 Nov 2026 18:08:22 +0100 Subject: [PATCH 137/288] fix(web): a PDF keeps its place when the pane is resized (#41537) Co-authored-by: Julius Marminge --- .../files/PdfViewer.browser.test.tsx | 33 +++++++++++++++++++ apps/web/src/components/files/PdfViewer.tsx | 15 +++++---- apps/web/src/components/files/pdfLayout.ts | 12 +++++++ 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsx index ef339999e8d10..81bf3bcf91364 100644 --- a/apps/web/src/components/files/PdfViewer.browser.test.tsx +++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx @@ -175,6 +175,39 @@ it("keeps the painted page while its width changes, then repaints it without a b } }); +it("keeps the page in view, with its painted canvas, when the pane narrows", async () => { + const page = { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Text) Tj ET" }; + const url = URL.createObjectURL(testPdf(Array.from({ length: 6 }, () => page))); + try { + const container = document.createElement("div"); + container.style.cssText = "display:flex;width:500px;height:300px"; + await using screen = await render( + , + { container }, + ); + await expect.element(screen.getByText("4 / 6 pages"), { timeout: 10_000 }).toBeVisible(); + const region = screen.container.querySelector('[role="region"]')!; + const canvas = region.querySelector('canvas[aria-label="Page 4"]')!; + await vi.waitFor(() => expect(canvas.width).toBeGreaterThan(300)); + + container.style.width = "300px"; + await vi.waitFor(() => { + const top = region.getBoundingClientRect().top; + const box = canvas.getBoundingClientRect(); + expect(box.width).toBe(region.clientWidth - 32); + expect(box.top).toBeLessThanOrEqual(top); + expect(box.bottom).toBeGreaterThan(top); + }); + await expect.element(screen.getByText("4 / 6 pages")).toBeVisible(); + } finally { + URL.revokeObjectURL(url); + } +}); + it("jumps to the first hit while still counting and keeps later manual navigation", async () => { setup(4); const page = (text: string) => ({ diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index 31faf628fbeb9..9842a621c0302 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -27,6 +27,7 @@ import { pdfPageScrollTop, pdfPageText, pdfPageWidth, + pdfResizedScrollTop, pdfRestoredScrollTop, PDF_MAX_ZOOM, PDF_MIN_ZOOM, @@ -263,7 +264,7 @@ export default function PdfViewer(props: { const [zoom, setZoom] = useState(initialView.zoom); const [pageWidth, setPageWidth] = useState(612); const [viewport, setViewport] = useState({ width: 600, height: 800 }); - const [scrollTop, setScrollTop] = useState(0); + const [scrolled, setScrolled] = useState({ top: 0, width: 0, pdf }); const [query, setQuery] = useState(""); const [matches, setMatches] = useState([]); const [finding, setFinding] = useState(false); @@ -338,6 +339,9 @@ export default function PdfViewer(props: { }, []); const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom); const offsets = pdfPageOffsets(ratios, width); + // A new page width moves every page, so the place in view has a new offset before the DOM scrolls. + const resized = pdf !== null && scrolled.pdf === pdf && scrolled.width !== width; + const scrollTop = resized ? pdfResizedScrollTop(ratios, scrolled, width) : scrolled.top; const current = currentPdfPage(offsets, ratios.length, scrollTop); const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height); // Stable callbacks let page canvases survive scroll and find updates. @@ -374,7 +378,7 @@ export default function PdfViewer(props: { top: pdfRestoredScrollTop(ratios, width, initialView, savedPosition?.width), left: initialView.left, }); - setScrollTop(node.scrollTop); + setScrolled({ top: node.scrollTop, width, pdf }); saveView(node); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits. @@ -392,7 +396,7 @@ export default function PdfViewer(props: { }; setZoom(value); }; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after the new zoom width has committed to page layout. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after a zoom or resize has committed the new page width. useLayoutEffect(() => { const anchor = zoomAnchor.current; zoomAnchor.current = null; @@ -402,7 +406,7 @@ export default function PdfViewer(props: { node.scrollTo({ top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width, }); - } + } else if (resized) node.scrollTo({ top: scrollTop }); saveView(node, anchor !== null); }); const firstMatch = matches[0]; @@ -561,8 +565,7 @@ export default function PdfViewer(props: { tabIndex={0} className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40" onScroll={(event) => { - const top = event.currentTarget.scrollTop; - setScrollTop(top); + setScrolled({ top: event.currentTarget.scrollTop, width, pdf }); saveView(event.currentTarget); }} onKeyDown={(event) => { diff --git a/apps/web/src/components/files/pdfLayout.ts b/apps/web/src/components/files/pdfLayout.ts index 9292fcf583b46..0f48a112aa07d 100644 --- a/apps/web/src/components/files/pdfLayout.ts +++ b/apps/web/src/components/files/pdfLayout.ts @@ -66,6 +66,18 @@ export function pdfRestoredScrollTop( ); } +/** Where the place at `from.top` lands after the page width changes from `from.width`. */ +export function pdfResizedScrollTop( + ratios: readonly number[], + from: { top: number; width: number }, + width: number, +) { + const offsets = pdfPageOffsets(ratios, from.width); + const page = currentPdfPage(offsets, ratios.length, from.top); + const offset = from.top - (offsets[page]! - PDF_PAGE_GAP); + return pdfRestoredScrollTop(ratios, width, { page, offset }, from.width); +} + export function pdfPageText( items: readonly ({ str: string; hasEOL: boolean } | { type: string })[], ) { From 990412468340b8362f82610de0eae70a5171abb7 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:09:55 -0600 Subject: [PATCH 138/288] fix(web): EPUBs with a percent-encoded package path open in the file preview (#41540) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 26 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 5 ++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index b32a64fd18373..0b4d7dc46b49f 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -667,4 +667,30 @@ Third}`; expect(result.pages[1]!.html).toContain('src="data:image/png;base64,'); expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/); }); + + it.each([ + ["percent-encoded", "My%20Book/book%201.opf", "My Book/book 1.opf", "My Book/one.xhtml"], + ["literal percent", "My%20Book/book.opf", "My%20Book/book.opf", "My%20Book/one.xhtml"], + ["malformed percent", "Book%ZZ/book.opf", "Book%ZZ/book.opf", "Book%ZZ/one.xhtml"], + ])( + "reads EPUB packages with %s rootfile paths", + async (_label, fullPath, packagePath, chapterPath) => { + const archive = new JSZip() + .file( + "META-INF/container.xml", + ``, + ) + .file( + packagePath, + '', + ) + .file( + chapterPath, + "First

Hello

", + ); + const result = await openEpub(archive); + if (result.type !== "document") throw new Error("Expected document"); + expect(result.pages).toEqual([{ title: "First", html: "

Hello

" }]); + }, + ); }); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index d04f1c9882ee9..f57d9c59a101d 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -423,8 +423,9 @@ export async function openDocument( export async function openEpub(archive: JSZip): Promise { markupBytes = 0; const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? ""); - const rootfile = find(container, "rootfile")[0]?.attrs["full-path"]; - if (!rootfile || !archive.file(rootfile)) throw new PreviewError({ code: "epub-no-package" }); + const fullPath = find(container, "rootfile")[0]?.attrs["full-path"] ?? ""; + const rootfile = [archivePath("", fullPath), fullPath].find((path) => path && archive.file(path)); + if (!rootfile) throw new PreviewError({ code: "epub-no-package" }); const packageRoot = parseXml(await archive.file(rootfile)!.async("string")); const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item])); const spine = find(packageRoot, "itemref"); From 7182abeeaab345f8a8e863a7835aead9b50ae57f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:19:01 -0800 Subject: [PATCH 139/288] fix(client-runtime): command failures show the server's text for string defects (#41550) --- .../src/errors/translatable.test.ts | 21 +++++++++++++++++++ packages/client-runtime/src/state/runtime.ts | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 packages/client-runtime/src/errors/translatable.test.ts diff --git a/packages/client-runtime/src/errors/translatable.test.ts b/packages/client-runtime/src/errors/translatable.test.ts new file mode 100644 index 0000000000000..de0339d9fd2d7 --- /dev/null +++ b/packages/client-runtime/src/errors/translatable.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; +import * as Schema from "effect/Schema"; + +import { squashAtomCommandFailure } from "../state/runtime.ts"; +import { thrownErrorMessage } from "./translatable.ts"; + +const decodeDefect = Schema.decodeUnknownSync(Schema.Defect()); + +describe("thrownErrorMessage", () => { + it("shows the text of a string defect that came back over RPC", () => { + const defect = decodeDefect( + "RPC contract is registered but unavailable in the control plane: projectClone.start", + ); + const error = squashAtomCommandFailure({ cause: Cause.die(defect) }); + + expect(thrownErrorMessage(error)).toBe( + "RPC contract is registered but unavailable in the control plane: projectClone.start", + ); + }); +}); diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index f91f838db78b0..b4674a07cb469 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -404,7 +404,9 @@ export function isAtomCommandInterrupted(result: AtomCommandResult; }): unknown { - return Cause.squash(result.cause); + const squashed = Cause.squash(result.cause); + // A server `Effect.die("text")` decodes over RPC as a bare string; callers read `Error`s. + return typeof squashed === "string" ? new Error(squashed) : squashed; } export async function settleAsyncResult( From 1c9ccc7127c386a50644535070ffc9168fbf8d74 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:29:00 -0800 Subject: [PATCH 140/288] fix(web): a grouped project's folder New thread starts on the viewed machine's copy (#41554) --- .../src/components/Sidebar.browser.test.tsx | 61 +++++++++++++++++++ apps/web/src/components/Sidebar.tsx | 13 +++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1fb930f55fabc..87f43d9f901f6 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -25,6 +25,7 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; +import { useConnectedEnvironmentIds, usePrimaryEnvironmentId } from "../state/environments"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -40,6 +41,7 @@ vi.mock(import("../state/olderSettledShelf"), async (original) => { return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) }; }); vi.mock("../state/entities", { spy: true }); +vi.mock("../state/environments", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); vi.mock("../hooks/useNowMinute", { spy: true }); vi.mock("../hooks/useThreadRouteTarget", { spy: true }); @@ -132,6 +134,65 @@ describe("sidebar header new thread", () => { }); }); +// regression: #41549 a grouped project's folder New thread went to the primary copy +describe("sidebar project folder new thread", () => { + it("starts in the copy of the viewed thread, as the new-thread shortcut does", async () => { + using stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: true }); + const primary = EnvironmentId.make("local"); + const dev1 = EnvironmentId.make("dev1"); + const repositoryIdentity = { + canonicalKey: "github.com/acme/demo-repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/acme/demo-repo.git", + }, + displayName: "acme/demo-repo", + }; + const primaryCopy = { ...project("demo-primary"), repositoryIdentity }; + const dev1Copy = { + ...project("demo-dev1"), + environmentId: dev1, + repositoryIdentity, + }; + vi.mocked(usePrimaryEnvironmentId).mockReturnValue(primary); + vi.mocked(useConnectedEnvironmentIds).mockReturnValue([primary, dev1]); + vi.mocked(useProjects).mockReturnValue([primaryCopy, dev1Copy]); + const dev1Thread = makeThreadFixture({ + environmentId: dev1, + id: ThreadId.make("dev1-thread"), + projectId: dev1Copy.id, + title: "dev1 work", + }); + vi.mocked(useQuietThreadShells).mockReturnValue([dev1Thread]); + const threadRef = scopeThreadRef(dev1, dev1Thread.id); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + const dev1ProjectRef = scopeProjectRef(dev1, dev1Copy.id); + const startThread = vi.fn().mockResolvedValue(null); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: dev1Thread, + defaultProjectRef: dev1ProjectRef, + defaultProjectFallbackReady: true, + handleNewThread: startThread, + routeDraftId: null, + routeThreadRef: threadRef, + }); + + await using screen = await render( + + + , + ); + await userEvent.click(screen.getByRole("button", { name: "New thread in acme/demo-repo" })); + + expect(startThread).toHaveBeenCalledExactlyOnceWith(dev1ProjectRef); + }); +}); + // regression: #38623 unsent drafts are listed above threads but mod+1..9 skipped them describe("sidebar numbered jumps", () => { it("numbers the unsent draft at the top before the threads below it", async () => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 9c1918be6b8e7..59fcb56bfce9d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -114,6 +114,7 @@ import { selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { + buildSidebarProjectPickerEntries, projectGroupsSpanEnvironments, resolveSidebarProjectScopeKeys, getSidebarProjectSettingsKey, @@ -135,7 +136,7 @@ import { useProjectPin } from "../hooks/useProjectGroupUpdate"; import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; -import { startNewThreadFromContext } from "../lib/chatThreadActions"; +import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions"; import { useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; @@ -1267,7 +1268,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => { if (isMobile) setOpenMobile(false); - void handleNewThread(scopeProjectRef(group.environmentId, group.id)); + const [entry] = buildSidebarProjectPickerEntries({ + groups: [group], + preferredProjectRef: resolveThreadActionProjectRef({ + ...newThreadContext, + activeThread: newThreadContext.activeThread ?? undefined, + }), + }); + const target = entry?.targetProject ?? group; + void handleNewThread(scopeProjectRef(target.environmentId, target.id)); }); const handleProjectFolderContextMenu = useStableCallback( ( From a9bec417292b06e3c180bb0ee6b1eb9e70d47986 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:31:28 -0600 Subject: [PATCH 141/288] fix(web): Office previews open files with malformed external links or spaced sheet names (#41547) Co-authored-by: Julius Marminge --- .../components/files/officeArchive.test.ts | 85 ++++++++++++++++++- .../web/src/components/files/officeArchive.ts | 26 +++--- 2 files changed, 100 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/files/officeArchive.test.ts b/apps/web/src/components/files/officeArchive.test.ts index 7e50bf5c80b02..fd8718e21fdcf 100644 --- a/apps/web/src/components/files/officeArchive.test.ts +++ b/apps/web/src/components/files/officeArchive.test.ts @@ -15,6 +15,7 @@ async function wordFile( body: string, parts: Partial> = {}, section = "", + extraRels = "", ) { const zip = new JSZip(); zip.file( @@ -31,7 +32,7 @@ async function wordFile( parts, ) .map((part) => relationship(part, `${part}.xml`)) - .join("")}`, + .join("")}${extraRels}`, ); for (const [part, xml] of Object.entries(parts)) zip.file(`word/${part}.xml`, xml); zip.file( @@ -148,4 +149,86 @@ describe("Word preview limits", () => { expect(await result.part("word/footnotes.xml")).toBe(footnotes); expect(await result.part("word/document.xml")).toContain("Body"); }); + + it("drops a malformed external hyperlink relationship while keeping body text", async () => { + const result = await prepared( + await wordFile( + paragraph("Body text"), + {}, + "", + ``, + ), + ); + expect(result.truncated).toBe(false); + expect(await result.part("word/document.xml")).toContain("Body text"); + expect(await result.part("word/_rels/document.xml.rels")).not.toContain("badLink"); + }); +}); + +async function workbookFile( + target: string, + sheetPath: string, + extraRels = "", + targetMode = "Internal", +) { + const zip = new JSZip(); + zip.file( + "[Content_Types].xml", + ``, + ); + zip.file( + "_rels/.rels", + `${relationship("officeDocument", "xl/workbook.xml")}`, + ); + zip.file( + "xl/workbook.xml", + ``, + ); + zip.file( + "xl/_rels/workbook.xml.rels", + `${extraRels}`, + ); + zip.file( + sheetPath, + `42`, + ); + return zip.generateAsync({ type: "arraybuffer" }); +} + +describe("Workbook relationship targets", () => { + it.each(["sheet 1.xml", "sheet%201.xml", "sheet#1.xml"])( + "prepares a worksheet whose ZIP name matches its target literally (%s)", + async (name) => { + const result = await prepareOffice( + await workbookFile(`worksheets/${name}`, `xl/worksheets/${name}`), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + expect(result.truncated).toBe(false); + expect(await zip.file(`xl/worksheets/${name}`)?.async("string")).toContain("42"); + }, + ); + + it("refuses a worksheet whose relationship is external", async () => { + await expect( + prepareOffice( + await workbookFile("worksheets/sheet2.xml", "xl/worksheets/sheet2.xml", "", "External"), + "xlsx", + ), + ).rejects.toMatchObject({ code: "workbook-sheet-count" }); + }); + + it("handles a malformed external relationship in workbook relationships", async () => { + const result = await prepareOffice( + await workbookFile( + "worksheets/sheet1.xml", + "xl/worksheets/sheet1.xml", + ``, + ), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + expect(result.truncated).toBe(false); + expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42"); + }); }); diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.ts index aabfc0b21f6dc..0e9b59ab8e9eb 100644 --- a/apps/web/src/components/files/officeArchive.ts +++ b/apps/web/src/components/files/officeArchive.ts @@ -598,10 +598,16 @@ async function boundWorkbook(archive: JSZip) { relationships.on("opentag", (tag) => { if (tag.local !== "Relationship") return; const type = tag.attributes.Type?.value; - const path = new URL( - tag.attributes.Target?.value ?? "", - "https://docx.invalid/xl/workbook.xml", - ).pathname.slice(1); + const target = tag.attributes.Target?.value ?? ""; + // Resolve as the engine does: literal ZIP names split on `/`, never URL syntax or escapes. + const segments = target.startsWith("/") ? [] : ["xl"]; + for (const segment of target.split("/")) { + if (segment === "..") segments.pop(); + else if (segment && segment !== ".") segments.push(segment); + } + const external = tag.attributes.TargetMode?.value.toLowerCase() === "external"; + // The engine reads an external worksheet from its default part, so leave it unresolved to refuse it. + const path = external && type?.endsWith("/worksheet") ? "" : segments.join("/"); if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path); else if (/\/(?:chartsheet|dialogsheet|xlMacrosheet|xlIntlMacrosheet)$/.test(type ?? "")) otherSheets.add(tag.attributes.Id?.value ?? ""); @@ -755,13 +761,13 @@ function wordPartTypes() { const external = attr("TargetMode").toLowerCase() === "external" || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(attr("Target")); - const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, ""); - // Preserve archive URL resolution, including literal query/fragment - // characters in ZIP names rather than silently classifying another file. - const target = new URL(attr("Target"), `https://docx.invalid/${folder}`) - .toString() - .slice("https://docx.invalid/".length); if (!external) { + const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, ""); + // Preserve archive URL resolution, including literal query/fragment + // characters in ZIP names rather than silently classifying another file. + const target = new URL(attr("Target"), `https://docx.invalid/${folder}`) + .toString() + .slice("https://docx.invalid/".length); if ( !WORD_BINARY_PARTS.has(role) && role !== "hyperlink" && From fa2ee196b5b4d371aecdedbebc3cdbc0c20c8553 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:35:37 -0800 Subject: [PATCH 142/288] fix(web): archived threads settings stay responsive with thousands of threads (#41539) --- .../settings/ArchivedThreadsPanel.tsx | 175 ++++++++++++------ 1 file changed, 118 insertions(+), 57 deletions(-) diff --git a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx index c44d37a359b1b..0ea512be7f9d5 100644 --- a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx +++ b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx @@ -23,7 +23,8 @@ import { useSearchableSetting } from "./settingsSearch"; import { ProjectFavicon } from "../ProjectFavicon"; import { msg, T, useGT, useMessages } from "gt-react"; -import { useRef, useState } from "react"; +import { type ReactNode, useRef, useState } from "react"; +import { observeIntersection } from "~/lib/observeIntersection"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; const ARCHIVE_ACTIONS = [ @@ -44,6 +45,43 @@ const ARCHIVE_ACTIONS = [ ] as const; type ArchiveAction = (typeof ARCHIVE_ACTIONS)[number]["action"]; +const ARCHIVED_ROW_CHUNK_SIZE = 50; +const ESTIMATED_ARCHIVED_ROW_PX = 67; + +// Thousands of archived threads would mount at once, so each chunk of rows mounts only near the +// visible part of the settings scroller and otherwise keeps its last measured height. +function ArchivedThreadChunk(props: { + readonly rowCount: number; + readonly initiallyMounted: boolean; + readonly renderRows: () => ReactNode; +}) { + const { rowCount } = props; + const [view, setView] = useState({ + near: props.initiallyMounted, + rowHeight: ESTIMATED_ARCHIVED_ROW_PX, + }); + return ( +
{ + if (!node) return; + return observeIntersection( + node, + (entry) => + setView({ + near: entry.isIntersecting, + rowHeight: entry.boundingClientRect.height / rowCount, + }), + { root: node.closest("[data-settings-page-scroll]"), rootMargin: "1200px 0px" }, + ); + }} + className="*:not-first:border-t *:not-first:border-border/50" + style={view.near ? undefined : { height: view.rowHeight * rowCount }} + > + {view.near ? props.renderRows() : null} +
+ ); +} + export function ArchivedThreadsPanel() { const searchableSetting = useSearchableSetting(); const gt = useGT(); @@ -139,15 +177,21 @@ export function ArchivedThreadsPanel() { } } } - const sortedGroups = Array.from(groups, ([key, group]) => ({ - ...group, - key, - threads: group.threads.toSorted((left, right) => { - const leftKey = left.archivedAt ?? left.createdAt; - const rightKey = right.archivedAt ?? right.createdAt; - return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); - }), - })); + const sortedGroups = []; + let firstRow = 0; + for (const [key, group] of groups) { + sortedGroups.push({ + ...group, + key, + firstRow, + threads: group.threads.toSorted((left, right) => { + const leftKey = left.archivedAt ?? left.createdAt; + const rightKey = right.archivedAt ?? right.createdAt; + return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); + }), + }); + firstRow += group.threads.length; + } return { groups: sortedGroups, hasMultipleEnvironments }; })(); @@ -210,6 +254,54 @@ export function ArchivedThreadsPanel() { reportFailure(result, gt("Archived thread action failed")); }; + const renderRow = (thread: ArchivedThread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + return ( + { + event.preventDefault(); + void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); + }} + title={thread.title} + description={ + + {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} + + Archived + {" \u00b7 Created "} + + + + } + control={ +
+ {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( + + void handleThreadAction(action, thread)} + /> + } + > + + + {m(label)} + + ))} +
+ } + /> + ); + }; + return ( {archivedGroups.length === 0 ? ( @@ -240,59 +332,28 @@ export function ArchivedThreadsPanel() { /> ) : ( - archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => ( + archivedGroups.map(({ key, project, title, firstRow, threads: projectThreads }, index) => ( } > - {projectThreads.map((thread) => { - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - return ( - { - event.preventDefault(); - void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); - }} - title={thread.title} - description={ - - {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} - - Archived - {" \u00b7 Created "} - - - - } - control={ -
- {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( - - void handleThreadAction(action, thread)} - /> - } - > - - - {m(label)} - - ))} -
- } - /> - ); - })} + {Array.from( + { length: Math.ceil(projectThreads.length / ARCHIVED_ROW_CHUNK_SIZE) }, + (_, chunkIndex) => { + const start = chunkIndex * ARCHIVED_ROW_CHUNK_SIZE; + const rows = projectThreads.slice(start, start + ARCHIVED_ROW_CHUNK_SIZE); + return ( + rows.map(renderRow)} + /> + ); + }, + )}
)) )} From 6aad800ecfe268c158af60d1102c3ec4acc9bab9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:53:50 -0600 Subject: [PATCH 143/288] fix(server): EPUB chapters with a query in their href extract their text (#41553) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 027029139a77e..3fe14f40ddbf6 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -864,7 +864,7 @@ async function* document(path: string, extension: string): AsyncGenerator { ], absent: ["[Extracted text truncated"], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": '', + "book.opf": + '', + "q?1.xhtml": "

Encoded question mark chapter text.

", + }, + expected: ["Encoded question mark chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, { ext: "epub", parts: { From 0ea0db39e272a472f26b97e9bfc3a6c7805112f2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:01:33 -0600 Subject: [PATCH 144/288] fix(shared): PascalCase test doubles like MockTransport.ts count as mocks (#41561) Co-authored-by: Julius Marminge --- packages/shared/src/changedFileKind.test.ts | 5 +++++ packages/shared/src/changedFileKind.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/changedFileKind.test.ts b/packages/shared/src/changedFileKind.test.ts index f16ad777d895c..f77db79426740 100644 --- a/packages/shared/src/changedFileKind.test.ts +++ b/packages/shared/src/changedFileKind.test.ts @@ -6,6 +6,11 @@ describe("classifyChangedFile", () => { it.each([ ["src/contest.py", "code"], ["test/fixtures/pr.json", "mocks"], + ["src/MockTransport.ts", "mocks"], + ["src/FakeClock.ts", "mocks"], + ["src/Foo.Mock.ts", "mocks"], + ["src/Mockup.ts", "code"], + ["src/Stubborn.ts", "code"], ["pnpm-lock.yaml", "generated"], ["convex/_generated/api.d.ts", "generated"], ["src/agent.eval.ts", "tests"], diff --git a/packages/shared/src/changedFileKind.ts b/packages/shared/src/changedFileKind.ts index 7da5ba5cb0c11..dca226bd06fc8 100644 --- a/packages/shared/src/changedFileKind.ts +++ b/packages/shared/src/changedFileKind.ts @@ -47,8 +47,9 @@ const GENERATED_NAME = /(\.generated\.|\.gen\.|\.g\.dart$|\.pb\.go$|_pb2(_grpc)?\.py$|\.pb\.(cc|h)$|\.min\.(js|css)$|\.(js|css)\.map$)/; const GENERATED_DIRS = new Set(["__generated__", "_generated", "generated"]); -const MOCK_NAME = - /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$|^(mocks?|fixtures?|stubs?|fakes?)([-_.A-Z]|$))/; +const MOCK_NAME = /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$)/i; +// Case-sensitive after the prefix: `MockClock.ts` is a mock, `Mockup.ts` is not. +const MOCK_PREFIX = /^([Mm]ocks?|[Ff]ixtures?|[Ss]tubs?|[Ff]akes?)([-_.A-Z]|$)/; const MOCK_DIRS = new Set([ "__fixtures__", "__mocks__", @@ -99,7 +100,7 @@ export function classifyChangedFile(path: string): ChangedFileKind { const inDir = (set: ReadonlySet) => dirs.some((dir) => set.has(dir)); if (GENERATED_FILES.has(name.toLowerCase()) || GENERATED_NAME.test(name) || inDir(GENERATED_DIRS)) return "generated"; - if (MOCK_NAME.test(name) || inDir(MOCK_DIRS)) return "mocks"; + if (MOCK_NAME.test(name) || MOCK_PREFIX.test(name) || inDir(MOCK_DIRS)) return "mocks"; if (TEST_NAME.test(name) || CLASS_TEST_NAME.test(name) || inDir(TEST_DIRS)) return "tests"; if (DOCS_NAME.test(name) && !NOT_DOCS_NAME.test(name)) return "docs"; return "code"; From 7f0e736cdba5987e2bc9a9e82e03cfde2d80b62a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:21:19 -0800 Subject: [PATCH 145/288] fix(server): GitHub issue URLs with no project on their host name the missing project (#41581) --- apps/server/src/issue/IssueService.test.ts | 21 +++++++++++++++++++++ apps/server/src/issue/IssueService.ts | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 26d02c06bfe66..f658c26f6c63c 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -349,6 +349,27 @@ describe("IssueService", () => { }), ); + it.effect( + "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout", + () => + Effect.gen(function* () { + // A plain folder project, while GitHub itself is a supported tracker. + const service = yield* makeService({ + projects: [project({ id: "folder" })], + trackers: [fakeTracker()], + }); + const resolved = yield* service + .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId) + .pipe(Effect.result); + if (resolved._tag === "Failure") { + expect(resolved.failure).not.toMatchObject({ + _tag: "IssueUnavailableError", + reason: "tracker-unsupported", + }); + } + }), + ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => Effect.gen(function* () { const tracker = IssueTrackerKind.make("azure-devops"); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 01d8b47382eef..1a913c9b0725f 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -824,7 +824,10 @@ const make = Effect.gen(function* () { if (standalone === null) { const found = serve(onTracker); if (found === null) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "resolveUrl", + detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`, + }); } return found.resolved; } From a369642c1c5c7a9a1e6b906167e3309005ad23e4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:32:01 -0600 Subject: [PATCH 146/288] fix(web): keys pressed on a focused video stay with the player (#41578) Co-authored-by: Julius Marminge --- .../components/chat/composerFocusRedirect.ts | 1 + .../chat/useChatShortcuts.browser.test.tsx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..2fc544a31c9b4 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -12,6 +12,7 @@ const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", + "video[controls]", '[role="application"]', '[role="button"]', '[role="checkbox"]', diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 61127d1a9d9c8..378bc2b5cce74 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -245,3 +245,21 @@ it("runs right panel commands from inside a side chat pane, but not thread comma expect(ran).toEqual(["toggle", "close", "toggle"]); }); + +it("leaves keys to a focused video player with controls", async () => { + const composerKeys: string[] = []; + await using _screen = await render( + <> + +
or in one piece (#41596) Co-authored-by: Julius Marminge --- packages/shared/src/markdownChunks.test.ts | 42 +++++++++++++++++++++- packages/shared/src/markdownChunks.ts | 34 +++++++++++++++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts index a5cf2a8017b35..8b4801ad7594f 100644 --- a/packages/shared/src/markdownChunks.test.ts +++ b/packages/shared/src/markdownChunks.test.ts @@ -76,9 +76,49 @@ describe("splitMarkdown", () => { "# literal", "", "", + "
", + "Answer", + "", + "Inside details", + "", + "
", + "", + "
", + "", + "```ts", + "inside a cell", + "```", + "", + "
", + "", + '
    ', + "", + "
  1. one
  2. ", + "", + "
  3. two
  4. ", + "", + "
", + "", + "```html", + "
", + "```", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["', + "", + "Inside details", + "", + "
", + "", "after", ].join("\n"); - expect(starts(text)).toEqual(["", open + 4); + if (close === -1) break; + kept += line.slice(at, open); + at = close + 3; + } + return kept + line.slice(at); +} + +function openedWrappers(line: string): number { + let opened = 0; + for (const [, closing] of withoutComments(line).matchAll(WRAPPER_TAG)) { + opened += closing ? -1 : 1; + } + return opened; +} /** Returns how to recognize the end of a block that `line` opens, or null for none. */ function blockCloser(line: string): ((line: string) => boolean) | null { @@ -44,7 +71,7 @@ function blockCloser(line: string): ((line: string) => boolean) | null { return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); } // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. - return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; + return HTML_BLOCK_START.test(line) ? closesAtBlankLine : null; } export interface MarkdownChunk { @@ -86,6 +113,7 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let afterDefinition = false; let afterHeading = false; let definitionChars = 0; + let openWrappers = 0; const flush = () => { chunks.push({ text: lines.join("\n"), lines: lines.length }); lines = []; @@ -98,8 +126,10 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let seen = 0; closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; } else { + if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0; const cut = chars >= targetChars && + openWrappers === 0 && (ATX_HEADING.test(line) || (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); if (cut) flush(); @@ -114,6 +144,8 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S definitionChars += line.length + 1; } } + if (closes === closesAtBlankLine) + openWrappers = Math.max(0, openWrappers + openedWrappers(line)); first = false; lines.push(line); chars += line.length + 1; From 0fcfc17c81a88eb5f0d9bff76425c5872f0465f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 11:39:06 -0800 Subject: [PATCH 155/288] fix(server): older history no longer reads every attempt row to find steered ones (#41620) --- apps/server/src/persistence/Migrations.ts | 2 ++ .../Migrations/111_SupersededRunAttemptIndex.ts | 14 ++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 2 ++ 3 files changed, 18 insertions(+) create mode 100644 apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 36762e9059b58..5c24577ad53ec 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -118,6 +118,7 @@ import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; import Migration0108 from "./Migrations/108_AgentFeedback.ts"; import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts"; import Migration0110 from "./Migrations/110_Workflows.ts"; +import Migration0111 from "./Migrations/111_SupersededRunAttemptIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -231,6 +232,7 @@ const migrationEntries = [ [108, "AgentFeedback", Migration0108], [109, "IssueTrackerAccounts", Migration0109], [110, "Workflows", Migration0110], + [111, "SupersededRunAttemptIndex", Migration0111], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts new file mode 100644 index 0000000000000..ad2f9f4a3817e --- /dev/null +++ b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Opening a thread's history looks up its few superseded attempts. Without this index that + // reads every attempt row of the thread, which is slow on a long thread with a cold cache. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_run_attempts_superseded_idx + ON orchestration_v2_projection_run_attempts(thread_id, run_id, root_node_id) + WHERE status = 'superseded' + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 1b8cf040b5fbc..de0d6a3f63ff5 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -90,6 +90,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -223,6 +224,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 4ab87289acdce039c9c68626f1fb74e8a3b59d50 Mon Sep 17 00:00:00 2001 From: James Cane Date: Mon, 23 Nov 2026 19:40:16 +0000 Subject: [PATCH 156/288] fix(server): recover dropped T3 MCP tool results in ACP and OpenCode Code Mode (#41552) Co-authored-by: Julius Marminge --- apps/server/src/mcp/McpHttpServer.ts | 74 +++- apps/server/src/mcp/toolkits/core.test.ts | 41 +++ .../Adapters/AntigravityAdapterV2.test.ts | 330 +++++++++++++++++- .../Adapters/OpenCode2AdapterV2.test.ts | 196 ++++++++++- .../provider/acp/AntigravityProtocol.test.ts | 34 ++ .../src/provider/acp/AntigravityProtocol.ts | 56 ++- packages/provider-acp/src/server/adapter.ts | 135 ++++++- .../src/server/McpProviderSessions.test.ts | 161 +++++++++ .../src/server/McpProviderSessions.ts | 153 +++++++- .../provider-opencode/src/server/toolItems.ts | 128 ++++++- .../src/server/v2/adapter.ts | 97 ++++- packages/shared/src/toolOutput.test.ts | 13 + packages/shared/src/toolOutput.ts | 20 ++ 13 files changed, 1398 insertions(+), 40 deletions(-) create mode 100644 packages/provider-core/src/server/McpProviderSessions.test.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index be41f8630b7dd..2b1deed86f037 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -56,6 +56,9 @@ import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; +import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -1218,6 +1221,67 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** + * ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on + * completion. Recording each thread-scoped call's compact result before returning lets adapters + * recover sent messages, IDs, counts, and error flags without depending on output passthrough. + */ +const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + if (Option.isNone(mcpSessions)) { + return yield* registration; + } + const capturingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + // html_render tracks its own path/hash recovery with publish cleanup in HtmlRender. + if (toolName === HTML_RENDER_TOOL_NAME) { + return server.addTool(options); + } + return server.addTool({ + ...options, + // Untraced: withToolSpans already opens a span per tool call. + handle: Effect.fnUntraced(function* (payload) { + const scopeOption = yield* Effect.serviceOption( + McpInvocationContext.McpInvocationContext, + ); + const thread = Option.getOrUndefined(scopeOption)?.thread; + const epoch = + thread === undefined + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + if (thread === undefined) return Effect.void; + if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) { + return Effect.void; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.void; + } + const output = + exit._tag === "Success" + ? compactT3McpToolOutput(toolName, exit.value) + : { isError: true }; + return output === undefined + ? Effect.void + : mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, { + providerSessionId: thread.providerSessionId, + epoch, + }); + }), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1300,8 +1364,10 @@ export const toolkitRegistration = , EX, ) => Layer.effectDiscard( withToolAnalytics( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolResultCapture( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( @@ -1318,7 +1384,7 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe( + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); @@ -1350,7 +1416,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); -const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); +export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 33c356af4e7e1..c1d35ace86940 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -416,6 +416,47 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); +it.effect("captures send_to_user results for providers that drop MCP outputs", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const draft = "### Status\n\nAll checks passed."; + const result = yield* server + .callTool({ name: "send_to_user", arguments: { message: draft } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(result.isError).not.toBe(true); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual( + { sentMessage: draft }, + ); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe( + undefined, + ); + + const invalid = yield* server + .callTool({ name: "send_to_user", arguments: { message: "" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + Effect.flip, + ); + expect(invalid).toMatchObject({ _tag: "InvalidParams" }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({ + isError: true, + }); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + ), + ), + ), +); + it.effect("records only failed calls of tools that hand off no work", () => { // Recording runs detached from the tool response, so the first event is awaited. const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..9924d6c831833 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,7 +13,12 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { + compactDynamicToolOutput, + htmlRenderFromToolItem, + previewRecordingIdFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -989,6 +994,329 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "recovers T3 MCP tool results across omitted outputs, replays, errors, and turn boundaries", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let promptIndex = 0; + let turn1Epoch = 0; + const instanceId = ProviderInstanceId.make("antigravity-mcp-result-test"); + const threadId = ThreadId.make("thread-antigravity-mcp-result"); + const statusUpdate = "### Current Status\n\nAll checks are passing."; + const inProgressText = "Streamed while running."; + const lateText = "Confirmed on a later completion."; + const lateErrorText = "Late explicit error."; + const unfinishedText = "Still running when turn ended."; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptIndex += 1; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const startTool = ( + toolCallId: string, + toolName: string, + rawInput: Record, + ) => + send({ + sessionUpdate: "tool_call", + toolCallId, + title: `Run mcp_t3-code_${toolName}`, + kind: "other", + status: "in_progress", + rawInput, + }); + const updateTool = ( + toolCallId: string, + status: "in_progress" | "completed" | "failed", + rawOutput?: unknown, + ) => + send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + ...(rawOutput === undefined ? {} : { rawOutput }), + }); + const recordSend = (message: string) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ); + + if (promptIndex === 2) { + // A Turn 1 handler finishing after Turn 1 closed must be rejected by epoch. + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: unfinishedText }, + { sentMessage: unfinishedText }, + { epoch: turn1Epoch }, + ); + yield* startTool("turn2-leaked-check", "send_to_user", { + message: unfinishedText, + }); + yield* updateTool("turn2-leaked-check", "completed", "Summary of turn 2"); + return { stopReason: "end_turn" as const }; + } + + turn1Epoch = yield* mcpSessions.toolResultEpoch(threadId); + + // agy 1.5.x adds toolSummary and omits output on completion, then may replay. + yield* startTool("send-empty", "send_to_user", { + message: statusUpdate, + toolSummary: "Send status update", + }); + yield* recordSend(statusUpdate); + yield* updateTool("send-empty", "completed"); + yield* updateTool("send-empty", "in_progress"); + yield* updateTool("send-empty", "completed", "Summary replay"); + + // Streaming output during in_progress still drains on completion. + yield* startTool("send-streaming", "send_to_user", { message: inProgressText }); + yield* recordSend(inProgressText); + yield* updateTool("send-streaming", "in_progress", { + sentMessage: inProgressText, + }); + yield* updateTool("send-streaming", "completed", { + sentMessage: inProgressText, + }); + yield* startTool("send-streaming-unpublished", "send_to_user", { + message: inProgressText, + }); + yield* updateTool("send-streaming-unpublished", "completed"); + + // Explicit MCP error preserves diagnostic content across summary replays. + yield* startTool("send-errored", "send_to_user", { message: "Denied" }); + yield* updateTool("send-errored", "completed", { + result: { + isError: true, + structuredContent: { sentMessage: "Denied" }, + content: [{ type: "text", text: "Denied by policy" }], + }, + }); + yield* updateTool("send-errored", "completed", "Summary of denied"); + + // Initial miss -> late explicit success or error still drains its new record. + yield* startTool("send-late", "send_to_user", { message: lateText }); + yield* updateTool("send-late", "completed"); + yield* recordSend(lateText); + yield* updateTool("send-late", "completed", { sentMessage: lateText }); + yield* startTool("send-late-unpublished", "send_to_user", { + message: lateText, + }); + yield* updateTool("send-late-unpublished", "completed"); + + yield* startTool("send-late-error", "send_to_user", { message: lateErrorText }); + yield* updateTool("send-late-error", "completed"); + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: lateErrorText }, + { isError: true }, + ); + yield* updateTool("send-late-error", "completed", { + result: { isError: true, content: [{ type: "text", text: "Denied late" }] }, + }); + yield* startTool("send-late-error-sibling", "send_to_user", { + message: lateErrorText, + }); + yield* updateTool("send-late-error-sibling", "completed"); + + // Empty-input completion that misses still recovers once a later completion brings arguments, + // and replacing arguments on the same call ID re-matches against the new arguments. + yield* startTool("send-late-args", "send_to_user", {}); + yield* recordSend("First args"); + yield* updateTool("send-late-args", "completed"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "First args" }, + }); + yield* recordSend("Second args"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "Second args" }, + rawOutput: "Summary of second", + }); + + // Bare failure without reported output must not consume a sibling call's cached result. + yield* startTool("send-bare-fail", "send_to_user", { message: "Shared ready" }); + yield* startTool("send-bare-fail-sibling", "send_to_user", { + message: "Shared ready", + }); + yield* recordSend("Shared ready"); + yield* updateTool("send-bare-fail", "failed"); + yield* updateTool("send-bare-fail-sibling", "completed"); + + // preview_recording_stop recovers its recording id. + yield* startTool("recording-stop", "preview_recording_stop", { + toolSummary: "Stop preview recording", + }); + yield* mcpSessions.recordToolResult( + threadId, + "preview_recording_stop", + {}, + { id: `${threadId}-rec-1` }, + ); + yield* updateTool("recording-stop", "completed"); + + // Unfinished call projected at turn end must not claim or leak to Turn 2. + yield* startTool("send-unfinished", "send_to_user", { + message: unfinishedText, + }); + yield* recordSend(unfinishedText); + + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-mcp-result"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + return Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + }); + const turn1Events = yield* runTurn(1); + const turn2Events = yield* runTurn(2); + const toolIn = (events: ReadonlyArray<(typeof turn1Events)[number]>, nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? event.turnItem + : undefined; + }; + const tool = (nativeId: string) => toolIn(turn1Events, nativeId); + + const sendEmptyUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-empty" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + sendEmptyUpdates.map((update) => sentMessageFromToolItem(update)), + [statusUpdate, statusUpdate], + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming")!), inProgressText); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming-unpublished")!), undefined); + const erroredUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-errored" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.strictEqual(erroredUpdates.length, 2); + for (const update of erroredUpdates) { + assert.strictEqual(compactDynamicToolOutput(update.output)?.isError, true); + assert.include(JSON.stringify(update.output), "Denied by policy"); + assert.strictEqual(sentMessageFromToolItem(update), undefined); + } + assert.strictEqual(sentMessageFromToolItem(tool("send-late")!), lateText); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-unpublished")!), undefined); + const lateErrorSibling = tool("send-late-error-sibling"); + assert.isDefined(lateErrorSibling); + assert.strictEqual(lateErrorSibling.status, "completed"); + assert.strictEqual(lateErrorSibling.output, undefined); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-args")!), "Second args"); + assert.strictEqual( + sentMessageFromToolItem(tool("send-bare-fail-sibling")!), + "Shared ready", + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-unfinished")!), undefined); + assert.strictEqual( + sentMessageFromToolItem(toolIn(turn2Events, "turn2-leaked-check")!), + undefined, + ); + assert.strictEqual( + previewRecordingIdFromToolItem(tool("recording-stop")!), + `${threadId}-rec-1`, + ); + }).pipe(Effect.provide(layerSession)), + ); }); /** diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 91a00fd60742f..33b2ecd4638c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -43,7 +43,7 @@ import { TestClock } from "effect/testing"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { htmlRenderFromToolItem, sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { @@ -1540,16 +1540,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.interrupt", { interrupted: true }), event("session.execution.interrupted", { sessionID: SESSION }), ]); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const watch = yield* watchBackgroundTurn(runtime); yield* runtime.startTurn(withLineage(thread)); yield* watch.attached; + // The child's nested T3 MCP results live under the root thread and outlive its turn. + const childResult = { message: "Child note" }; + yield* mcpSessions.recordToolResult(threadId, "send_to_user", childResult, { + sentMessage: childResult.message, + }); yield* runtime.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId, }); assert.equal((yield* watch.terminal)?.status, "interrupted"); assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - }), + assert.deepEqual(yield* mcpSessions.takeToolResult(threadId, "send_to_user", childResult), { + sentMessage: childResult.message, + }); + }).pipe(Effect.scoped), ); it.effect("stops background subagents on a user Stop", () => @@ -5321,6 +5331,188 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("shows send_to_user messages a Code Mode script sends without returning them", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const messages = ["First mid-turn note", "Second mid-turn note"]; + yield* Effect.forEach(messages, (message) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ), + ); + const tool = { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-execute-send", + }; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "execute" }), + event("session.tool.called", { ...tool, input: { code: "`; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 0f3f8519bddc7..e70be7cb9f1fc 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -755,7 +755,7 @@ describe("AssetAccess", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" })); - yield* fs.writeFileString(path.join(root, "payload.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4"); const link = path.join(root, "report.pdf"); const issue = issueAssetUrl({ @@ -772,7 +772,7 @@ describe("AssetAccess", () => { return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); }; - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); yield* fs.remove(link); @@ -783,7 +783,7 @@ describe("AssetAccess", () => { }); yield* fs.remove(link); - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect(yield* resolveIssued(issued.relativeUrl)).toBeNull(); }).pipe(Effect.provide(layerTest)), ); @@ -1807,6 +1807,51 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)("refuses a favicon link whose target is not an image", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-" }), + ); + const pictures = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-pictures-" }), + ); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "real.svg"), ""); + const resolveIssued = (relativeUrl: string) => { + const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); + }; + for (const link of [path.join(root, "favicon.svg"), path.join(pictures, "custom.svg")]) { + const issue = issueAssetUrl({ + resource: { _tag: "project-favicon", cwd: root }, + ...(link.startsWith(pictures) ? { projectFaviconPath: link } : {}), + }); + + yield* fs.symlink(path.join(root, "page.xhtml"), link); + expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "real.svg"), link); + const issued = yield* issue; + expect(yield* resolveIssued(issued.relativeUrl)).toEqual({ + kind: "file", + path: path.join(root, "real.svg"), + }); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); + // An outside icon's URL names its target, so repointing the link cannot change it. + expect(yield* resolveIssued(issued.relativeUrl)).toEqual( + link.startsWith(pictures) ? { kind: "file", path: path.join(root, "real.svg") } : null, + ); + yield* fs.remove(link); + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("ignores a client favicon path hint", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 2b8f1029ae3a3..d91975114e6eb 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -287,6 +287,8 @@ const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(functio const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* ( filePath: string, ) { + // Checked again here: a link can be repointed after its URL was issued. + if (!isProjectFaviconPath(filePath)) return null; if (!filePath.toLowerCase().endsWith(".icns")) { return { kind: "file", path: filePath } satisfies ResolvedAsset; } @@ -824,6 +826,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + // A favicon link must resolve to an image file. + if (canonicalFaviconPath && !isProjectFaviconPath(canonicalFaviconPath)) { + return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); + } claims = isExternalOverride && canonicalFaviconPath ? { diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index d7fee1a2271df..f78c4acf28d3d 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -44,7 +44,14 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { + headers: { + "set-cookie": "upstream=1", + "clear-site-data": '"*"', + "content-type": "text/html", + "content-security-policy": "script-src *", + }, + }), ); }), ); @@ -122,6 +129,11 @@ describe("device hub proxy", () => { ); expect(response.status).toBe(200); expect(await response.text()).toBe("frame"); + expect(response.headers.get("set-cookie")).toBeNull(); + expect(response.headers.get("clear-site-data")).toBeNull(); + // Opened as a page, a hub response gets an opaque origin and no script. + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect(requests).toEqual(["http://hub.test/api/devices"]); expect(finalized()).toBe(1); }); diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 9778cf084b017..b7194d1feeeb7 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -164,11 +164,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. + // Clear-Site-Data likewise applies to the origin that serves it. if ( name === "content-encoding" || name === "transfer-encoding" || name === "connection" || - name === "set-cookie" + name === "set-cookie" || + name === "clear-site-data" ) { continue; } @@ -176,6 +178,9 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( } // Long-lived MJPEG and AVCC responses must not be buffered by compression. headers["cache-control"] = "no-store, no-transform"; + // Hub responses are data and streams; none renders as a page on this origin. + headers["x-content-type-options"] = "nosniff"; + headers["content-security-policy"] = "default-src 'none'; sandbox"; const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 6e011aef39d26..2f2f6b8f85534 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -20,6 +20,7 @@ import { openMediaFile } from "./assets/MediaFile.ts"; import { injectMcpAppCsp, injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES, } from "@t3tools/shared/mcpApp"; @@ -54,7 +55,9 @@ describe("MCP app asset responses", () => { method, ), ); - const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)); + const expected = injectMcpAppDocumentBootstrap( + injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)), + ); expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( String(new TextEncoder().encode(expected).byteLength), @@ -842,7 +845,7 @@ describe("video asset byte ranges", () => { }); describe("assetResponseHeaders", () => { - it("sandboxes SVG assets", () => { + it("sandboxes SVG and other XML assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", @@ -850,6 +853,15 @@ describe("assetResponseHeaders", () => { expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty( "Content-Security-Policy", ); + for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) { + expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + ); + } + expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty( + "Content-Security-Policy", + ); }); it("serves inline attachment documents with their declared mime type", () => { expect( diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index acec877a45c55..8a31a99287e38 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -5,7 +5,11 @@ import { EnvironmentHttpApi, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; -import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; +import { + injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, + injectMcpAppThemeBootstrap, +} from "@t3tools/shared/mcpApp"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; @@ -77,6 +81,13 @@ const isSafeInlineMediaMimeType = (mimeType: string): boolean => const isSafeInlineDocumentMimeType = (mimeType: string): boolean => mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; +// XML types render as documents, so they get the same policy as SVG. +const isScriptableXmlPath = (filePath: string): boolean => + Option.match(Mime.getType(filePath), { + onNone: () => false, + onSome: (mimeType) => /(?:\/xml(?:$|-)|\+xml$)/.test(mimeType), + }); + export function downloadContentDisposition(fileName?: string): string { if (fileName === undefined) { return "attachment"; @@ -134,7 +145,7 @@ export function assetResponseHeaders( "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY, } : {}), - ...(!options?.download && lowerPath.endsWith(".svg") + ...(!options?.download && isScriptableXmlPath(lowerPath) ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; @@ -189,6 +200,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( new TextDecoder().decode(bytes), injectMcpAppThemeBootstrap, injectMcpAppCookieBootstrap, + // Applied last so it is the document's first script. + injectMcpAppDocumentBootstrap, (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); diff --git a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx index ed6c4b9261393..2ea2330f50af7 100644 --- a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx +++ b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx @@ -2,6 +2,8 @@ import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; +import { injectMcpAppDocumentBootstrap } from "@t3tools/shared/mcpApp"; + import "~/index.css"; import { act, fakeTimers, render } from "../../../test/render"; @@ -22,10 +24,29 @@ addEventListener("message", (event) => { parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized" }, "*"); `; +const sizeChanged = (height: number) => + `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`; +// What the app's frame shows after the app follows a link: another page in the same window. +// Its nested frame keeps `load`, which stops the app, from firing before its message arrives. +const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(``)}`; +// Served as the server serves an app: the document bootstrap is its first script. +const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(``); + +const asset = vi.hoisted(() => ({ html: "" })); +const setup = (html: string) => { + asset.html = html; +}; + vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: `data:text/html,${encodeURIComponent(APP_HTML)}`, + url: `data:text/html,${encodeURIComponent(asset.html)}`, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -44,6 +65,7 @@ const nextInitializedFrom = () => describe("McpAppFrame", () => { it("keeps a reopened app when the old document's second teardown finishes late", async () => { + setup(APP_HTML); const firstInitialized = nextInitializedFrom(); await using screen = await render( { expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull(); await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument(); }); + + it("ignores a page the app's frame navigated to", async () => { + setup(NAVIGATING_APP_HTML); + const element = () => ( + + ); + await using screen = await render(element()); + const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement; + const row = frame.parentElement!.parentElement!; + // The app resizes only after the host's answer reached it, so the bridge works both ways. + await expect.element(row).toHaveStyle({ height: "321px" }); + + // A tool update hands the row an equal app in a new object, which re-attaches the host. + await screen.rerender(element()); + frame.contentWindow!.postMessage("leave", "*"); + await expect + .element(screen.getByText("The Demo app left its page and was stopped")) + .toBeInTheDocument(); + expect(row.style.height).toBe("321px"); + }); }); diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index c0893c2d6f7c3..3d90a688f717c 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -38,6 +38,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { attachMcpAppDocumentLink } from "./mcpAppDocumentLink"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { @@ -269,16 +270,15 @@ export function McpAppFrame(props: { } return approved; }; - const target = () => frameRef.current?.contentWindow ?? null; const scope = () => { const { environmentId, threadId, itemId } = readLive().props; return { environmentId, input: { threadId, itemId } }; }; + const documentLink = attachMcpAppDocumentLink(frame, (data) => host.receive(data)); const host = makeMcpAppHost({ app, hostVersion: APP_VERSION, - // Opaque origins require "*"; the window reference scopes delivery to this frame. - post: (message) => target()?.postMessage(message, "*"), + post: documentLink.post, hostContext, callTool: async ({ name, arguments: args }) => { const { environmentId, input } = scope(); @@ -401,12 +401,9 @@ export function McpAppFrame(props: { }, }); hostRef.current = host; - const receive = (event: MessageEvent) => { - if (event.source !== null && event.source === target()) host.receive(event.data); - }; - window.addEventListener("message", receive); + window.addEventListener("message", documentLink.receive); return () => { - window.removeEventListener("message", receive); + window.removeEventListener("message", documentLink.receive); void host.teardown(); hostRef.current = null; frameRef.current = null; diff --git a/apps/web/src/components/chat/mcpAppDocumentLink.ts b/apps/web/src/components/chat/mcpAppDocumentLink.ts new file mode 100644 index 0000000000000..6982dd3e12a80 --- /dev/null +++ b/apps/web/src/components/chat/mcpAppDocumentLink.ts @@ -0,0 +1,67 @@ +import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp"; + +const MAX_UNCONFIRMED_MESSAGES = 256; + +interface DocumentLink { + link: MessagePort | "window" | null; + nextProbe: number; + deliver: (data: unknown) => void; + readonly unconfirmed: Map; +} + +// Kept per frame, not per host: a host that re-attaches to the same frame must not take the +// frame's next message for a first one. +const documentLinks = new WeakMap(); + +/** + * Ties the bridge to the frame's first document. A frame's window outlives its document, so the + * bridge follows the port that document's bootstrap sends first, not the window. Servers without + * the bootstrap keep the plain window bridge. + */ +export function attachMcpAppDocumentLink( + frame: HTMLIFrameElement, + deliver: (data: unknown) => void, +) { + let state = documentLinks.get(frame); + if (state === undefined) { + state = { link: null, nextProbe: 0, deliver, unconfirmed: new Map() }; + documentLinks.set(frame, state); + } + const current = state; + current.deliver = deliver; + return { + receive: (event: MessageEvent) => { + if (event.source === null || event.source !== frame.contentWindow) return; + if (current.link === null) { + const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null; + if (port !== null) { + current.link = port; + port.onmessage = (reply: MessageEvent) => { + const probe: unknown = reply.data?.alive; + if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return; + const data = current.unconfirmed.get(probe); + current.unconfirmed.delete(probe); + current.deliver(data); + }; + return; + } + current.link = "window"; + } + if (current.link === "window") { + current.deliver(event.data); + return; + } + // Only the first document can answer, so a reply proves it sent this message. + if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return; + current.unconfirmed.set(current.nextProbe, event.data); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin. + current.link.postMessage({ alive: current.nextProbe }); + current.nextProbe += 1; + }, + post: (message: unknown) => { + // Opaque origins require "*"; the window reference scopes delivery to this frame. + if (current.link === "window") frame.contentWindow?.postMessage(message, "*"); + else current.link?.postMessage({ message, origin: window.location.origin }); + }, + }; +} diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 63a2f119056c1..c0f057a0d508a 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -1,9 +1,5 @@ /* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */ -import { - decodeFilePreviewText, - filePreviewKind, - hostPreviewMimeTypeFromExtension, -} from "@t3tools/shared/filePreview"; +import { decodeFilePreviewText, filePreviewKind } from "@t3tools/shared/filePreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { ChevronLeftIcon, ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react"; import { msg, T, useGT, useMessages } from "gt-react"; @@ -29,6 +25,7 @@ import { type BinaryWorkerRequest, type BinaryWorkerResult, } from "./binaryPreviewProtocol"; +import { archiveImageUrl } from "./archiveImageUrl"; import { PreviewImage } from "./PreviewImage"; import { readBinaryPreview } from "./readBinaryPreview"; import { previewErrorText, previewFailureText } from "./previewFailureMessages"; @@ -69,15 +66,10 @@ function ArchiveFile(props: { readonly path: string; readonly bytes: Uint8Array< // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Create an object URL for the extracted image and revoke it when the entry changes or unmounts. useEffect(() => { if (kind !== "image") return; - const extension = props.path.slice(props.path.lastIndexOf(".")); - const objectUrl = URL.createObjectURL( - new Blob([props.bytes], { - type: hostPreviewMimeTypeFromExtension(extension) ?? "application/octet-stream", - }), - ); + const image = archiveImageUrl(props.path, props.bytes); // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL only after registering its cleanup. - setUrl(objectUrl); - return () => URL.revokeObjectURL(objectUrl); + setUrl(image.url); + return image.revoke; }, [props.bytes, props.path, kind]); if (kind === "image") return url ? : ; diff --git a/apps/web/src/components/files/archiveImageUrl.test.ts b/apps/web/src/components/files/archiveImageUrl.test.ts new file mode 100644 index 0000000000000..90eb11f347831 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.test.ts @@ -0,0 +1,15 @@ +import { expect, it } from "vite-plus/test"; + +import { archiveImageUrl } from "./archiveImageUrl"; + +it("shows an archived SVG from a data URL", () => { + const svg = new TextEncoder().encode(''); + for (const path of ["art/logo.svg", "LOGO.SVG"]) { + expect(archiveImageUrl(path, svg).url).toBe( + `data:image/svg+xml;base64,${btoa(String.fromCharCode(...svg))}`, + ); + } + const png = archiveImageUrl("art/logo.png", new Uint8Array([137, 80, 78, 71])); + expect(png.url).toMatch(/^blob:/); + png.revoke(); +}); diff --git a/apps/web/src/components/files/archiveImageUrl.ts b/apps/web/src/components/files/archiveImageUrl.ts new file mode 100644 index 0000000000000..bdba586d48f11 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.ts @@ -0,0 +1,20 @@ +import { hostPreviewMimeTypeFromExtension } from "@t3tools/shared/filePreview"; +import * as Base64 from "effect/encoding/Base64"; + +/** + * A URL an `` can show for an image taken out of an archive. SVG uses a data: URL, which + * has an opaque origin wherever it is opened; other types use a blob: URL. + */ +export function archiveImageUrl( + path: string, + bytes: Uint8Array, +): { readonly url: string; readonly revoke: () => void } { + const mimeType = + hostPreviewMimeTypeFromExtension(path.slice(path.lastIndexOf("."))) ?? + "application/octet-stream"; + if (mimeType === "image/svg+xml") { + return { url: `data:${mimeType};base64,${Base64.encode(bytes)}`, revoke: () => undefined }; + } + const url = URL.createObjectURL(new Blob([bytes], { type: mimeType })); + return { url, revoke: () => URL.revokeObjectURL(url) }; +} diff --git a/packages/shared/src/mcpApp.ts b/packages/shared/src/mcpApp.ts index 7c3afd221365d..4f25f4ba83317 100644 --- a/packages/shared/src/mcpApp.ts +++ b/packages/shared/src/mcpApp.ts @@ -251,6 +251,23 @@ export function injectMcpAppCookieBootstrap(html: string): string { return `${prefix}${bootstrap}${html.slice(prefix.length)}`; } +export const MCP_APP_DOCUMENT_MESSAGE = "t3-mcp-app-document"; + +/** + * Binds the host bridge to this document rather than to the frame's window, which outlives it. + * The document's first script hands the host a private port: the host answers only over it, and + * acts on a message only once this document confirms it is alive. + */ +export function injectMcpAppDocumentBootstrap(html: string): string { + const bootstrap = ``; + // Preserve captured CSP ahead of executable code, including this bootstrap. + const prefix = + /^(?:\uFEFF?\s*]*>\s*)?(?:)?/i.exec( + html, + )![0]; + return `${prefix}${bootstrap}${html.slice(prefix.length)}`; +} + export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string { const features: Array = []; if (permissions?.camera) features.push("camera"); From ae3352e0512bbd2aa609f7176e1e547f670265f4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 17:40:58 -0600 Subject: [PATCH 200/288] fix(server): checkpoints work when a Git path ends in a space (#41725) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriver.test.ts | 45 ++++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 8 ++--- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 78a436a1424e4..d2eed8bad23a7 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -2098,6 +2098,51 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "checkpoint capture keeps whitespace at the end of Git paths", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-edge-space-capture-", + }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const git = (cwd: string, args: ReadonlyArray) => + driver.execute({ + operation: "test", + cwd, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + }); + const library = path.join(parent, "library"); + yield* fileSystem.makeDirectory(library); + yield* git(library, ["init"]); + yield* git(library, ["commit", "--allow-empty", "-m", "initial"]); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/edge-space"); + // The newline name takes the per-path fallback; the other takes the one-spawn answer. + for (const name of ["repo ", "multi\nline "]) { + const cwd = path.join(parent, name); + yield* fileSystem.makeDirectory(cwd); + yield* git(cwd, ["init", `--separate-git-dir=${path.join(parent, `${name.trim()} git `)}`]); + yield* git(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", library, "lib"]); + yield* git(cwd, ["commit", "-m", "initial"]); + yield* fileSystem.writeFileString(path.join(cwd, "dirty.txt"), "pending\n"); + yield* fileSystem.writeFileString(path.join(cwd, "lib", "dirty.txt"), "nested\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.strictEqual( + (yield* git(cwd, ["show", `${checkpointRef}:dirty.txt`])).stdout, + "pending\n", + ); + assert.strictEqual( + (yield* git(path.join(cwd, "lib"), ["show", `${checkpointRef}:dirty.txt`])).stdout, + "nested\n", + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("restores empty checkpoints without changing paths outside the workspace", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 56b4b44d0156e..bba371104af14 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -992,7 +992,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd, args: ["rev-parse", "--git-common-dir"], }); - const gitCommonDir = result.stdout.trim(); + const gitCommonDir = result.stdout.replace(/\n$/, ""); if (path.isAbsolute(gitCommonDir)) return gitCommonDir; const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return path.resolve(physicalCwd, gitCommonDir); @@ -1025,9 +1025,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const [gitCommonDir = "", indexPath = "", topLevel = "", prefix = "", head = ""] = lines; if (headChecked && lines.length === (headExists ? 6 : 5) && lines.at(-1) === "") { return { - gitCommonDir: gitCommonDir.trim(), - indexPath: indexPath.trim(), - topLevel: topLevel.trim(), + gitCommonDir, + indexPath, + topLevel, prefix, headExists, head: headExists ? head : undefined, From b654fc27baac7bb831c3d21820c263e8667687a7 Mon Sep 17 00:00:00 2001 From: daTuzzo <123642701+daTuzzo@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:41:11 +0200 Subject: [PATCH 201/288] fix(server): automatic port selection checks the address the server binds (#41730) Co-authored-by: Julius Marminge --- apps/server/src/cli/automaticPort.test.ts | 6 +++-- apps/server/src/cli/automaticPort.ts | 10 ++++--- apps/server/src/cli/config.test.ts | 17 ++++++++---- apps/server/src/cli/config.ts | 33 ++++++++++++----------- packages/shared/src/Net.test.ts | 23 ++++++++++++++++ packages/shared/src/Net.ts | 23 +++++++++++++--- packages/shared/src/hostClassification.ts | 4 +++ 7 files changed, 86 insertions(+), 30 deletions(-) diff --git a/apps/server/src/cli/automaticPort.test.ts b/apps/server/src/cli/automaticPort.test.ts index 1f7805569744f..b39c94720cbc8 100644 --- a/apps/server/src/cli/automaticPort.test.ts +++ b/apps/server/src/cli/automaticPort.test.ts @@ -34,6 +34,7 @@ interface Scenario { readonly tcpv6ExitCode?: number; readonly wslpathMissing?: boolean; readonly reservedPorts?: ReadonlyArray; + readonly host?: string; } const select = (scenario: Scenario) => { @@ -92,7 +93,7 @@ const select = (scenario: Scenario) => { ); return Effect.gen(function* () { const selectAutomaticPort = yield* AutomaticPort.make; - const port = yield* selectAutomaticPort(3773); + const port = yield* selectAutomaticPort(3773, scenario.host); return { port, commands }; }).pipe(Effect.provide(layer)); }; @@ -149,12 +150,13 @@ describe("automatic port selection", () => { }), ); - it.effect("never queries Windows outside WSL", () => + it.effect("never queries Windows outside WSL or for a specific bind address", () => Effect.gen(function* () { for (const scenario of [ { kernelRelease: "6.8.0-45-generic\n" }, // macOS and Windows have no kernel release file. {}, + { kernelRelease: WSL_KERNEL, windowsPorts: [3773], host: "100.64.0.7" }, ] satisfies ReadonlyArray) { const result = yield* select(scenario); expect(result.port).toBe(3773); diff --git a/apps/server/src/cli/automaticPort.ts b/apps/server/src/cli/automaticPort.ts index 354de65d2519b..70e8bad6c8b05 100644 --- a/apps/server/src/cli/automaticPort.ts +++ b/apps/server/src/cli/automaticPort.ts @@ -1,3 +1,4 @@ +import { listensOnLoopback } from "@t3tools/shared/hostClassification"; import * as NetService from "@t3tools/shared/Net"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -44,14 +45,17 @@ export const make = Effect.gen(function* () { return new Set(listeners.map((listener) => listener.port)); }).pipe(Effect.orElseSucceed(() => null)); - return Effect.fn("automaticPort.select")(function* (preferred: number) { - if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred); + return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) { + // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address. + if (!listensOnLoopback(host) || !(yield* isWsl)) { + return yield* net.findAvailablePort(preferred, host); + } const windows = yield* readWindowsHostListeners; if (windows === null) { yield* Effect.logWarning( "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.", ); - return yield* net.findAvailablePort(preferred); + return yield* net.findAvailablePort(preferred, host); } if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) { return preferred; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 9d1ffb5c1298a..bbd13c1132953 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -872,15 +872,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const baseDir = yield* FileSystem.FileSystem.pipe( Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })), ); - const selected: number[] = []; - const selectAutomaticPort = (preferred: number) => + const selected: Array = []; + const selectAutomaticPort = (preferred: number, host: string | undefined) => Effect.sync(() => { - selected.push(preferred); + selected.push([preferred, host]); return 50_123; }); const resolvePort = (flags: { readonly mode?: Option.Option<"web" | "desktop">; readonly port: Option.Option; + readonly host?: Option.Option; }) => resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), { selectAutomaticPort, @@ -895,12 +896,18 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); expect(yield* resolvePort({ port: Option.none() })).toBe(50_123); - expect(selected).toEqual([3773]); + expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe( + 50_123, + ); + expect(selected).toEqual([ + [3773, undefined], + [3773, "100.64.0.7"], + ]); expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788); expect( yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }), ).toBe(3773); - expect(selected).toEqual([3773]); + expect(selected).toHaveLength(2); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a62682772bcce..87ff2588c5e34 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -271,6 +271,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct readonly rejectRunningServer?: boolean; readonly selectAutomaticPort?: ( preferred: number, + host: string | undefined, ) => Effect.Effect; }, ) { @@ -310,22 +311,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct () => "web", ); - const port = yield* Option.match( - resolveOptionPrecedence( - normalizedFlags.port, - Option.fromUndefinedOr(env.port), - Option.fromUndefinedOr(bootstrap?.port), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(ServerConfig.DEFAULT_PORT); - } - return selectAutomaticPort(ServerConfig.DEFAULT_PORT); - }, - }, - ); const devUrl = Option.getOrElse( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, @@ -451,6 +436,22 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const host = Option.getOrElse(explicitHost, () => privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined, ); + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + Option.fromUndefinedOr(bootstrap?.port), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(ServerConfig.DEFAULT_PORT); + } + return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host); + }, + }, + ); const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); const otel = yield* OtelEnvironment.load; diff --git a/packages/shared/src/Net.test.ts b/packages/shared/src/Net.test.ts index d4b00f5f957da..ca86a5db4a46f 100644 --- a/packages/shared/src/Net.test.ts +++ b/packages/shared/src/Net.test.ts @@ -1,4 +1,5 @@ import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -44,6 +45,10 @@ const openServer = (host?: string): Effect.Effect entries ?? []) + .find((entry) => entry.family === "IPv4" && !entry.internal)?.address; + it.layer(NetService.layer)("NetService", (it) => { describe("Net helpers", () => { it.effect.each(["EAFNOSUPPORT", "EADDRNOTAVAIL"])( @@ -99,9 +104,27 @@ it.layer(NetService.layer)("NetService", (it) => { const resolved = yield* net.findAvailablePort(preferred); assert.ok(resolved > 0); assert.notEqual(resolved, preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, ownIpv4), preferred); }), closeServer, ), ); + + it.effect.skipIf(ownIpv4 === undefined)( + "findAvailablePort keeps a port that only loopback uses for a specific bind address", + () => + Effect.acquireUseRelease( + openServer("127.0.0.1"), + (server) => + Effect.gen(function* () { + const net = yield* NetService.NetService; + const preferred = getPort(server); + + assert.equal(yield* net.findAvailablePort(preferred, ownIpv4), preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, "0.0.0.0"), preferred); + }), + closeServer, + ), + ); }); }); diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.ts index 40ef669db4e64..5a8f3214f177c 100644 --- a/packages/shared/src/Net.ts +++ b/packages/shared/src/Net.ts @@ -6,6 +6,8 @@ import * as Context from "effect/Context"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import { listensOnLoopback } from "./hostClassification.ts"; + export class NetError extends Schema.TaggedError()("NetError", { message: Schema.String, cause: Schema.optional(Schema.Defect()), @@ -35,7 +37,7 @@ export interface NetServiceShape { readonly reserveLoopbackPort: (host?: string) => Effect.Effect; - readonly findAvailablePort: (preferred: number) => Effect.Effect; + readonly findAvailablePort: (preferred: number, host?: string) => Effect.Effect; } export class NetService extends Context.Service()( @@ -130,6 +132,19 @@ export const make = () => { ); }); + const isPortAvailableForHost = Effect.fn("Net.isPortAvailableForHost")(function* ( + port: number, + host: string | undefined, + ): Effect.fn.Return { + if (host === undefined || listensOnLoopback(host)) { + return yield* isPortAvailableOnLoopback(port); + } + if (yield* hasListenerOnHost(port, host)) { + return false; + } + return yield* canListenOnHost(port, host); + }); + const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect => Effect.callback((resume) => { const probe = NodeNet.createServer(); @@ -167,11 +182,11 @@ export const make = () => { isPortAvailableOnLoopback, hasListenerOnHost, reserveLoopbackPort, - findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred) { - if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) { + findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred, host) { + if (preferred > 0 && (yield* isPortAvailableForHost(preferred, host))) { return preferred; } - return yield* reserveLoopbackPort(); + return yield* reserveLoopbackPort(listensOnLoopback(host) ? undefined : host); }), } satisfies NetServiceShape; }; diff --git a/packages/shared/src/hostClassification.ts b/packages/shared/src/hostClassification.ts index b10b226ec35c7..a9951a869d332 100644 --- a/packages/shared/src/hostClassification.ts +++ b/packages/shared/src/hostClassification.ts @@ -179,5 +179,9 @@ export const isPublicFaviconHost = (host: string): boolean => { export const isWildcardHost = (host: string | undefined): boolean => host === "0.0.0.0" || host === "::" || host === "[::]"; +/** An unset, loopback, or wildcard bind host shares the port that `localhost` clients reach. */ +export const listensOnLoopback = (host: string | undefined): boolean => + host === undefined || host === "" || isWildcardHost(host) || isLocalLoopbackHost(host); + export const formatHostForUrl = (host: string): string => host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; From 8217726c1068751b1951058cf1b185c1091e687a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:42:07 -0800 Subject: [PATCH 202/288] fix(server): cut-off checkpoint captures no longer strand Git LFS temp files (#41697) --- apps/server/src/vcs/GitVcsDriver.test.ts | 181 +++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 68 +++++++++ 2 files changed, 249 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index d2eed8bad23a7..9ef6c1e7a9324 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -369,6 +369,187 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each(["interrupt", "timeout"] as const)( + "checkpoint staging $0 removes the Git LFS temp files its clean filter wrote", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const lfsTmp = path.join(cwd, ".git/lfs/tmp"); + yield* fs.makeDirectory(lfsTmp, { recursive: true }); + const otherOperation = path.join(lfsTmp, "owned-by-another-git-lfs"); + yield* fs.writeFileString(otherOperation, "another git-lfs process is hashing this"); + + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + // Like git-lfs clean: copy the content into /tmp while hashing, and only + // move or remove that copy once hashing finishes. A killed filter strands it. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, Buffer.alloc(1024 * 1024));", + `const s = require('node:net').connect(${address.port}, '127.0.0.1');`, + "s.resume(); process.stdin.resume();", + "s.on('close', () => process.exit(0));", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.promise(() => connected.promise); + const laterOperation = path.join(lfsTmp, "started-during-capture"); + yield* fs.writeFileString(laterOperation, "another git-lfs process started later"); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + + assert.sameMembers(yield* fs.readDirectory(lfsTmp), [ + "owned-by-another-git-lfs", + "started-during-capture", + ]); + assert.strictEqual( + yield* fs.readFileString(otherOperation), + "another git-lfs process is hashing this", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint staging moves Git LFS objects its clean filter wrote into LFS storage", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // Like git-lfs clean: hash through /tmp, then move the copy into objects. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "const content = fs.readFileSync(0);", + "const oid = require('node:crypto').createHash('sha256').update(content).digest('hex');", + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "const dir = storage + '/objects/' + oid.slice(0, 2) + '/' + oid.slice(2, 4);", + "fs.mkdirSync(dir, { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, content);", + "fs.renameSync(storage + '/tmp/' + process.pid, dir + '/' + oid);", + "process.stdout.write('oid sha256:' + oid + '\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + const pointer = yield* git(["show", `${checkpointRef}:weights.npz`]); + const oid = pointer.stdout.trim().slice("oid sha256:".length); + assert.strictEqual( + yield* fs.readFileString( + path.join(cwd, ".git/lfs/objects", oid.slice(0, 2), oid.slice(2, 4), oid), + ), + "large untracked data\n", + ); + assert.isFalse(yield* fs.exists(path.join(cwd, ".git/lfs/tmp"))); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture fails instead of dropping Git LFS objects it cannot list", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // A file where git-lfs keeps its objects makes the store unreadable without being absent. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.readFileSync(0);", + "fs.mkdirSync(storage, { recursive: true });", + "fs.writeFileSync(storage + '/objects', 'not a directory');", + "process.stdout.write('pointer\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const result = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit); + + const error = Exit.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + const ref = yield* driver.execute({ + operation: "checkpoint-test", + cwd, + args: ["rev-parse", "--verify", "--quiet", checkpointRef], + allowNonZeroExit: true, + }); + assert.strictEqual(ref.exitCode, 1); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index bba371104af14..551c863510423 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1259,6 +1259,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // git-lfs's clean filter copies each file into /tmp while hashing it and strands + // that copy when killed. Give it storage that is removed with the capture's private objects. + const privateLfs = path.join(privateObjects, "lfs"); + const publishLfsObjects = Effect.gen(function* () { + const source = path.join(privateLfs, "objects"); + const objects = (yield* fileSystem.readDirectory(source, { recursive: true }).pipe( + // Absent when no file went through the filter; any other failure must stop publication. + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "publish", + cause, + }), + ), + )).filter((entry) => /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/.test(entry)); + if (objects.length === 0) return; + const configured = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + // git-lfs resolves a relative lfs.storage against the common Git directory. + const storage = path.resolve(gitCommonDir, configured.stdout.trim() || "lfs"); + yield* Effect.forEach( + objects, + (entry) => + Effect.gen(function* () { + const from = path.join(source, entry); + const to = path.join(storage, "objects", entry); + if (yield* fileSystem.exists(to)) return; + yield* fileSystem.makeDirectory(path.dirname(to), { recursive: true }); + // Identical oids are interchangeable, so losing a race to another writer is fine. + // lfs.storage may be on another volume, where only a copy can move the object. + const partial = `${to}.${indexId}`; + yield* fileSystem.rename(from, to).pipe( + Effect.catch((cause) => + Effect.flatMap(fileSystem.exists(to), (exists) => + exists + ? Effect.void + : fileSystem.copyFile(from, partial).pipe( + Effect.andThen(fileSystem.rename(partial, to)), + Effect.ensuring( + fileSystem.remove(partial, { force: true }).pipe(Effect.ignore), + ), + Effect.mapError(() => cause), + ), + ), + ), + ); + }), + { concurrency: 16, discard: true }, + ).pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + }); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1272,6 +1337,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + // Any command on the scratch index can run the clean filter, not just add. + ...VcsProcess.gitConfigEnv(hostEnv, "lfs.storage", privateLfs, hostPlatform), }; const cleanupTempIndex = Effect.forEach( @@ -1791,6 +1858,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + yield* publishLfsObjects; // Git writers have exited; bound publication by fanout directory. yield* fileSystem.readDirectory(privateObjects).pipe( Effect.flatMap((directories) => From 5ab8dc4bfcc6568786a46abec867183e6b8442d4 Mon Sep 17 00:00:00 2001 From: Dibas <81339759+dibas-np@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:28:36 +0545 Subject: [PATCH 203/288] fix(mobile): show every image when Markdown puts one per line (#30280) Co-authored-by: Julius Marminge --- apps/mobile/src/lib/markdownDocument.ts | 35 ++++++++++++++++++++++-- apps/mobile/src/lib/markdownHtml.test.ts | 25 +++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index b44b96fca49b8..c11d00bc9aae0 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -498,13 +498,44 @@ function markdownWithWindowsPathDestinations(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference"; +const isSpace = (node: MarkdownNode) => + node.type === "break" || (node.type === "text" && node.value.trim() === ""); + +// Native Markdown sizes an image as a block only when it is its paragraph's only child. +function markdownWithImageParagraphs(markdown: string): string { + // Skips the extra parse unless a line ending sits between two images. + if (!/[\])][ \t]*\\?(?:\r\n?|\n)[ \t]*!\[/.test(markdown)) return markdown; + const edits: MarkdownEdit[] = []; + for (const block of parser.parse(markdown).children) { + if ( + block.type !== "paragraph" || + !block.children.every((child) => isImage(child) || isSpace(child)) + ) + continue; + const images = block.children.filter(isImage); + for (const [index, image] of images.slice(1).entries()) { + const start = images[index]!.position?.end.offset; + const end = image.position?.start.offset; + if (start === undefined || end === undefined) continue; + const ending = /\r\n?|\n/.exec(markdown.slice(start, end)); + if (ending) edits.push({ start, end, content: ending[0].repeat(2) }); + } + } + return applyMarkdownEdits(markdown, edits); +} + // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. -export function markdownForNativeParsing(markdown: string): string { +function normalizedMarkdown(markdown: string): string { return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); } +export function markdownForNativeParsing(markdown: string): string { + return markdownWithImageParagraphs(normalizedMarkdown(markdown)); +} + export function parseMarkdownDocument(markdown: string): Root { - return parser.parse(markdownForNativeParsing(markdown)); + return parser.parse(normalizedMarkdown(markdown)); } export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 64c5d02df3532..6cce7f84b475c 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + markdownForNativeParsing, markdownForNativeRendering, markdownHtmlContent, markdownWithHtml, @@ -303,6 +304,30 @@ describe("file embeds in native thread and file Markdown", () => { } }); + it("gives each image on its own line its own native paragraph", async () => { + const images = + "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]"; + const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`; + const paragraphs = ( + await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX)) + ).children?.map((block) => block.children?.map((child) => child.type).join(" ")); + expect(paragraphs).toEqual([ + "Text", + "Image", + "Image", + "Image", + "Image Text Image", + "Image", + "Text", + ]); + expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe( + "![a](./a.png)\r\n\r\n![b](./b.png)", + ); + expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe( + "![a](./a.png)\r\r![b](./b.png)", + ); + }); + it("retains standalone audio players and image/video embeds in threads", () => { const source = "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)"; From 0d6fe2141abe62de48d5b836d4ff8b26f37308b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:44:06 -0800 Subject: [PATCH 204/288] fix(server): mode limits follow the turn a message joins (#41746) Co-authored-by: Claude Fable 5.2 --- .../src/mcp/OrchestratorMcpService.test.ts | 56 ++++- apps/server/src/mcp/OrchestratorMcpService.ts | 56 +++-- .../src/orchestration-v2/Orchestrator.ts | 94 ++++++-- .../ProviderTurnStartService.test.ts | 2 + .../ProviderTurnStartService.ts | 4 + .../SteeringCompletion.integration.test.ts | 221 ++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 10 +- docs/user/cursor.md | 4 +- packages/contracts/src/orchestrationV2.ts | 4 + .../src/server/adapter.test.ts | 20 +- .../provider-cursor/src/server/adapter.ts | 34 ++- .../src/server/workspaceMcpServers.ts | 4 +- 12 files changed, 456 insertions(+), 53 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 551a84109cfa2..c99f9b0a6e1ad 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3950,6 +3950,8 @@ describe("OrchestratorMcpService provider resolution", () => { boundThread: OrchestrationV2ThreadShell | null, upserted: Ref.Ref, saved: ScheduledTask = tasks[0]!, + /** Stores each keyed create under the id its key derives, as the real service does. */ + created?: Ref.Ref>, ) => OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -3984,9 +3986,24 @@ describe("OrchestratorMcpService provider resolution", () => { Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ - list: () => Effect.succeed({ tasks }), - upsert: () => - Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), + list: () => + created === undefined + ? Effect.succeed({ tasks }) + : Ref.get(created).pipe(Effect.map((stored) => ({ tasks: stored }))), + upsert: (input) => + Ref.update(upserted, (count) => count + 1).pipe( + Effect.andThen( + created === undefined || input.commandId === undefined + ? Effect.void + : Ref.set(created, [ + { + ...saved, + id: ScheduledTaskService.scheduledTaskIdForCommand(input.commandId), + }, + ]), + ), + Effect.as({ task: saved }), + ), }), ), ), @@ -4084,6 +4101,39 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "refuses to replay a creation over a task whose thread now runs above the caller", + () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const created = yield* Ref.make>([]); + const bound = task({ threadId: boundThreadId }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + [bound], + liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), + upserted, + bound, + created, + ), + ), + ); + const create = (prompt: string) => + mcp.scheduleTask(supervisedClient, { + projectId, + prompt, + schedule: { type: "webhook" }, + freshSession: true, + clientRequestId: "nightly", + }); + yield* create("Check the build"); + const error = yield* create("Something else").pipe(Effect.flip); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.equal(yield* Ref.get(upserted), 1); + }), + ); + it.effect("reports a saved task even when its bound thread cannot be read", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8b58504247ba9..825094d4027e0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2369,6 +2369,21 @@ const make = Effect.gen(function* () { }, ); + const requireScheduledTaskWithinLimits = Effect.fn( + "OrchestratorMcpService.requireScheduledTaskWithinLimits", + )(function* ( + task: ScheduledTask, + limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, + ) { + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + }); + /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above @@ -2392,10 +2407,7 @@ const make = Effect.gen(function* () { if (task === undefined) { return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } + yield* requireScheduledTaskWithinLimits(task, limits); return task; }); @@ -2423,6 +2435,16 @@ const make = Effect.gen(function* () { .slice(0, 80) .replace(/[\uD800-\uDBFF]$/, ""); const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task"); + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + const commandId = + input.clientRequestId === undefined + ? undefined + : stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", + }); const upsertInput: ScheduledTaskUpsertInput = { title, prompt: input.prompt, @@ -2441,18 +2463,22 @@ const make = Effect.gen(function* () { interactionMode: limits.interactionMode, createdBy: "agent", creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), - }), + ...(commandId === undefined ? {} : { commandId }), }; + // A replayed key rewrites the task it created, which its user may since have raised or + // rebound: that is an edit of the task as it now stands. + if (commandId !== undefined) { + const replayedId = ScheduledTaskService.scheduledTaskIdForCommand(commandId); + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const replayed = tasks.find((candidate) => candidate.id === replayedId); + if (replayed !== undefined) yield* requireScheduledTaskWithinLimits(replayed, limits); + } const { task } = yield* scheduledTasks .upsert(upsertInput) .pipe( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8547084085e6b..7dc93dc5c196e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6018,6 +6018,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + // A turn keeps the modes it started with, so a thread lowered since can hold a broader one. + // A turn that recorded none is taken as unrestricted. + const turnStartedModes = ( + attempts: ReadonlyArray, + run: OrchestrationV2Run | undefined, + ) => + attempts.find((attempt) => attempt.id === run?.activeAttemptId)?.startedModes ?? { + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + }; + + // A parked steer is delivered later by the server, without the caller's limit, into a turn + // whose modes are not recorded yet. Only a caller allowed any turn may park or rewrite one. + const limitForbidsParkedSteer = Effect.gen(function* () { + const limit = narrowToCeiling(yield* DispatchModeLimit, runtimeModeCeiling); + return ( + limit !== undefined && + exceededDispatchModeLimit(limit, { + runtimeMode: "full-access", + interactionMode: "default", + }) !== undefined + ); + }); + const refuseAboveDispatchModeLimit = Effect.fn("orchestrationV2.dispatch.refuseAboveModeLimit")( function* ( command: OrchestrationV2ServerCommand, @@ -6694,6 +6718,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if (steeringPolicy === "active_steering") { + yield* refuseAboveDispatchModeLimit( + input.command, + input.command.threadId, + turnStartedModes(input.projection.attempts, targetRun), + ); const instanceChanged = input.projection.thread.providerInstanceId !== input.modelSelection.instanceId; // Only a user's steer carries the picker's selection; the adapter applies it to the live turn. @@ -7960,21 +7989,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { - const adapter = yield* providerAdapters - .get(target.providerInstanceId) - .pipe(mapDispatchError(command)); - const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); - yield* commandPolicy - .decideSteeringExecution({ - commandId: command.commandId, - threadId: command.threadId, - providerInstanceId: target.providerInstanceId, - capabilities, - }) - .pipe(mapDispatchError(command)); - yield* ensureSteeringMessage(command, command); - steerWhenReadyRunId = target.id; - dispatchMode = { type: "queue_after_active" }; + // Such a caller's message waits for its own turn instead. + if (yield* limitForbidsParkedSteer) { + dispatchMode = { type: "queue_after_active" }; + } else { + const adapter = yield* providerAdapters + .get(target.providerInstanceId) + .pipe(mapDispatchError(command)); + const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); + yield* commandPolicy + .decideSteeringExecution({ + commandId: command.commandId, + threadId: command.threadId, + providerInstanceId: target.providerInstanceId, + capabilities, + }) + .pipe(mapDispatchError(command)); + yield* ensureSteeringMessage(command, command); + steerWhenReadyRunId = target.id; + dispatchMode = { type: "queue_after_active" }; + } } } if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { @@ -11577,6 +11611,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runtimeRequest.responseCapability.type === "live" ? runtimeRequest.responseCapability.providerSessionId : null; + if (providerSessionId !== null && (yield* DispatchModeLimit) !== undefined) { + // The answer goes into the turn that asked, which keeps the modes it started with. + const live = yield* projectionStore + .getThreadRecords(command.threadId, ["runs", "attempts"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + yield* refuseAboveDispatchModeLimit( + command, + command.threadId, + turnStartedModes( + live.attempts, + live.runs.find((run) => run.id === context.node?.runId), + ), + ); + } const providerSession = context.session; if (providerSessionId !== null && providerSession === undefined) { return yield* new OrchestratorDispatchError({ @@ -12171,6 +12223,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { + if (yield* limitForbidsParkedSteer) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The current turn is not running yet. Try again once it is.", + }); + } yield* ensureSteeringMessage(command, queuedMessage); const adapter = yield* providerAdapters .get(target.providerInstanceId) @@ -12576,10 +12635,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A command cannot steer, so an edit into one keeps it queued where it is. if ( queuedRun.steerWhenReadyRunId !== undefined && - isSlashCommand({ + (isSlashCommand({ text: command.text, attachments: command.attachments ?? queuedMessage.attachments, - }) + }) || + (yield* limitForbidsParkedSteer)) ) { const { steerWhenReadyRunId: _, ...queued } = queuedRun; yield* emitEvent({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index ef9bd2bb32712..bcb75e097a5bb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -582,6 +582,8 @@ function makeLocalCommandHarness(input: { id: threadId, activeProviderThreadId: providerThreadId, projectId: ProjectId.make("project-native-account-command"), + runtimeMode: "full-access", + interactionMode: "default", branch: input.worktreePath === undefined ? null : "feature/restore", worktreePath: input.worktreePath ?? null, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 1cb77e387f950..e66506fa31f8c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1959,6 +1959,10 @@ export const layer: Layer.Layer< : { nativeThreadId: runningProviderThread.nativeThreadRef.nativeId }), status: "running", startedAt: now, + startedModes: { + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + }, }; const runningRootNode: OrchestrationV2ExecutionNode = { ...rootNode, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 4a665211ef68b..7798a7e00e267 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -14,6 +14,7 @@ import { ProviderInstanceId, ProviderThreadId, ProviderTurnId, + RuntimeRequestId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ScheduledTaskId, ThreadId, @@ -34,6 +35,7 @@ import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { DispatchModeLimit } from "./DispatchModeLimit.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; @@ -512,6 +514,8 @@ const composerSelection = { options: [...runSelection.options, { id: "fastMode", value: false }], }; +const supervised = { runtimeMode: "approval-required", interactionMode: "default" } as const; + const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* ( name: string, canRestart = false, @@ -1940,6 +1944,223 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it" }), ); +it.effect( + "refuses a limited caller's steer into a turn started before its thread was lowered", + () => + Effect.gen(function* () { + const { steered, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("steer-above-limit"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Codex keeps its session, and its running turn the full-access policy it started with. + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const steer = { + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "follow up", + attachments: [], + dispatchMode: { type: "start_immediately" }, + deliveryIntent: "steer", + createdBy: "agent", + creationSource: "mcp", + } as const; + const refused = yield* orchestrator + .dispatch(steer) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + yield* worker.drain(); + assert.deepEqual(steered, []); + + // The refusal records nothing, and a caller without the limit still reaches the turn. + yield* orchestrator.dispatch(steer); + yield* worker.drain(); + assert.lengthOf(steered, 1); + + // The turn's own record decides: one that started within the limit takes the steer. + const attempt = (yield* orchestrator.getThreadProjection(threadId)).attempts[0]!; + assert.deepEqual(attempt.startedModes, { + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("started-supervised"), + type: "run-attempt.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...attempt, startedModes: supervised }, + }, + ], + }); + yield* orchestrator + .dispatch({ + ...steer, + commandId: CommandId.make("steer-within"), + messageId: MessageId.make("message:steer-within"), + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + yield* worker.drain(); + assert.lengthOf(steered, 2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("queues a limited caller's steer into a turn that is not running yet", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("steer-not-ready"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + const steer = (name: string) => + ({ + type: "message.dispatch", + commandId: CommandId.make(name), + threadId, + messageId: MessageId.make(`message:${name}`), + text: "follow up", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }) as const; + const queuedBy = Effect.fn("queuedBy")(function* (name: string) { + return (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make(`message:${name}`), + )!; + }); + // Every MCP caller carries a limit; one at full access parks its steer like the owner. + yield* orchestrator.dispatch(steer("parked")).pipe( + Effect.provideService(DispatchModeLimit, { + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + const parked = yield* queuedBy("parked"); + assert.equal(parked.steerWhenReadyRunId, started[0]!.runId); + + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + // A parked steer is delivered by the server itself, which carries no caller limit. + yield* orchestrator + .dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit-parked"), + threadId, + runId: parked.id, + text: "rewritten", + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + assert.isUndefined((yield* queuedBy("parked")).steerWhenReadyRunId); + + yield* orchestrator + .dispatch(steer("steer")) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + const queued = yield* queuedBy("steer"); + assert.isUndefined(queued.steerWhenReadyRunId); + + yield* orchestrator + .dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queued.id, + targetRunId: started[0]!.runId, + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + const kept = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === queued.id, + )!; + assert.equal(kept.status, "queued"); + assert.isUndefined(kept.steerWhenReadyRunId); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("refuses a limited caller's answer to a turn started above its limit", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("answer-above"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const now = yield* DateTime.now; + const requestId = RuntimeRequestId.make("request:question"); + const session = (yield* orchestrator.getThreadProjection(threadId)).providerSessions[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("question"), + type: "runtime-request.updated", + threadId, + occurredAt: now, + payload: { + id: requestId, + nodeId: started[0]!.rootNodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status: "pending", + responseCapability: { type: "live", providerSessionId: session.id }, + createdAt: now, + resolvedAt: null, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const respond = { + type: "runtime-request.respond", + commandId: CommandId.make("respond"), + threadId, + requestId, + decision: "accept", + } as const; + const refused = yield* orchestrator + .dispatch(respond) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + + yield* orchestrator.dispatch(respond); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).runtimeRequests[0]?.status, + "resolved", + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #39404 a later agent message steers ahead of one queued behind /compact it.effect("delivers agent messages queued behind /compact before a later one steers", () => Effect.gen(function* () { diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 3db6f783f649a..488852884f69e 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -81,6 +81,10 @@ import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookF import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts"; export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; + +/** The task a create carrying this idempotency key writes, and rewrites when the key is replayed. */ +export const scheduledTaskIdForCommand = (commandId: CommandId) => + ScheduledTaskId.make(`scheduled-task:${commandId}`); const isScheduledTaskError = Schema.is(ScheduledTaskError); const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError); const PROMPT_TOO_LONG = "The filled-in prompt is too long."; @@ -1480,9 +1484,9 @@ export const layer = Layer.effect( : null; const id = input.id ?? - ScheduledTaskId.make( - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, - ); + (input.commandId + ? scheduledTaskIdForCommand(input.commandId) + : ScheduledTaskId.make(`scheduled-task:${uuid}`)); // Look up by the *resolved* id so idempotent creates (commandId replays) // keep their run history, and so real load failures propagate instead // of silently resetting an existing row. diff --git a/docs/user/cursor.md b/docs/user/cursor.md index f10ca24fb596f..f78ccf343d0cb 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -17,7 +17,9 @@ not expose yet. Custom Cursor MCP servers and plugins are not configured in T3 Code. They load from the environment machine's Cursor config when the agent opens: project `.cursor/mcp.json`, user `~/.cursor/mcp.json`, -and installed plugins under `~/.cursor/plugins`. Plugin tools +and installed plugins under `~/.cursor/plugins`. A project's own Cursor config, including its +`.cursor/mcp.json`, loads only in **Full access**; in the other +[permission modes](./permission-modes.md) a checkout cannot start MCP servers. Plugin tools can appear without a login; OAuth MCP servers still need credentials. Run `agent mcp login ` with the cwd set to the T3 project root (tokens land in `~/.cursor/projects//mcp-auth.json`). Cursor desktop Connections auth does not write diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8843d8cacf805..dfde87c009f66 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -897,6 +897,10 @@ export const OrchestrationV2RunAttempt = Schema.Struct({ ]), startedAt: Schema.NullOr(Schema.DateTimeUtc), completedAt: Schema.NullOr(Schema.DateTimeUtc), + /** The thread's modes when this attempt's turn started. A later change reaches only the next turn. */ + startedModes: Schema.optional( + Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }), + ), }); export type OrchestrationV2RunAttempt = typeof OrchestrationV2RunAttempt.Type; diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 4e687ed2b9c9e..90db987cf2c99 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -3275,7 +3275,7 @@ describe("CursorAdapterV2", () => { const workspace = path.join(scratch, "workspace"); const home = path.join(scratch, "home"); const loadServers = () => - cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }).pipe( + cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }, { includeProject: true }).pipe( Effect.provideService(HostProcess.HomeDirectory, home), Effect.provideService(HostProcess.Environment, {}), ); @@ -3398,13 +3398,13 @@ describe("CursorAdapterV2", () => { Effect.provideService(HostProcess.Environment, {}), ); const now = yield* DateTime.now; - const sendTurn = (ordinal: number) => + const sendTurn = (ordinal: number, turnPolicy = runtimePolicy) => runtime .startTurn({ threadId, providerThread, modelSelection, - runtimePolicy, + runtimePolicy: turnPolicy, runId: RunId.make(`cursor-mcp-run-${ordinal}`), runOrdinal: ordinal, providerTurnOrdinal: ordinal, @@ -3479,6 +3479,20 @@ describe("CursorAdapterV2", () => { ); yield* sendTurn(3); assert.deepEqual(sentWith[2], t3Servers); + // A restricted turn starts no command the checkout names; the user's own file still applies. + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), + "[]", + ); + for (const [index, runtimeMode] of ( + ["approval-required", "auto-accept-edits", "auto"] as const + ).entries()) { + yield* sendTurn(4 + index, { ...runtimePolicy, runtimeMode }); + assert.deepEqual(sentWith[3 + index], { + repro: { command: "node", args: [`${home}/shadowed.mjs`], cwd: projectRoot }, + ...t3Servers, + }); + } yield* fileSystem.writeFileString( path.join(workspace, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index c758e46a7b3dc..042adcc9c3e9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -309,6 +309,17 @@ const CURSOR_AGENT_SETTING_SOURCES = [ "plugins", ] as const satisfies ReadonlyArray; +/** Whether the checkout's own Cursor config (settings, hooks, MCP servers) may load: only unrestricted turns. */ +function cursorLoadsProjectConfig( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + platform: NodeJS.Platform, +): boolean { + const policy = cursorRuntimeAgentPolicy(runtimePolicy, platform); + return ( + runtimePolicy.runtimeMode === "full-access" && !policy.autoReview && !policy.sandboxEnabled + ); +} + export function makeCursorAgentOptions(input: { readonly apiKey?: string; readonly modelSelection: ModelSelection; @@ -332,12 +343,9 @@ export function makeCursorAgentOptions(input: { ? {} : { dirs: [...input.runtimePolicy.workspace.extraRoots] }), autoReview: policy.autoReview, - settingSources: - input.runtimePolicy.runtimeMode === "full-access" && - !policy.autoReview && - !policy.sandboxEnabled - ? [...CURSOR_AGENT_SETTING_SOURCES] - : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), + settingSources: cursorLoadsProjectConfig(input.runtimePolicy, input.platform) + ? [...CURSOR_AGENT_SETTING_SOURCES] + : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), sandboxOptions: { enabled: policy.sandboxEnabled, }, @@ -2731,10 +2739,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( } }; - const resolveWorkspaceMcpServers = (cwd: string | null) => - cwd === null + const resolveWorkspaceMcpServers = ( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + ) => { + const { cwd } = runtimePolicy; + return cwd === null ? Effect.succeed({}) - : cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe( + : cursorWorkspaceMcpServers(cwd, adapterOptions.environment, { + includeProject: cursorLoadsProjectConfig(runtimePolicy, platform), + }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -2746,6 +2759,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as({})), ), ); + }; const openAgent = Effect.fnUntraced(function* (openInput: { readonly operation: "create" | "resume"; @@ -3030,7 +3044,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( // A send-time set replaces the create-time set, so the workspace servers go only here and are // read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources. const turnMcpServers = { - ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), + ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy)), ...mcpServers, }; let starting = true; diff --git a/packages/provider-cursor/src/server/workspaceMcpServers.ts b/packages/provider-cursor/src/server/workspaceMcpServers.ts index f3e53b508e3b3..6cdfb98f5116a 100644 --- a/packages/provider-cursor/src/server/workspaceMcpServers.ts +++ b/packages/provider-cursor/src/server/workspaceMcpServers.ts @@ -83,6 +83,8 @@ function cursorProjectSlug(projectRoot: string): string { export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")(function* ( cwd: string, environment: NodeJS.ProcessEnv, + // The project file is the checkout's own; a restricted turn must not start its commands. + options: { readonly includeProject: boolean }, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -144,7 +146,7 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( const seen = new Set(); const servers: Record = {}; for (const file of [ - path.join(projectRoot, ".cursor", "mcp.json"), + ...(options.includeProject ? [path.join(projectRoot, ".cursor", "mcp.json")] : []), path.join(userHome, ".cursor", "mcp.json"), ]) { const contents = yield* readJsonc(file); From 7dd35d324db68c092ab5dec0fa7ea7659470c6b3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:45:25 -0800 Subject: [PATCH 205/288] fix(server): link codes and guest links require the access they hand out (#41742) Getting a link code through a linked environment now requires the scopes of the access level requested, and creating a guest link requires orchestration:read, in addition to access:write. The link dialog offers linking through another environment only when the session holds them. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.test.ts | 70 +++++++++++++++++++ .../server/src/peer/PeerClientPairing.test.ts | 32 --------- .../settings/LinkedEnvironmentsSettings.tsx | 14 +++- docs/internals/04_environment-auth.md | 11 ++- docs/internals/06_t3-connect.md | 4 +- docs/user/remote-access.md | 3 +- .../contracts/src/clientRpcPermissions.ts | 11 +++ 7 files changed, 107 insertions(+), 38 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 750ff136ac07d..15ddfb90b08a5 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,6 +355,76 @@ it.effect("pairs a client with a linked environment only for one that may hand o }).pipe(Effect.scoped), ); +it.effect("hands out a link code or a guest link only within what the session itself holds", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate + > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate, + ), + ); + let handled = 0; + const environmentId = EnvironmentId.make("environment-box"); + const threadId = ThreadId.make("thread-1"); + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.peerLinksPairLink, () => + Effect.sync(() => { + handled++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ), + group.toLayerHandler(WS_METHODS.guestShareCreate, () => + Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))), + ), + ); + const clientWith = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))), + ); + + // Managing access alone is not running agents or reading threads. + const manager = yield* clientWith([AuthAccessWriteScope]); + expect( + yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + expect( + yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + + const supervisor = yield* clientWith([ + AuthAccessWriteScope, + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + ]); + expect( + yield* supervisor[WS_METHODS.peerLinksPairLink]({ + environmentId, + access: "full-access", + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); + expect(handled).toBe(0); + + expect( + (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type, + ).toBe("unsupported"); + expect(handled).toBe(1); + yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit); + expect(handled).toBe(2); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts index 17a5df1cb75ff..8dacc53f7f07e 100644 --- a/apps/server/src/peer/PeerClientPairing.test.ts +++ b/apps/server/src/peer/PeerClientPairing.test.ts @@ -257,38 +257,6 @@ it.effect("pairs no client while Linked environments is off on either side", () ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); -it.effect("a full-access link gets a pairing code that links another environment to the box", () => - Effect.scoped( - Effect.gen(function* () { - const b = yield* serveBox(); - const a = yield* makeLaptop; - yield* linkTo(a.links, b, "full-access"); - const phone = yield* a.client([AuthAccessWriteScope]); - - const result = yield* a.pairing.requestForLink( - { environmentId: box.environmentId, access: "approval-required" }, - phone, - ); - if (result.type !== "credential") return yield* Effect.die(result); - expect(result).toMatchObject({ environmentId: box.environmentId, urls: [b.url] }); - - // A third environment links with it, at the access the code was minted for. - const desk = yield* Layer.build( - layerLinkingEnvironment(descriptorOf("environment-desk", "Desk")), - ); - const linked = yield* Context.get(desk, PeerLinks.PeerLinks).link({ - url: b.url, - pairingCode: result.credential, - access: "approval-required", - }); - expect(linked).toMatchObject({ - environmentId: box.environmentId, - access: "approval-required", - }); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - it.effect("a linked environment from before link pairing is never asked for one", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 5ab6debec7255..71afddaa33b32 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -329,8 +329,20 @@ export function LinkEnvironmentDialog({ const throughCandidate = prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null)); const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null); + // The environment holding the link refuses a level this client's session there does not hold. + const mayPairThrough = useAtomValue( + peerLinkEnvironment.pairLink.permissionAtom( + throughCandidate?.viaEnvironmentId ?? null, + throughCandidate === null + ? undefined + : { environmentId: throughCandidate.environmentId, access }, + ), + ); const through = - throughCandidate !== null && via !== null && !throughFailed.has(throughCandidate.environmentId) + throughCandidate !== null && + via !== null && + mayPairThrough && + !throughFailed.has(throughCandidate.environmentId) ? throughCandidate : null; const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open); diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 53c9f60d8f7c6..8b80c65860d60 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -8,8 +8,12 @@ model. ## Scoped sessions and delegation - **Narrowing only.** Pairing delegates a set of scopes. Exchanging a bootstrap credential can - narrow a grant, never widen it. Creating another pairing link requires both `access:write` and - every scope being delegated. Client labels and device metadata have no authorization role. + narrow a grant, never widen it. Client labels and device metadata have no authorization role. +- **`access:write` hands out what the session holds and revokes anything.** Every route that + returns a credential to the caller requires `access:write` and every scope that credential + carries: a pairing link, an MCP sign-in approval, a link code from a linked environment, and a + guest link (which reads a thread). Revoking is not capped by the caller's scopes. Admitting a + T3 Connect device is not delegation; see [T3 Connect](./06_t3-connect.md). - **Why the default grant includes management scopes.** `terminal:operate` and `orchestration:operate` already grant OS-user execution (which can invoke `t3 auth session issue`), so withholding access or relay management from the default grant would not be a real boundary. @@ -48,7 +52,8 @@ model. - **Peer-link client pairing.** Only a full-access peer link may mint a one-time client pairing on the linked environment (since full-access agents can already run `t3 auth pairing create`). The linked side enforces this itself, and the operation stays a human-triggered RPC/HTTP route rather - than an MCP tool. + than an MCP tool. The same route mints a code that links another environment at a chosen access + level, and the linking side's RPC requires the caller to hold that level's scopes. ### Reusable dev credential diff --git a/docs/internals/06_t3-connect.md b/docs/internals/06_t3-connect.md index 2962721830a86..dc60a5468b849 100644 --- a/docs/internals/06_t3-connect.md +++ b/docs/internals/06_t3-connect.md @@ -28,7 +28,9 @@ Deployment and Clerk configuration live in the [Connect setup runbook](../operat compromised relay signing key. Enabling `requireConnectDeviceApproval` shifts trust from the relay to approved DPoP key thumbprints: untrusted keys mint credentials that cannot be spent until someone with `access:write` approves the key, and revoking a key revokes all of its sessions and - pending credentials. + pending credentials. Approving admits a device already signed in to the owner's cloud account + and returns no credential to the approver, so `access:write` alone is enough, as it is for + turning the setting off. - **Anti-hijack and anti-SSRF rules.** Managed tunnels expose only the server's own loopback HTTP origin (ignoring caller-supplied origins). The relay refuses to relink an active environment ID under a different key until unlinked, resolves endpoints only from its own managed allocations, diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 051445f03eb07..bdcd2281ccd08 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -488,7 +488,8 @@ it needs no pairing code. A machine this app is not connected to, shown only because another environment links to it, can still be linked without a code when that link has full access: drop the plus on it and the environment holding the link gets the pairing code -from it. Your session on that environment must manage access there. The result +from it. Your session on that environment must manage access there and already +have the access you pick. The result is a separate link with the access you pick, listed and revocable on the linked machine like any other. Links still do not chain. diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b23b4650b20a9..eb61fff1c0abd 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -11,7 +11,9 @@ import { AuthSourceControlWriteScope, AuthTerminalOperateScope, type AuthEnvironmentScope, + mcpClientScopes, } from "./auth.ts"; +import { PeerLinkLinkPairingInput } from "./peerLink.ts"; import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts"; import { WS_METHODS } from "./rpc.ts"; @@ -106,6 +108,7 @@ export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; const decodePrepareThread = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput); const decodeStackedAction = Schema.decodeUnknownSync(GitRunStackedActionInput); +const decodeLinkPairing = Schema.decodeUnknownSync(PeerLinkLinkPairingInput); export function clientRpcRequiredScopes( method: string, @@ -124,6 +127,14 @@ export function clientRpcRequiredScopes( ) return [AuthSourceControlWriteScope, AuthOrchestrationReadScope]; } + // Handing out access takes holding it: the caller gets back a credential it can spend itself. + if (method === WS_METHODS.peerLinksPairLink && input !== undefined) { + const held = mcpClientScopes(decodeLinkPairing(input).access); + return [AuthAccessWriteScope, ...held]; + } + if (method === WS_METHODS.guestShareCreate) { + return [AuthAccessWriteScope, AuthOrchestrationReadScope]; + } return Object.hasOwn(CLIENT_GUARDED_RPC_SCOPES, method) ? [CLIENT_GUARDED_RPC_SCOPES[method as ClientGuardedRpcTag]] : []; From 2dd323463a300d82663eaa5df3e9b85b78d3eb7a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:48:05 -0800 Subject: [PATCH 206/288] fix(server): API request bodies have a 1 MiB default limit and tag scans stay linear (#41747) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/McpOAuth.test.ts | 22 +++++++++++++ apps/server/src/cloud/http.test.ts | 12 +++++++ apps/server/src/http.ts | 7 ++++ apps/server/src/server.ts | 1 + .../src/pullRequestMarkdown.test.ts | 21 ++++++++++++ .../client-runtime/src/pullRequestMarkdown.ts | 32 +++++++++++++++++-- packages/shared/src/htmlRender.test.ts | 21 ++++++++++-- packages/shared/src/htmlRender.ts | 12 ++++--- 8 files changed, 119 insertions(+), 9 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index f66d0b1c6e81c..c21b707bad889 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -27,6 +27,7 @@ import * as CloudLink from "../cloud/CloudLink.ts"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; @@ -75,6 +76,7 @@ const makeLayerRoutes = ( ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ).pipe( Layer.provideMerge(layerEnvironmentAuth), @@ -216,6 +218,26 @@ it.effect("derives discovery metadata from the origin the client reached", () => ), ); +it.effect("answers 413 to a body over the API limit", () => + withRoutes((handler) => + Effect.gen(function* () { + const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1); + for (const [path, contentType] of [ + ["/api/auth/browser-session", "application/json"], + ["/oauth/token", "application/x-www-form-urlencoded"], + ["/oauth/mcp/register", "application/json"], + ]) { + const init = { method: "POST", headers: { "content-type": contentType! } }; + expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413); + // A chunked body declares no length, so the reader itself has to stop. + const chunked = new Blob([body]).stream(); + const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit); + expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413); + } + }), + ), +); + it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 5115a27e63012..852be24a22200 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -31,6 +31,7 @@ import * as AuthHttp from "../auth/http.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; @@ -78,6 +79,7 @@ const layerConfig = Layer.effect( const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe( Layer.provide([AuthHttp.layer, ConnectHttp.layer]), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), Layer.provide(CloudLink.layer), Layer.provide(ServerSettings.ServerSettingsService.layerTest()), Layer.provide(EnvironmentKeys.layer), @@ -303,4 +305,14 @@ describe("link proof over a non-loopback transport", () => { expect(response.status).toBe(401); }), ); + + it.effect("answers 413 to a relay proof body over the API limit", () => + Effect.gen(function* () { + const { post } = yield* linkProofClient; + const payload = { proof: "x".repeat(ServerHttp.API_MAX_BODY_BYTES) }; + for (const path of ["/api/t3-connect/health", "/api/t3-connect/mint-credential"]) { + expect((yield* post(path, payload)).status, path).toBe(413); + } + }), + ); }); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 8a31a99287e38..493356998393a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -33,6 +33,7 @@ import { HttpServerRequest, HttpServerRespondable, } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { OtlpTracer, OtlpSerialization } from "effect/observability"; @@ -284,6 +285,12 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers }); }); +// The default body limit for API routes. Routes that take more set their own limit. +export const API_MAX_BODY_BYTES = 1024 * 1024; +export const layerApiBodyLimit = HttpRouter.middleware( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(API_MAX_BODY_BYTES)), +).layer; + export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { global: true, }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 26cea18609b93..b3c21d9918860 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -900,6 +900,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(ServerHttp.layerServerEnvironmentHttpApi), Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index 7d9d162d76a05..a397241775db6 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -190,6 +190,15 @@ describe("pull request body segmentation", () => { ]); }); + it.each([ + ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`], + ["a run of unclosed video tags", `${"
(promise: Promise, millis: number): Promise { @@ -471,20 +476,21 @@ async function captureElement(element: Element): Promise { pickedAt: new Date().toISOString(), }; try { - const context = await withCaptureTimeout( - Promise.resolve(getElementContext(element)), + const context: unknown = await withCaptureTimeout( + Promise.resolve(pageWorld.elementContext(element)), ELEMENT_CONTEXT_TIMEOUT_MS, ); - if (context) { - const stack = (context.stack ?? []).map(toStackFrame); + if (typeof context === "object" && context !== null) { + const frames = pageField(context, "stack"); + const stack = Array.isArray(frames) ? frames.map(toStackFrame) : []; return { ...base, - selector: context.selector, - htmlPreview: context.htmlPreview ?? "", - componentName: context.componentName, + selector: pageString(context, "selector"), + htmlPreview: pageString(context, "htmlPreview") ?? "", + componentName: pageString(context, "componentName"), source: stack[0] ?? null, stack, - styles: context.styles ?? "", + styles: pageString(context, "styles") ?? "", }; } } catch {} diff --git a/apps/desktop/src/preview/WebviewPreferences.test.ts b/apps/desktop/src/preview/WebviewPreferences.test.ts index 572a290e2b669..ed3df8bb1f9c7 100644 --- a/apps/desktop/src/preview/WebviewPreferences.test.ts +++ b/apps/desktop/src/preview/WebviewPreferences.test.ts @@ -25,6 +25,10 @@ describe("PREVIEW_WEBVIEW_PREFERENCES", () => { } }); + it("keeps the page out of the picker preload's JavaScript world", () => { + expect(parsed["contextIsolation"]).toBe("true"); + }); + it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => { expect(parsed["sandbox"]).toBe("true"); }); diff --git a/apps/desktop/src/preview/WebviewPreferences.ts b/apps/desktop/src/preview/WebviewPreferences.ts index 4dc9d9aa6b732..cb1ddb11bd1ea 100644 --- a/apps/desktop/src/preview/WebviewPreferences.ts +++ b/apps/desktop/src/preview/WebviewPreferences.ts @@ -1,3 +1,3 @@ -/** sandbox:true is required with contextIsolation:false or the shared page global would expose Node and IPC. */ +/** The picker preload runs in its own JavaScript world; PageWorld.ts holds what must run in the page's. */ export const PREVIEW_WEBVIEW_PREFERENCES = - "contextIsolation=false,sandbox=true,nodeIntegration=false"; + "contextIsolation=true,sandbox=true,nodeIntegration=false"; diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3d882399a6173..28a2cde19d0cc 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -76,6 +76,7 @@ function makeFakeBrowserWindow() { const webContents = { id: 1, session: { + setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn(), }, @@ -1536,7 +1537,7 @@ describe("DesktopWindow", () => { }, { primaryPasteEnabled: true, expected: [PASSKEY_BRIDGE_ARGUMENT] }, ])( - "passes the primary-paste setting to preview guests (enabled: $primaryPasteEnabled)", + "isolates preview guests and passes them the primary-paste setting (enabled: $primaryPasteEnabled)", ({ primaryPasteEnabled, expected }) => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1562,6 +1563,7 @@ describe("DesktopWindow", () => { }); assert.deepEqual(webPreferences.additionalArguments, expected); + assert.isTrue(webPreferences.contextIsolation); }).pipe(Effect.provide(layer)); }), ); @@ -1615,6 +1617,63 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens only web links from popups and declines external-protocol navigations", () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const openedExternalUrls: unknown[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount: yield* Ref.make(0), + mainWindow: yield* Ref.make>(Option.none()), + openedExternalUrls, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const openHandler = vi.mocked(fakeWindow.window.webContents.setWindowOpenHandler).mock + .lastCall?.[0]; + if (!openHandler) { + return yield* Effect.die("window open handler was not registered"); + } + for (const url of [ + "vscode://file/home/user/project/readme.md", + "vscode://vscode-remote/ssh-remote+remote.example/home/user/project", + "zed://ssh/remote.example/home/user/project", + "jetbrains://gateway/ssh/environment?h=remote.example", + "grokbot://app/v1/prompt?text=hi", + "https://example.com/docs", + ]) { + assert.deepEqual( + openHandler({ url } as Electron.HandlerDetails), + { action: "deny" }, + url, + ); + } + yield* Effect.promise(() => Promise.resolve()); + + assert.deepEqual(openedExternalUrls, ["https://example.com/docs"]); + + const answerPermission = vi.mocked( + fakeWindow.window.webContents.session.setPermissionRequestHandler, + ).mock.lastCall?.[0]; + if (!answerPermission) { + return yield* Effect.die("permission request handler was not registered"); + } + const answers = (["openExternal", "media"] as const).map((permission) => { + const callback = vi.fn(); + answerPermission(fakeWindow.window.webContents, permission, callback, { + isMainFrame: false, + requestingUrl: "http://127.0.0.1:3773/api/assets/token/page.html", + }); + return callback.mock.lastCall?.[0]; + }); + assert.deepEqual(answers, [false, true]); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("offers to copy the bare address when right-clicking a mailto link", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..ebf64c7540507 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -633,7 +633,7 @@ export const make = Effect.gen(function* () { webPreferences.sandbox = true; webPreferences.nodeIntegration = false; webPreferences.nodeIntegrationInSubFrames = false; - webPreferences.contextIsolation = false; + webPreferences.contextIsolation = true; webPreferences.disableHtmlFullscreenWindowResize = true; if (previewPasskeys.bridgeEnabled) { webPreferences.additionalArguments = [ @@ -773,12 +773,19 @@ export const make = Effect.gen(function* () { void runPromise(previewManager.prepareWebview(contents)); }); + // Popups from every frame in this window arrive here without a caller, so only web links + // pass. The app opens editors and other applications over IPC. window.webContents.setWindowOpenHandler(({ url }) => { - if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) { + if (Option.isSome(ElectronShell.parseWebExternalUrl(url))) { void runPromise(electronShell.openExternal(url)); } return { action: "deny" }; }); + // Chromium asks this before handing a navigation to an OS protocol handler, and grants it + // when nothing answers. External links are opened through ElectronShell only. + window.webContents.session.setPermissionRequestHandler((_contents, permission, callback) => + callback(permission !== "openExternal"), + ); window.webContents.on("will-navigate", (event, url) => { if ( isSameOriginRendererNavigation({ diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 42063f99b63a0..4866dd32d08f9 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -2,6 +2,7 @@ import "vite-plus/test/config"; import * as NodeOS from "node:os"; import { defaultInclude, defineConfig } from "vite-plus"; +import { Rolldown } from "vite-plus/pack"; import { isDesktopRuntimeExternalDependency } from "../../scripts/lib/desktop-external-packages.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; @@ -26,6 +27,28 @@ const publicConfigDefine = { ), }; +const PAGE_WORLD_MODULE = /[\\/]src[\\/]preview[\\/]PageWorld\.ts$/; + +/** + * The preview preload passes `installPageWorld` to `contextBridge.executeInMainWorld`, which runs + * the function's source text in the page. Inline the module's imports into the function body so + * that text is complete on its own. + */ +const pageWorldFunction = (): Rolldown.Plugin => ({ + name: "t3code:preview-page-world", + async load(id) { + if (!PAGE_WORLD_MODULE.test(id)) return null; + const bundle = await Rolldown.rolldown({ input: id, platform: "browser" }); + try { + const { output } = await bundle.generate({ format: "iife", name: "pageWorld" }); + for (const file of await bundle.watchFiles) this.addWatchFile(file); + return `export function installPageWorld(host) {\n${output[0].code}\nreturn pageWorld.installPageWorld(host);\n}\n`; + } finally { + await bundle.close(); + } + }, +}); + export default defineConfig({ run: { tasks: { @@ -136,11 +159,9 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), entry: ["src/preview-pick-preload.ts"], + plugins: [pageWorldFunction()], deps: { - alwaysBundle: (id) => - id === "react-grab" || - id.startsWith("react-grab/") || - id === "@t3tools/shared/keybindingMatching", + alwaysBundle: (id) => id === "@t3tools/shared/keybindingMatching", }, }, { diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index a072ecc107e26..645d53d630c74 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -96,6 +96,7 @@ vi.mock(import("../localApi"), async (original) => ({ shell: { openExternal: state.openExternal }, }) as never, })); +vi.mock(import("../env"), async (original) => ({ ...(await original()), isElectron: true })); vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({ ...(await original()), resolvePullRequestPreviewTarget: () => null, @@ -323,3 +324,19 @@ it("preserves keyboard activation of a file-options button", async () => { await userEvent.click(button); await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse")); }); + +it("opens an editor link over the desktop bridge on a click and on a middle-click", async () => { + using _setup = setup(); + const href = "vscode://file/work/docs/readme.md:3"; + await using screen = await renderMarkdown(`[Open in editor](${href})`); + for (const [type, button] of [ + ["click", 0], + ["auxclick", 1], + ] as const) { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, button }); + await act(async () => screen.anchor().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(true); + expect(state.openExternal).toHaveBeenLastCalledWith(href); + } + expect(state.openExternal).toHaveBeenCalledTimes(2); +}); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index f29acac070e42..f41cc0375bee2 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1427,7 +1427,8 @@ const CHAT_MARKDOWN_COMPONENTS = { }) !== "app" ) { // Open desktop Alt-clicks before Chromium downloads them so link routers can read the held key. - if (isElectron && event.altKey) { + // Editor links also go over IPC: the desktop popup handler only passes web links. + if (isElectron && (event.altKey || isLocalEditorFileHref(href))) { event.preventDefault(); event.stopPropagation(); void readLocalApi() @@ -1453,6 +1454,19 @@ const CHAT_MARKDOWN_COMPONENTS = { void readLocalApi()?.shell.openExternal(href); }); }} + onAuxClick={(event) => { + // A middle-click raises no click event, and the desktop popup handler only passes web links. + if (!isElectron || event.button !== 1 || !href || !isLocalEditorFileHref(href)) return; + event.preventDefault(); + void readLocalApi() + ?.shell.openExternal(href) + .catch((cause) => + reportMarkdownActionFailure( + { operation: "open-link-external", target: href }, + cause, + ), + ); + }} onKeyDown={(event) => { if (href && faviconHost) openContextMenuFromKeyboard(event); }} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 962cfd089dd2b..45f55bde2b2d8 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -675,7 +675,7 @@ export interface DesktopPreviewRecordingInputEvent { export interface DesktopPreviewWebviewConfig { partition: string; - /** Sandboxed with contextIsolation off so the picker preload can read the React DevTools hook. */ + /** Sandboxed and context-isolated; the picker preload reaches React through a function it runs in the page. */ webPreferences: string; /** Absolute file:// preload URL; null requires disabling element picking. */ preloadUrl: string | null; From 78cffe29ec3adc3d1c0acde2f4425c616973114f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:07:52 -0800 Subject: [PATCH 214/288] fix: a merge or review stays on the commit you opened the pull request on (#41761) Co-authored-by: Claude Fable 5.2 --- .../pull-requests/PullRequestControls.tsx | 8 +- .../PullRequestMergeControls.tsx | 13 ++- .../pull-requests/PullRequestReviewSheet.tsx | 14 ++- .../pull-requests/PullRequestRouteScreen.tsx | 8 +- .../guide/PullRequestGuideScreen.tsx | 1 + .../pullRequest/PullRequestService.test.ts | 11 ++- .../src/pullRequest/PullRequestService.ts | 85 +++++++++++-------- .../chat/ThreadDetailsPrRow.browser.test.tsx | 40 ++++++--- .../components/chat/ThreadDetailsPrRow.tsx | 10 ++- .../pullRequest/PullRequestComposer.tsx | 6 ++ ...stDetailPanel.permissions.browser.test.tsx | 51 ++++++++++- .../pullRequest/PullRequestDetailPanel.tsx | 47 ++++++++++ .../PullRequestReviewForm.browser.test.tsx | 8 +- .../pullRequest/PullRequestReviewForm.tsx | 7 ++ .../PullRequestStackMenu.browser.test.tsx | 21 ++++- .../pullRequest/PullRequestStackMenu.tsx | 6 +- .../pullRequestDetail.logic.test.ts | 14 +++ .../pullRequest/pullRequestDetail.logic.ts | 21 +++++ .../usePullRequestActions.browser.test.tsx | 6 ++ .../pullRequest/usePullRequestActions.ts | 8 ++ apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + docs/user/source-control.md | 5 ++ .../src/state/pullRequests.test.ts | 33 +++++++ .../client-runtime/src/state/pullRequests.ts | 9 +- packages/contracts/src/pullRequest.ts | 2 + .../src/server/PullRequestProvider.ts | 2 + .../src/server/ForgejoPullRequestProvider.ts | 2 +- .../src/server/GitCafePullRequestProvider.ts | 2 +- .../src/server/GitHubPullRequestApi.ts | 2 + .../src/server/gitHubPullRequestJson.test.ts | 2 + .../src/server/gitHubPullRequestJson.ts | 4 + 40 files changed, 396 insertions(+), 72 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx index 99ad80b80074e..11e92266cc327 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx @@ -119,6 +119,8 @@ export function PullRequestActionToolbar(props: { readonly pr: PullRequestDetail | null; readonly params: PullRequestParams; readonly filePath?: string; + /** The head of the diff on screen, when the screen shows one. */ + readonly reviewedHeadSha?: string | undefined; /** The screen's actions menu; the vertical bar shows it here with the toolbar's tools. */ readonly menu: AppBarMenu; readonly onOpenFiles?: () => void; @@ -152,7 +154,11 @@ export function PullRequestActionToolbar(props: { const chooseThread = agent.chooseThread; const agentActions = agent.actions.filter((action) => action.task !== "ask"); const open = (mode: "review" | "comment") => - navigation.navigate("PullRequestReview", { ...props.params, mode }); + navigation.navigate("PullRequestReview", { + ...props.params, + mode, + reviewedHeadSha: props.reviewedHeadSha ?? props.pr?.headSha, + }); const primaryPress = () => (pendingReview ? open("review") : agent.start("ask")); const threadMenuItems = agent.threadActions("ask"); const openFiles = diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index 42894c06b3785..0fcc79c3eb7ac 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -158,7 +158,10 @@ export function PullRequestMergeControls(props: { permissions.canWrite && canPerformPullRequestAction(pr, autoAction); - const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + const perform = async ( + action: "merge" | "enable-auto-merge" | "disable-auto-merge", + shownHeadSha: string | undefined, + ) => { if ( pending.current || (action !== "disable-auto-merge" && !method) || @@ -172,6 +175,10 @@ export function PullRequestMergeControls(props: { input: { ...target.input, action, + // A merge lands the head on screen and refuses one that moved; a stack pins its other layers. + ...(action !== "disable-auto-merge" && shownHeadSha + ? { expectedHeadSha: shownHeadSha } + : {}), ...(action === "merge" && method && stack.stack && scope ? { stackNumber: stack.stack.number, @@ -218,6 +225,8 @@ export function PullRequestMergeControls(props: { } }; const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + // The overview refreshes on focus, so the alert merges the head it was opened on. + const shownHeadSha = pr.headSha; const title = action === "merge" ? scope && scope.layers.length > 1 @@ -274,7 +283,7 @@ export function PullRequestMergeControls(props: { : action === "enable-auto-merge" ? gt("Enable auto-merge") : gt("Disable auto-merge"), - onPress: () => void perform(action), + onPress: () => void perform(action, shownHeadSha), }, ]); }; diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index ec45e5f3a33ca..8bf3c0290b45d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -70,7 +70,13 @@ const VERDICTS = [ export function PullRequestReviewSheet({ route, -}: StaticScreenProps) { +}: StaticScreenProps< + PullRequestParams & { + readonly mode: "review" | "comment"; + /** The head the opening screen showed; this sheet's own read can run ahead of it. */ + readonly reviewedHeadSha?: string | undefined; + } +>) { const params = route.params; const gt = useGT(); const m = useMessages(); @@ -97,6 +103,7 @@ export function PullRequestReviewSheet({ onChangeValue: setBody, support: result.data?.capabilities ?? null, }); + const reviewedHeadSha = params.reviewedHeadSha ?? result.data?.headSha; const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha); const [requestedVerdict, setRequestedVerdict] = useState("comment"); const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value)); @@ -130,6 +137,7 @@ export function PullRequestReviewSheet({ ...target, input: { ...target.input, + ...(reviewedHeadSha ? { expectedHeadSha: reviewedHeadSha } : {}), verdict: verdict.value, body, comments: submitted.comments.map( @@ -150,8 +158,8 @@ export function PullRequestReviewSheet({ - navigation.navigate("PullRequestReview", { ...params, mode: "review" }), + navigation.navigate("PullRequestReview", { + ...params, + mode: "review", + reviewedHeadSha: pr?.headSha, + }), }, ] : []), @@ -1271,6 +1275,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestReview", { ...route.params, mode: "review", + reviewedHeadSha: diffHead.sha ?? undefined, }), }, ] @@ -1503,6 +1508,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestFiles", route.params)} diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx index 852ba3932323e..97e35e7739f8e 100644 --- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx +++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx @@ -283,6 +283,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps +it.effect("refuses a merge or review whose head moved past expectedHeadSha and pins the host", () => Effect.gen(function* () { const head = "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"; const pinned: Array = []; + const reviewed: Array = []; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ @@ -1566,10 +1567,18 @@ it.effect("refuses a merge whose head moved past expectedHeadSha and pins the ho getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("Body"), headSha: head }), getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")), runAction: (input) => Effect.sync(() => void pinned.push(input.expectedHeadSha)), + submitReview: (input) => Effect.sync(() => void reviewed.push(input.expectedHeadSha)), }), ], }); const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const approval = { ...reference, verdict: "approve" as const, body: "", comments: [] }; + const unseen = yield* Effect.flip( + service.submitReview({ ...approval, expectedHeadSha: "0a1b2c4" }), + ); + assert.include(unseen.message, head); + yield* service.submitReview({ ...approval, expectedHeadSha: "0a1b2c3d4" }); + assert.deepStrictEqual(reviewed, [head]); const refused = yield* Effect.flip( service.runAction({ ...reference, action: "merge", expectedHeadSha: "0a1b2c4" }), ); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 690b7c4153f98..b7e56e2062096 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2315,32 +2315,7 @@ export const make = Effect.gen(function* () { ), ) : Effect.succeed(false); - // Hosts that cannot pin a merge to a commit still refuse a head that already moved. - const expected = input.expectedHeadSha; - const headPinned: Effect.Effect = - expected === undefined - ? Effect.undefined - : project.api - .getChangeRequest({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - }) - .pipe( - Effect.mapError(toPullRequestError("runAction")), - Effect.flatMap((current) => - typeof current.headSha === "string" && isHeadSha(current.headSha, expected) - ? Effect.succeed(current.headSha) - : Effect.fail( - new PullRequestOperationError({ - operation: "runAction", - detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, - }), - ), - ), - ); - return headPinned.pipe( + return pinnedHead(project, input, "runAction").pipe( Effect.flatMap((expectedHeadSha) => Effect.map(mergeSettings, (removeAgentCreditsOnMerge) => ({ expectedHeadSha, @@ -2407,6 +2382,37 @@ export const make = Effect.gen(function* () { }), ); + // Hosts that cannot pin a write to a commit still refuse a head that already moved. + const pinnedHead = ( + project: SupportedProject, + input: { readonly number: number; readonly expectedHeadSha?: string | undefined }, + operation: string, + ): Effect.Effect => { + const expected = input.expectedHeadSha; + return expected === undefined + ? Effect.undefined + : project.api + .getChangeRequest({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }) + .pipe( + Effect.mapError(toPullRequestError(operation)), + Effect.flatMap((current) => + typeof current.headSha === "string" && isHeadSha(current.headSha, expected) + ? Effect.succeed(current.headSha) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, + }), + ), + ), + ); + }; + const comment: PullRequestService["Service"]["comment"] = (input) => (input.body.trim().length === 0 ? Effect.fail( @@ -2566,17 +2572,22 @@ export const make = Effect.gen(function* () { "You need write access on this repository to comment on a line of a change request.", ); } - return project.api - .submitReview({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - verdict: input.verdict, - body: input.body, - comments: input.comments, - }) - .pipe(Effect.mapError(toPullRequestError("submitReview"))); + return pinnedHead(project, input, "submitReview").pipe( + Effect.flatMap((expectedHeadSha) => + project.api + .submitReview({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + verdict: input.verdict, + body: input.body, + comments: input.comments, + ...(expectedHeadSha === undefined ? {} : { expectedHeadSha }), + }) + .pipe(Effect.mapError(toPullRequestError("submitReview"))), + ), + ); }), ); }), diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index b17067affb96f..666bbccd13684 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -17,6 +17,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ issuesSupported: false, isDraft: false, + headSha: "shown-head", status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -59,6 +60,7 @@ const queryData = () => ({ title: "Test PR", state: "open", isDraft: state.isDraft, + headSha: state.headSha, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -178,19 +180,21 @@ it("merges with the last selected merge method", async () => { const { container } = screen; state.mergeMethods = ["merge", "squash"]; useUiStateStore.getState().setPullRequestMergeMethod("squash"); - await act(async () => { - await screen.rerender( - , - ); - }); + const rerender = () => + act(async () => { + await screen.rerender( + , + ); + }); + await rerender(); const clickMerge = async (scope: ParentNode) => await act(async () => { [...scope.querySelectorAll("button")] @@ -200,10 +204,17 @@ it("merges with the last selected merge method", async () => { await clickMerge(container); const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); + // A push that a background refresh picks up while the confirmation is open. + state.headSha = "pushed-head"; + await rerender(); await clickMerge(dialog); expect(state.perform).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + input: expect.objectContaining({ + action: "merge", + mergeMethod: "squash", + expectedHeadSha: "shown-head", + }), }), ); }); @@ -260,6 +271,7 @@ async function setup() { state.updateToast.mockReset(); state.issuesSupported = false; + state.headSha = "shown-head"; state.isDraft = false; state.status = "success"; state.extraStatus = null; diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 3b7836b32293d..dd3e93ca9a578 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,14 +166,19 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); + const [armedMergeHead, setArmedMergeHead] = useState(); const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, + // The row shows no diff, so a merge lands the head it had when the confirmation opened. + headSha: armedMergeHead ?? detail?.headSha, terminology, onSuccess: () => { checksQuery.refresh(); onActed?.(); }, + // A refused merge usually means the row is stale, so show what the host has now. + onFailure: () => detailQuery.refresh(), }); const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail }); const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod); @@ -449,7 +454,10 @@ export function ThreadDetailsPrRow({ method: mergeMethodKey, }, ), - onClick: () => setConfirmingMerge(true), + onClick: () => { + setArmedMergeHead(detail?.headSha); + setConfirmingMerge(true); + }, } : null; diff --git a/apps/web/src/components/pullRequest/PullRequestComposer.tsx b/apps/web/src/components/pullRequest/PullRequestComposer.tsx index e59580d43bddd..e6dd58e82b824 100644 --- a/apps/web/src/components/pullRequest/PullRequestComposer.tsx +++ b/apps/web/src/components/pullRequest/PullRequestComposer.tsx @@ -22,6 +22,7 @@ export function PullRequestComposer({ environmentId, reference, detail, + shownHeadSha, actionPending, onCommentAction, onCommented, @@ -31,6 +32,8 @@ export function PullRequestComposer({ environmentId: EnvironmentId; reference: PullRequestRef; detail: PullRequestDetailView; + /** The head the reader was shown, which a background refresh of `detail` can run ahead of. */ + shownHeadSha: string | undefined; actionPending: boolean; onCommentAction: ( body: string, @@ -180,6 +183,7 @@ export function PullRequestComposer({ active={open && mode === "review"} environmentId={environmentId} reference={reference} + headSha={shownHeadSha} completionScope={pullRequestCompletionScope(detail, environmentId, reference)} term={term} verdicts={verdicts} @@ -193,6 +197,8 @@ export function PullRequestComposer({ setOpen(false); onReviewSubmitted(); }} + // A refusal usually means new commits, so show what the host has now. + onRefused={onReviewSubmitted} /> ) : null} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx index 74a755927854e..e7a4733ae9410 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx @@ -7,12 +7,13 @@ import { type PullRequestDetailView, } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import appCss from "~/index.css?inline"; import { DraftId, useComposerDraftStore } from "~/composerDraftStore"; import { act, fakeTimers, render } from "../../../test/render"; -const { permissions, reads, shown } = vi.hoisted(() => ({ +const { command, permissions, reads, shown } = vi.hoisted(() => ({ + command: vi.fn(), permissions: { checkout: true, operate: true }, reads: { diff: [] as unknown[] }, shown: { detail: null as PullRequestDetailView | null }, @@ -70,7 +71,7 @@ vi.mock(import("~/state/pullRequests"), async (original) => { }); vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), - useAtomCommand: (() => vi.fn()) as never, + useAtomCommand: (() => command) as never, })); import { createWorkspaceFocusController, workspaceAreaProps } from "~/lib/workspaceFocus"; @@ -153,6 +154,7 @@ function setup() { permissions.operate = true; reads.diff = []; shown.detail = detail; + command.mockReset(); useComposerDraftStore.setState({ draftsByThreadKey: {} }); } @@ -183,6 +185,49 @@ it("can still add conflict resolution to an existing composer without checkout s expect(draft?.prompt).toContain(detail.url); }); +it("keeps a merge and a review on the head the reader was shown until they load new commits", async () => { + setup(); + command.mockResolvedValue({ _tag: "Success", value: undefined }); + const at = (headSha: string): PullRequestDetailView => ({ + ...detail, + headSha, + mergeability: "mergeable", + mergeCapabilities: { merge: false, squash: true, rebase: false }, + capabilities: { + ...detail.capabilities, + actions: ["merge"], + mergeMethods: ["squash"], + review: { ...detail.capabilities.review, verdicts: ["approve"] }, + }, + viewerPermissions: { ...detail.viewerPermissions, actions: ["merge"], verdicts: ["approve"] }, + }); + const sent = (key: "action" | "verdict") => + command.mock.calls.flatMap(([call]) => + call?.input?.[key] === undefined ? [] : [call.input.expectedHeadSha], + ); + const merge = async () => { + await screen.getByRole("button", { name: "Squash and merge" }).click(); + await screen.getByRole("button", { name: "Confirm merge?" }).click(); + }; + shown.detail = at("shown-head"); + await using screen = await render(panel()); + await expect.element(screen.getByRole("button", { name: "Squash and merge" })).toBeVisible(); + // A background refresh brings a push the reader has not looked at. + shown.detail = at("pushed-head"); + await screen.rerender(panel()); + await expect.element(screen.getByText(/still applies to shown-h/)).toBeVisible(); + await merge(); + await screen.getByRole("button", { name: "Review pull request" }).click(); + // The composer popup is portalled outside the rendered tree. + await page.getByRole("button", { name: "Submit review" }).click(); + await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"])); + expect(sent("action")).toEqual(["shown-head"]); + + await screen.getByRole("button", { name: "Load new commits" }).click(); + await merge(); + await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "pushed-head"])); +}); + it("reads the first diff page once the pointer rests on the Code tab", async () => { setup(); await using screen = await render(panel()); diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e14ab19d9012..110aac26cde5c 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -36,6 +36,7 @@ import { GitCommitHorizontalIcon, MessageSquareIcon, PanelRightIcon, + TriangleAlertIcon, } from "lucide-react"; import { lazy, @@ -83,6 +84,7 @@ import { vcsEnvironment } from "~/state/vcs"; import { RelativeTime } from "~/components/RelativeTime"; import { useUiStateStore } from "~/uiStateStore"; +import { Alert, AlertAction, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; @@ -139,6 +141,8 @@ import { pullRequestHandoffLabels, PULL_REQUEST_MERGE_METHOD_LABELS, checkoutFailureDescription, + mergeHeadPin, + seenPullRequestHead, readableFailure, resolvePullRequestReferenceHost, resolvePullRequestPrimaryControl, @@ -709,6 +713,20 @@ export function PullRequestDetailPanel({ nativeStackQuery.refresh(); }; const [refreshToken, setRefreshToken] = useState(0); + const seenHeadKey = `${environmentId}:${pullRequestKey}`; + const [storedSeenHead, setSeenHead] = useState | null>( + null, + ); + // A stored answer paints first, so only a settled read counts as shown. + const seenHead = seenPullRequestHead( + storedSeenHead, + seenHeadKey, + detailQuery.isPending ? undefined : detail?.headSha, + ); + if (seenHead !== storedSeenHead) setSeenHead(seenHead); + const shownHeadSha = seenHead.sha ?? detail?.headSha; + const unseenHeadSha = + detail?.state === "open" && detail.headSha !== shownHeadSha ? detail.headSha : undefined; const [activityRevision, setActivityRevision] = useState<{ readonly key: string; readonly updatedAt: string; @@ -867,6 +885,7 @@ export function PullRequestDetailPanel({ input: { ...reference, action, + ...mergeHeadPin(action, shownHeadSha), ...(method ? { mergeMethod: method } : {}), ...(updateMethod ? { updateMethod } : {}), }, @@ -884,6 +903,8 @@ export function PullRequestDetailPanel({ title: actionFailureLabels(changeRequestTermKind(terminology))[action], description: readableFailure(failure, hint), }); + // A refused merge usually means new commits, so show what the host has now. + if (action === "merge" || action === "enable-auto-merge") refreshDetail(); onActed?.(action, "failed"); return false; } @@ -1603,6 +1624,7 @@ export function PullRequestDetailPanel({ onRetry={nativeStackQuery.error ? nativeStackQuery.refresh : undefined} reference={reference} environmentId={environmentId} + shownHeadSha={shownHeadSha} onSelect={onSelectPullRequest} mergeMethod={selectedMergeMethod} stale={!nativeStackQuery.isFresh} @@ -1896,6 +1918,30 @@ export function PullRequestDetailPanel({ + {unseenHeadSha !== undefined && shownHeadSha !== undefined ? ( +
+ + + + {gt("New commits were pushed. A merge or review still applies to {sha}.", { + sha: shownHeadSha.slice(0, 7), + })} + + + + + +
+ ) : null} {detail ? ( , ); await screen.getByRole("button", { name: "Submit review" }).click(); @@ -52,7 +54,11 @@ it("submits only the line comments still in the draft when dictation finishes", await act(() => mocks.queue.mock.calls[0]![0]("Dictated summary")); expect(mocks.submit).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ body: "Dictated summary", comments: [] }), + input: expect.objectContaining({ + body: "Dictated summary", + comments: [], + expectedHeadSha: "reviewed-head", + }), }), ); }); diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx index d581c6c9e2f06..6cedcd7a1d492 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx @@ -63,6 +63,7 @@ export function PullRequestReviewForm({ environmentId, active, reference, + headSha, completionScope, term, verdicts, @@ -71,11 +72,14 @@ export function PullRequestReviewForm({ pending, onPendingChange, onSubmitted, + onRefused, }: { environmentId: EnvironmentId; /** False while the form stays mounted but hidden; dictation is cancelled then. */ active: boolean; reference: PullRequestRef; + /** The head on screen, which the review is pinned to. */ + headSha: string | undefined; completionScope: PullRequestCompletionScope | null; term: ChangeRequestTermKind; verdicts: ReadonlyArray; @@ -84,6 +88,7 @@ export function PullRequestReviewForm({ pending: boolean; onPendingChange: (pending: boolean) => void; onSubmitted: () => void; + onRefused: () => void; }) { const gt = useGT(); const resolve = useMessages(); @@ -125,6 +130,7 @@ export function PullRequestReviewForm({ environmentId, input: { ...reference, + ...(headSha === undefined ? {} : { expectedHeadSha: headSha }), verdict: verdict.value, body: submittedBody, comments: submittedComments, @@ -140,6 +146,7 @@ export function PullRequestReviewForm({ m(msg("The host refused the review. Your draft is still here to try again.")), ), }); + onRefused(); return; } // Preserve comments and summary edits made during submission. diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx index 2aed048ba9662..2d75923260bf5 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx @@ -3,17 +3,19 @@ import { EnvironmentId, ProjectId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; -const state = vi.hoisted(() => ({ detail: "" })); +const state = vi.hoisted(() => ({ detail: "", sent: [] as unknown[] })); vi.mock(import("~/state/use-atom-command"), async () => { const { PullRequestOperationError } = await import("@t3tools/contracts"); const { Cause } = await import("effect"); const { AsyncResult } = await import("effect/reactivity"); return { - useAtomCommand: (() => async () => - AsyncResult.failure( + useAtomCommand: (() => async (call: { readonly input: unknown }) => { + state.sent.push(call.input); + return AsyncResult.failure( Cause.fail(new PullRequestOperationError({ operation: "runAction", detail: state.detail })), - )) as never, + ); + }) as never, }; }); @@ -24,6 +26,7 @@ import { PullRequestStackMenu } from "./PullRequestStackMenu"; function setup(detail: string) { state.detail = detail; + state.sent = []; } const HEAD_MOVED = "The stack head moved. Refresh the stack before trying again."; @@ -58,6 +61,7 @@ it.each([ layers: [{ number: 2, headBranch: "feature", headSha: "abc123", state: "open" }], }} canMerge + shownHeadSha="shown" stale={false} canRebase mergeMethod="squash" @@ -73,4 +77,13 @@ it.each([ } await page.getByRole("dialog").getByRole("button", { name: row.label, exact: true }).click(); await expect.element(page.getByText(row.description, { exact: true })).toBeInTheDocument(); + // The stack's own read can be ahead of the head the reader was shown; a merge lands only that one. + expect(state.sent).toEqual([ + expect.objectContaining( + row.label === "Merge stack" + ? { expectedHeadSha: "shown", expectedStackHeads: [{ number: 2, headSha: "abc123" }] } + : { action: "update-branch" }, + ), + ]); + if (row.label !== "Merge stack") expect(state.sent[0]).not.toHaveProperty("expectedHeadSha"); }); diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx index e2300578f4b76..1a1eb33c42254 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx @@ -30,7 +30,7 @@ import { PullRequestStackLayers } from "./PullRequestStackLayers"; import { PullRequestStackHeader } from "./PullRequestStackHeader"; import { PullRequestStackLayerContent } from "./PullRequestStackLayerContent"; import { PullRequestGlyph } from "./pullRequestIcons"; -import { readableFailure } from "./pullRequestDetail.logic"; +import { mergeHeadPin, readableFailure } from "./pullRequestDetail.logic"; import { changeRequestTermKind } from "./changeRequestTerm"; @@ -40,6 +40,7 @@ export function PullRequestStackMenu({ stack, reference, environmentId, + shownHeadSha, stale, canMerge, canRebase, @@ -56,6 +57,8 @@ export function PullRequestStackMenu({ stack: PullRequestStack; reference: PullRequestRef; environmentId: EnvironmentId; + /** The head of `reference` the reader was shown; the stack read can run ahead of it. */ + shownHeadSha: string | undefined; stale: boolean; canMerge: boolean; canRebase: boolean; @@ -115,6 +118,7 @@ export function PullRequestStackMenu({ number: target.number, stackNumber: stack.number, expectedStackHeads: actionHeads, + ...mergeHeadPin(action, shownHeadSha), action, ...(action === "merge" ? { mergeMethod } : { updateMethod: "rebase" }), }, diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 3d0ae22b15017..a71bc0d2db367 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -60,6 +60,7 @@ import { pullRequestLinkSubject, writePullRequestDetailSnapshot, readableFailure, + seenPullRequestHead, } from "./pullRequestDetail.logic"; import type { ReviewCommentContext } from "~/reviewCommentContext"; @@ -2058,6 +2059,19 @@ describe("single-PR merge compatibility during stack discovery", () => { ); }); +describe("seenPullRequestHead", () => { + it("takes the first settled head and keeps it until another pull request is shown", () => { + // A stored answer paints before the read settles, and is not what the reader ends up seeing. + const loading = seenPullRequestHead(null, "pr-1", undefined); + expect(loading).toEqual({ key: "pr-1", sha: undefined }); + const seen = seenPullRequestHead(loading, "pr-1", "a"); + expect(seen).toEqual({ key: "pr-1", sha: "a" }); + expect(seenPullRequestHead(seen, "pr-1", "b")).toBe(seen); + expect(seenPullRequestHead(seen, "pr-1", undefined)).toBe(seen); + expect(seenPullRequestHead(seen, "pr-2", "c")).toEqual({ key: "pr-2", sha: "c" }); + }); +}); + describe("readableFailure", () => { it("replaces a host tool's bare failure with the hint, for every host", () => { for (const message of [ diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index d98ec3ff114ec..ad9285f6fc322 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -1543,6 +1543,27 @@ const TOOL_NOISE = [ const FAILURE_DETAIL_MAX_LENGTH = 320; +/** + * The head a reader was first shown. A background refresh does not move it, so a merge or review + * keeps applying to the commits they read until they load the newer ones. + */ +export function seenPullRequestHead( + seen: { readonly key: string; readonly sha: string | undefined } | null, + key: string, + settledHead: string | undefined, +) { + return seen !== null && seen.key === key && (seen.sha !== undefined || settledHead === undefined) + ? seen + : { key, sha: settledHead }; +} + +/** A merge lands the head the reader was shown, so it refuses a head that moved since. */ +export function mergeHeadPin(action: PullRequestAction, headSha: string | undefined) { + return (action === "merge" || action === "enable-auto-merge") && headSha !== undefined + ? { expectedHeadSha: headSha } + : {}; +} + export function readableFailure(failure: unknown, hint: string): string { const raw = failure instanceof Error ? failure.message : typeof failure === "string" ? failure : ""; diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 79089c0a858c6..4b62dd0ae3266 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -35,6 +35,7 @@ function MergeButton({ reference }: { reference: PullRequestRef }) { const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, + headSha: `head-${reference.number}`, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( @@ -81,6 +82,11 @@ it("keeps pending merges with their pull request when navigating between threads await expect.element(button).toBeEnabled(); await userEvent.click(button); expect(state.runAction).toHaveBeenCalledTimes(2); + // Each merge is pinned to the head its own row showed. + expect(state.runAction.mock.calls.map(([call]) => call.input.expectedHeadSha)).toEqual([ + "head-1", + "head-2", + ]); await screen.rerender(); await expect.element(button).toHaveTextContent("Merging..."); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index f7885e098d3c3..3c016af497c0f 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -44,6 +44,7 @@ import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast"; import { checkoutFailureDescription, appendHandoff, + mergeHeadPin, readableFailure, } from "./pullRequestDetail.logic"; import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic"; @@ -187,12 +188,17 @@ const actionFailureHints = (term: ChangeRequestTermKind): Record void; terminology: ChangeRequestTerminology; onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void; /** Resolve repository settings on click to avoid per-row reads. */ @@ -227,6 +233,7 @@ export function usePullRequestActionRunner({ input: { ...reference, action, + ...mergeHeadPin(action, headSha), ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}), }, }); @@ -241,6 +248,7 @@ export function usePullRequestActionRunner({ actionFailureHints(changeRequestTermKind(terminology))[action], ), }); + onFailure?.(action); return; } toastManager.add({ diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3fe4a8bfabb00..761473fabb358 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Checkout-Befehl kopiert", "d2970574ef7860d0": "{term, select, mr {Branch des Merge Requests kopieren} cr {Branch der Änderungsanfrage kopieren} other {Branch des Pull Requests kopieren}}", "45c92416a82cf22c": "Branch-Name kopiert", + "43a18c0bc37988f4": "Neue Commits wurden gepusht. Ein Merge oder Review gilt weiterhin für {sha}.", + "c930a7ffa49054f0": "Neue Commits laden", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Kommentare nicht verfügbar", "95601ce075194611": "{count, plural, one {{formatted} Kommentar} other {{formatted} Kommentare}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f03dc33bf1fb8..2764010f88414 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -6843,6 +6843,8 @@ "45674081908ac8aa": "Checkout command copied", "d2970574ef7860d0": "Copy {term, select, mr {merge request} cr {change request} other {pull request}} branch", "45c92416a82cf22c": "Branch name copied", + "43a18c0bc37988f4": "New commits were pushed. A merge or review still applies to {sha}.", + "c930a7ffa49054f0": "Load new commits", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Comments unavailable", "95601ce075194611": "{count, plural, one {{formatted} comment} other {{formatted} comments}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index a701345663865..f7bd7ecb09588 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar la rama de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "45c92416a82cf22c": "Nombre de la rama copiado", + "43a18c0bc37988f4": "Se enviaron nuevos commits. Una fusión o revisión sigue aplicándose a {sha}.", + "c930a7ffa49054f0": "Cargar nuevos commits", "63e533a9db74e8dc": "Comprobaciones", "4f7ca990d538a8bc": "Comentarios no disponibles", "95601ce075194611": "{count, plural, one {{formatted} comentario} other {{formatted} comentarios}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index df68cc6cb7438..209553a0cda86 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -6837,6 +6837,8 @@ "45674081908ac8aa": "Commande de checkout copiée", "d2970574ef7860d0": "Copier la branche de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "45c92416a82cf22c": "Nom de la branche copié", + "43a18c0bc37988f4": "De nouveaux commits ont été poussés. Une fusion ou une revue s’applique toujours à {sha}.", + "c930a7ffa49054f0": "Charger les nouveaux commits", "63e533a9db74e8dc": "Vérifications", "4f7ca990d538a8bc": "Commentaires indisponibles", "95601ce075194611": "{count, plural, one {{formatted} commentaire} other {{formatted} commentaires}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 3752913600c78..c9e97b9e3f263 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -6806,6 +6806,8 @@ "45674081908ac8aa": "チェックアウトコマンドをコピーしました", "d2970574ef7860d0": "{term, select, mr {マージリクエストのブランチをコピー} cr {変更リクエストのブランチをコピー} other {プルリクエストのブランチをコピー}}", "45c92416a82cf22c": "ブランチ名をコピーしました", + "43a18c0bc37988f4": "新しいコミットがプッシュされました。マージやレビューは引き続き {sha} に適用されます。", + "c930a7ffa49054f0": "新しいコミットを読み込む", "63e533a9db74e8dc": "チェック", "4f7ca990d538a8bc": "コメントを利用できません", "95601ce075194611": "{count, plural, other {{formatted} 件のコメント}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c327226d81e4c..7d528f7527d27 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -6810,6 +6810,8 @@ "45674081908ac8aa": "체크아웃 명령 복사됨", "d2970574ef7860d0": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 브랜치 복사", "45c92416a82cf22c": "브랜치 이름 복사됨", + "43a18c0bc37988f4": "새 커밋이 푸시되었습니다. 병합이나 리뷰는 여전히 {sha}에 적용됩니다.", + "c930a7ffa49054f0": "새 커밋 불러오기", "63e533a9db74e8dc": "검사", "4f7ca990d538a8bc": "댓글을 사용할 수 없음", "95601ce075194611": "{count, plural, other {댓글 {formatted}개}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 36d5130814b0a..33e0262600d4a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar o branch {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}", "45c92416a82cf22c": "Nome do branch copiado", + "43a18c0bc37988f4": "Novos commits foram enviados. Um merge ou uma revisão ainda se aplica a {sha}.", + "c930a7ffa49054f0": "Carregar novos commits", "63e533a9db74e8dc": "Verificações", "4f7ca990d538a8bc": "Comentários indisponíveis", "95601ce075194611": "{count, plural, one {{formatted} comentário} other {{formatted} comentários}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 34d4295aa74d4..a93a2ce219ea2 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Команда checkout скопирована", "d2970574ef7860d0": "{term, select, mr {Копировать ветку мерж-реквеста} cr {Копировать ветку запроса на изменение} other {Копировать ветку пул-реквеста}}", "45c92416a82cf22c": "Имя ветки скопировано", + "43a18c0bc37988f4": "Отправлены новые коммиты. Слияние или ревью по-прежнему относится к {sha}.", + "c930a7ffa49054f0": "Загрузить новые коммиты", "63e533a9db74e8dc": "Проверки", "4f7ca990d538a8bc": "Комментарии недоступны", "95601ce075194611": "{count, plural, one {{formatted} комментарий} few {{formatted} комментария} many {{formatted} комментариев} other {{formatted} комментария}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 8b26904ba4a54..2b15a6570f9ab 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -6842,6 +6842,8 @@ "45674081908ac8aa": "Utcheckningskommandot kopierades", "d2970574ef7860d0": "Kopiera grenen för {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}", "45c92416a82cf22c": "Grennamnet kopierades", + "43a18c0bc37988f4": "Nya commits har pushats. En merge eller granskning gäller fortfarande {sha}.", + "c930a7ffa49054f0": "Läs in nya commits", "63e533a9db74e8dc": "Kontroller", "4f7ca990d538a8bc": "Kommentarer är inte tillgängliga", "95601ce075194611": "{count, plural, one {{formatted} kommentar} other {{formatted} kommentarer}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cc9e902308327..fc0cbe1297c4f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -6849,6 +6849,8 @@ "45674081908ac8aa": "已复制检出工作副本的命令", "d2970574ef7860d0": "复制 {term, select, mr {MR} cr {change request} other {PR}} 分支", "45c92416a82cf22c": "已复制分支名称", + "43a18c0bc37988f4": "有新的提交被推送。合并或评审仍针对 {sha}。", + "c930a7ffa49054f0": "加载新提交", "63e533a9db74e8dc": "检查", "4f7ca990d538a8bc": "评论不可用", "95601ce075194611": "{count, plural, other {{formatted} 条评论}}", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 16d8c34547a17..b014ba3357d43 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -234,6 +234,11 @@ Where you can edit a description, you can also tick its checkboxes from the Summ (the Overview tab on mobile). GitLab calls these merge requests. +A merge or review applies to the commits you opened the pull request on. When someone pushes +meanwhile, the web and desktop apps offer **Load new commits**; until you do, a merge or review is refused and your +review draft is kept. Merging from a thread's pull request row, or from the list, lands the head that +row had when you confirmed. + Save a filter setup with **Views → Save current view** on the Pull Requests page. For example, choose **Reviewing** (**Your review** on mobile) and save it as "PRs Requesting My Review". Choose a saved view to restore its search, filters, sort order, and server/project scope. After changing filters, use **Update saved view** to diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index daa8f041a2e1f..3044463eb0e2b 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -1064,6 +1064,39 @@ it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)( }), ); +it.effect("pins a quick merge to the head it judged mergeable unless the caller showed one", () => + Effect.gen(function* () { + const pinned: Array = []; + const client = { + [WS_METHODS.pullRequestsDetail]: () => + Effect.succeed({ + state: "open", + isDraft: false, + headSha: "checked-head", + capabilities: { actions: ["merge"] }, + viewerPermissions: { actions: ["merge"] }, + }), + [WS_METHODS.pullRequestsRunAction]: (input: { expectedHeadSha?: string }) => + Effect.sync(() => void pinned.push(input.expectedHeadSha)), + } as unknown as WsRpcProtocolClient; + const { atoms, registry } = yield* makeTestRuntime(client); + const input = { + projectId: ProjectId.make("project-1"), + repository: "acme/web", + number: 1, + action: "merge" as const, + resolveMergeMethod: () => "squash" as const, + }; + for (const shown of [{}, { expectedHeadSha: "shown-head" }]) { + yield* atoms.runAction.run(registry, { + environmentId: TARGET.environmentId, + input: { ...input, ...shown }, + }); + } + expect(pinned).toEqual(["checked-head", "shown-head"]); + }), +); + it.effect("keeps a close batch ordered and continues after a refused close", () => Effect.gen(function* () { const calls: number[] = []; diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 6ca8705a5735a..01fb80d817645 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -1132,7 +1132,14 @@ export function createPullRequestEnvironmentAtoms( detail: cause instanceof Error ? cause.message : "Could not choose a merge method.", }), }); - preparedInput = { ...actionInput, mergeMethod }; + // Without a head the caller showed, pin to the one this read judged mergeable. + preparedInput = { + ...actionInput, + mergeMethod, + ...(actionInput.expectedHeadSha === undefined && detail.headSha !== undefined + ? { expectedHeadSha: detail.headSha } + : {}), + }; } return yield* routedRequest(WS_METHODS.pullRequestsRunAction, { ...preparedInput, diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 0771055de4de4..3318ae3cdcb58 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -916,6 +916,8 @@ export type PullRequestReviewCommentDraft = typeof PullRequestReviewCommentDraft export const PullRequestSubmitReviewInput = Schema.Struct({ ...PullRequestRef.fields, + /** Reviews refuse when the head commit is no longer this one. */ + expectedHeadSha: Schema.optional(TrimmedNonEmptyString), verdict: PullRequestReviewVerdict, body: Schema.String.check(Schema.isMaxLength(65_536)), comments: Schema.Array(PullRequestReviewCommentDraft), diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index fffa0feb4014b..ec6ae07b5d5d6 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -615,6 +615,8 @@ export interface PullRequestProviderApi { readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + /** Hosts that can pin a review to a head commit do; the caller has already checked it. */ + readonly expectedHeadSha?: string; }, ) => Effect.Effect; diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts index e6c8a47a922ee..ae96a89eb805b 100644 --- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts @@ -622,7 +622,7 @@ export const make = Effect.gen(function* () { ? "REQUEST_CHANGES" : "COMMENT", body: input.body, - commit_id: pr.head.sha, + commit_id: input.expectedHeadSha ?? pr.head.sha, comments: input.comments.map((comment) => { const position = comment.position; const old = diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index 37108af262b7a..5dbc797ff4386 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -1349,7 +1349,7 @@ export const make = Effect.gen(function* () { body: { verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict, ...(input.body.length === 0 ? {} : { body: input.body }), - commitOid: pull.headOid, + commitOid: input.expectedHeadSha ?? pull.headOid, expectedVersion: pull.version, requestId: yield* randomUuidV4, }, diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 0f6b76dd5040c..0ae73bcde3891 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -811,6 +811,7 @@ export class GitHubPullRequestApi extends Context.Service< readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + readonly expectedHeadSha?: string; }) => Effect.Effect; readonly replyToReviewThread: (input: { @@ -3119,6 +3120,7 @@ export const make = Effect.gen(function* () { verdict: input.verdict, body: input.body, comments: input.comments, + expectedHeadSha: input.expectedHeadSha, }), }) .pipe(Effect.asVoid); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index e049943a3978f..cd26dcf2d4a5b 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -1644,6 +1644,7 @@ describe("review submission payload", () => { const payload = buildReviewSubmission({ verdict: "request-changes", body: "Two things.", + expectedHeadSha: "0a1b2c3d4e5f", comments: [ { path: "src/a.ts", @@ -1658,6 +1659,7 @@ describe("review submission payload", () => { ], }); expect(payload).toEqual({ + commit_id: "0a1b2c3d4e5f", event: "REQUEST_CHANGES", body: "Two things.", comments: [ diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 9eed567a6a4da..08ba8fd8b241f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -285,6 +285,8 @@ export function isSubjectOfPullRequest(result: PullRequestSubject.Result): boole } const ReviewSubmissionSchema = Schema.Struct({ + /** Without it GitHub records the review against whatever the head is when it arrives. */ + commit_id: Schema.optional(Schema.String), event: Schema.Literals(["COMMENT", "APPROVE", "REQUEST_CHANGES"]), body: Schema.String, comments: Schema.Array( @@ -325,8 +327,10 @@ export function buildReviewSubmission(input: { readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + readonly expectedHeadSha?: string | undefined; }): typeof ReviewSubmissionSchema.Type { return { + ...(input.expectedHeadSha === undefined ? {} : { commit_id: input.expectedHeadSha }), event: REVIEW_EVENTS[input.verdict], body: input.body, comments: input.comments.map((comment) => { From 46f360d8dde801b78e9788c2ea3084bdc7b933a0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:12:07 -0800 Subject: [PATCH 215/288] fix(client): a link to a newly linked machine's thread opens without a reload (#41722) --- .../src/features/threads/ThreadFeed.tsx | 22 +++++- apps/mobile/src/state/linkedThread.ts | 16 ++-- apps/mobile/src/state/peerLinks.ts | 27 +++++-- .../src/components/chat/LinkedThreadPage.tsx | 4 +- .../components/chat/MarkdownThreadLink.tsx | 1 + apps/web/src/state/linkedThreadView.ts | 5 +- apps/web/src/state/peerLinks.ts | 13 +++- .../src/state/peerLinks.test.ts | 76 +++++++++++++++++++ .../client-runtime/src/state/peerLinks.ts | 17 +++++ 9 files changed, 160 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index e2d5c141a479d..c24b70c575139 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -84,7 +84,12 @@ import { } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { + hasThreadLinks, + hostedThreadLink, + parseThreadLinkHref, + threadLinkRefs, +} from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; import { parseComposerContextHref, @@ -339,6 +344,11 @@ import { } from "./threadFeedEndFollow"; import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; +const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) => + hasThreadLinks(markdown) + ? threadLinkRefs(markdown, environmentId).map((ref) => ref.environmentId) + : []; + const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. includeBlockquotes: Platform.OS === "ios", @@ -1311,7 +1321,10 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const liveMarkdown = useLiveThreadLinkLabels( props.markdown, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.markdown) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.markdown, props.environmentId), + ), ); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; @@ -2746,7 +2759,10 @@ function UserMessageContent(props: UserMessageContentProps) { const liveText = useLiveThreadLinkLabels( props.text, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.text) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.text, props.environmentId), + ), ); const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records); const text = replaceComposerContextReferences(liveText, (ref) => { diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index ff4c75b9ac1ac..8a0adc790940e 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -27,16 +27,14 @@ export function useLinkedThreadReach( const own = presentationById.get(id); return own && { connected: own.connection.phase === "connected" }; }; - const links = useLinkedEnvironments( - subagents.some( - (subagent) => - subagent.childThreadId === null && - subagent.remoteChild !== undefined && - ownConnection(subagent.remoteChild.environmentId)?.connected !== true, - ) - ? environmentId - : null, + const remote = subagents.flatMap((subagent) => + subagent.childThreadId === null && + subagent.remoteChild !== undefined && + ownConnection(subagent.remoteChild.environmentId)?.connected !== true + ? [subagent.remoteChild.environmentId] + : [], ); + const links = useLinkedEnvironments(remote.length > 0 ? environmentId : null, remote); return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; } diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index 40a13f2150234..ae403a4e72068 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { linkableMachines, linkedEnvironmentNames, @@ -6,7 +6,7 @@ import { } from "@t3tools/client-runtime/link-request"; import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect, useEffectEvent, useMemo } from "react"; +import { useContext, useEffect, useEffectEvent, useMemo } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; import { useEnvironments } from "./environments"; @@ -19,19 +19,36 @@ export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtom /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. * Its agents can read threads there, and so can a client allowed to read threads on it. + * A `wanted` machine this app is not connected to and the names lack makes them reread. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, + wanted: ReadonlyArray = [], ): ReadonlyMap { const { environments } = useEnvironments(); const offered = offersLinkedEnvironments( environments.find((environment) => environment.environmentId === environmentId)?.serverConfig, ); + const queried = offered ? environmentId : null; const links = useEnvironmentQuery( - offered && environmentId !== null - ? peerLinkEnvironment.names({ environmentId, input: {} }) - : null, + queried === null ? null : peerLinkEnvironment.names({ environmentId: queried, input: {} }), ); + const connected = new Set( + environments + .filter((environment) => environment.connection.phase === "connected") + .map((environment) => environment.environmentId), + ); + const missing = [...new Set(wanted)].filter((id) => id !== environmentId && !connected.has(id)); + const refreshKey = + queried === null || missing.length === 0 ? "" : [queried, ...[...missing].sort()].join(" "); + const registry = useContext(RegistryContext); + const refreshLacking = useEffectEvent(() => { + if (queried !== null) peerLinkEnvironment.refreshNamesLacking(registry, queried, missing); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this app are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (refreshKey !== "") refreshLacking(); + }, [refreshKey]); return useMemo( () => linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments }), [environments, links.data, offered], diff --git a/apps/web/src/components/chat/LinkedThreadPage.tsx b/apps/web/src/components/chat/LinkedThreadPage.tsx index 08d216a212650..0749f199083ee 100644 --- a/apps/web/src/components/chat/LinkedThreadPage.tsx +++ b/apps/web/src/components/chat/LinkedThreadPage.tsx @@ -26,7 +26,9 @@ export function LinkedThreadPage(props: { const gt = useGT(); const own = useEnvironment(environmentId); const connected = own?.connection.phase === "connected"; - const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId).get(environmentId); + const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId, environmentId).get( + environmentId, + ); if (connected) { return ( { const offered = useAtomValue( environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId), @@ -56,6 +58,13 @@ export function useLinkedEnvironments( ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); + const registry = useContext(RegistryContext); + const queried = offered ? environmentId : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this client are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (queried === null || wanted === undefined) return; + peerLinkEnvironment.refreshNamesLacking(registry, queried, [wanted]); + }, [registry, queried, wanted]); return linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments: identities, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index dd39162df8a4c..ce4d267aaef18 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -18,9 +18,16 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { TestClock } from "effect/testing"; +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type PreparedConnection, + type SupervisorConnectionState, +} from "../connection/model.ts"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import type { LinkedThreadView } from "../linkedThread.ts"; +import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; @@ -191,3 +198,72 @@ describe("linkThroughRoutes", () => { ]); }); }); + +describe("refreshNamesLacking", () => { + // regression: #41707 a link made outside this client stayed unknown while the names were read + it.effect("rereads fresh names that lack a wanted machine, once per miss", () => + Effect.gen(function* () { + const target = new PrimaryConnectionTarget({ + environmentId: id("via"), + label: "Via", + httpBaseUrl: "https://via.example.test", + wsBaseUrl: "wss://via.example.test", + }); + let stored = [{ environmentId: id("known"), label: "Known" }]; + let reads = 0; + const client = { + [WS_METHODS.peerLinksNames]: () => + Effect.sync(() => { + reads += 1; + return { links: stored }; + }), + } as unknown as WsRpcProtocolClient; + const session = { client } as unknown as RpcSession; + const supervisor = EnvironmentSupervisor.of({ + target, + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected", + }), + session: yield* SubscriptionRef.make(Option.some(session)), + prepared: yield* SubscriptionRef.make(Option.none()), + } as unknown as EnvironmentSupervisor["Service"]); + const environment = EnvironmentRegistry.of({ + run: (_id, effect) => Effect.provideService(effect, EnvironmentSupervisor, supervisor), + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor, supervisor), + } as EnvironmentRegistry["Service"]); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) => + Effect.sync(() => registry.dispose()), + ); + const names = links.names({ environmentId: target.environmentId, input: {} }); + registry.mount(names); + const settled = () => + AtomRegistry.toStream(registry, names).pipe( + Stream.filter((result) => AsyncResult.isSuccess(result) && !result.waiting), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + yield* settled(); + expect(reads).toBe(1); + + links.refreshNamesLacking(registry, target.environmentId, [id("known")]); + expect(reads).toBe(1); + + // Linked from the CLI or another client inside the names' stale time: the server has it, + // this client was not told. + stored = [...stored, { environmentId: id("new"), label: "New" }]; + links.refreshNamesLacking(registry, target.environmentId, [id("new")]); + // A second reader meeting the same machine joins the read under way. + links.refreshNamesLacking(registry, target.environmentId, [id("new")]); + const reread = yield* settled(); + expect(reads).toBe(2); + expect( + AsyncResult.isSuccess(reread) && reread.value.links.map((link) => link.environmentId), + ).toEqual([id("known"), id("new")]); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index a7af1ac15b4c9..3be676d3e5dc2 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -101,6 +101,23 @@ export function createPeerLinkEnvironmentAtoms( return { list, names, + /** + * Rereads `environmentId`'s link names when they lack one of `wanted`, however fresh they + * are. Links made elsewhere (the CLI, another client, a batch) are not pushed, so a reader + * that meets a machine the names lack asks once more; a read under way already answers it. + */ + refreshNamesLacking: ( + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + wanted: ReadonlyArray, + ) => { + const atom = names({ environmentId, input: {} }); + const result = registry.get(atom); + if (!AsyncResult.isSuccess(result) || result.waiting) return; + const known = new Set(result.value.links.map((link) => link.environmentId)); + if (wanted.every((id) => known.has(id))) return; + registry.refresh(atom); + }, link: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:link", tag: WS_METHODS.peerLinksLink, From eecb58c6d60cbf168b4402c47896374555b2dc6d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:12:40 -0800 Subject: [PATCH 216/288] fix: approvals and hosted pairing show what is being approved (#41769) Co-authored-by: Claude Fable 5.2 --- .../Adapters/CodexAdapterV2.test.ts | 114 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 91 +++++++++++--- apps/server/src/serverSettings.test.ts | 4 + apps/server/src/serverSettings.ts | 6 +- apps/web/src/components/ChatView.tsx | 9 +- .../auth/PairingRouteSurface.browser.test.tsx | 36 ++++++ .../components/auth/PairingRouteSurface.tsx | 67 ++++++---- apps/web/src/components/chat/ChatComposer.tsx | 7 +- .../components/chat/runtimeModeConfig.test.ts | 33 +++++ .../src/components/chat/runtimeModeConfig.ts | 25 ++++ apps/web/src/i18n/translations/de.json | 6 +- apps/web/src/i18n/translations/en.json | 6 +- apps/web/src/i18n/translations/es.json | 6 +- apps/web/src/i18n/translations/fr.json | 6 +- apps/web/src/i18n/translations/ja.json | 6 +- apps/web/src/i18n/translations/ko.json | 6 +- apps/web/src/i18n/translations/pt-BR.json | 6 +- apps/web/src/i18n/translations/ru.json | 6 +- apps/web/src/i18n/translations/sv.json | 6 +- apps/web/src/i18n/translations/zh.json | 6 +- docs/user/remote-access.md | 3 +- 21 files changed, 399 insertions(+), 56 deletions(-) create mode 100644 apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx create mode 100644 apps/web/src/components/chat/runtimeModeConfig.test.ts diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a07c3d6fe47c6..390d1f334739e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -13151,6 +13151,120 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("shows what an approval grants apart from the reason the model gave", () => + Effect.gen(function* () { + const reason = "Needed to build the project."; + const permissions = { + fileSystem: { + write: ["/w/out"], + entries: [ + { access: "write", path: { type: "path", path: "/w/out" } }, + { access: "write", path: { type: "special", value: { kind: "root" } } }, + { access: "read", path: { type: "glob_pattern", pattern: "/w/docs/**/*.md" } }, + { access: "write", path: { type: "special", value: { kind: "unknown", path: "" } } }, + ], + }, + network: { enabled: true }, + } satisfies CodexSchema.PermissionsRequestApprovalParams["permissions"]; + const request = ( + id: number, + method: string, + params: Record, + result: Record, + ): Array => [ + { + type: "emit_inbound", + label: method, + frame: { + id, + method, + params: { threadId: nativeThreadId, turnId: nativeTurnId, startedAtMs: 2, ...params }, + }, + }, + { type: "expect_outbound", label: method, frame: { id, result } }, + ]; + const manyFiles = Array.from({ length: 21 }, (_, index) => ({ + ...addA, + path: `/w/${String(index).padStart(2, "0")}.ts`, + })); + const { harness, answerNext } = yield* startApprovalTurn("approval-scope", [ + ...request( + 0, + "item/permissions/requestApproval", + { itemId: "permissions", cwd: "/w", reason, permissions }, + { permissions, scope: "turn" }, + ), + ...request( + 1, + "item/commandExecution/requestApproval", + { + itemId: "command", + cwd: "/w/app", + reason, + command: "pnpm install", + networkApprovalContext: { host: "example.com", protocol: "https" }, + }, + { decision: "accept" }, + ), + fileChange("started", nativeTurnId, "patch", manyFiles), + ...request( + 2, + "item/fileChange/requestApproval", + { itemId: "patch", reason, grantRoot: "/w" }, + { decision: "accept" }, + ), + fileChange("completed", nativeTurnId, "patch", manyFiles), + ...request( + 3, + "execCommandApproval", + { + callId: "legacy", + conversationId: nativeThreadId, + command: ["pnpm", "run", "build"], + cwd: "/w/app", + parsedCmd: [], + reason, + }, + { decision: "approved" }, + ), + turnCompleted(nativeTurnId), + ]); + const requests = [ + yield* answerNext, + yield* answerNext, + yield* answerNext, + yield* answerNext, + ]; + yield* harness.firstTerminal; + + assert.deepEqual( + requests.map((pending) => { + const item = approvalItem(harness.events, pending); + return [item?.prompt, item?.reason]; + }), + [ + [ + "write /w/out\nwrite / (entire filesystem)\nread /w/docs/**/*.md\nwrite unknown path\nnetwork", + reason, + ], + ["pnpm install\ncwd /w/app\nnetwork https example.com", reason], + [[...manyFiles.map((file) => `add ${file.path}`), "write /w"].join("\n"), reason], + ["pnpm run build\ncwd /w/app", reason], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("classifies permission requests that only list sandbox entries", () => Effect.gen(function* () { const permissionRequest = ( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 6ec6d44ef0b6b..c7a7343d515fe 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -209,25 +209,74 @@ function codexMultiFilePatch( .join(""); } +// The prompt states the operation being approved; Codex's `reason` goes to the item's `reason`. function codexFileChangeApprovalPrompt(input: { - readonly reason?: string | null; readonly grantRoot?: string | null; readonly fileChanges?: CodexFileChangeKinds; }): string | undefined { - const reason = input.reason?.trim(); - if (reason) return reason; const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) => left.localeCompare(right), ); - if (entries.length > 0) { - const described = entries.slice(0, 20).map(([path, change]) => { - const movePath = change.type === "update" ? change.move_path : undefined; - return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; - }); - const remaining = entries.length - described.length; - return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n"); + // The card scrolls, so every path is listed. + const described = entries.map(([path, change]) => { + const movePath = change.type === "update" ? change.move_path : undefined; + return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; + }); + const grantRoot = input.grantRoot?.trim(); + return [...described, ...(grantRoot ? [`write ${grantRoot}`] : [])].join("\n") || undefined; +} + +function codexCommandApprovalPrompt( + input: Pick< + CodexSchema.CommandExecutionRequestApprovalParams, + "command" | "cwd" | "networkApprovalContext" + >, +): string | undefined { + const network = input.networkApprovalContext; + return ( + [ + ...(input.command?.trim() ? [input.command] : []), + ...(input.cwd?.trim() ? [`cwd ${input.cwd}`] : []), + ...(network ? [`network ${network.protocol} ${network.host}`] : []), + ].join("\n") || undefined + ); +} + +function codexFileSystemPathLabel( + path: CodexSchema.PermissionsRequestApprovalParams__FileSystemPath, +): string { + if (path.type === "path") return path.path; + if (path.type === "glob_pattern") return path.pattern; + const special = path.value; + switch (special.kind) { + case "root": + return "/ (entire filesystem)"; + case "slash_tmp": + return "/tmp"; + case "tmpdir": + return "temporary directory"; + case "minimal": + return "minimal system paths"; + case "project_roots": + return ["project roots", special.subpath].filter(Boolean).join("/"); + case "unknown": + return [special.path, special.subpath].filter(Boolean).join("/") || "unknown path"; } - return input.grantRoot?.trim() || undefined; +} + +function codexPermissionsApprovalPrompt( + permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"], +): string | undefined { + // Codex may list a path both in the legacy `read`/`write` lists and in `entries`. + const lines = new Set(); + for (const access of ["read", "write"] as const) { + for (const path of permissions.fileSystem?.[access] ?? []) lines.add(`${access} ${path}`); + } + for (const entry of permissions.fileSystem?.entries ?? []) { + lines.add(`${entry.access} ${codexFileSystemPathLabel(entry.path)}`); + } + if (permissions.network?.enabled) lines.add("network"); + return [...lines].join("\n") || undefined; } export function normalizeCodexThreadLoadModelSelection(selection: ModelSelection): ModelSelection { @@ -4852,10 +4901,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly nativeRequestId: string; readonly requestKind: ProviderRequestKind; readonly prompt?: string | null; + readonly reason?: string | null | undefined; readonly appName?: string; readonly options?: ReadonlyArray; }) { const createdAt = yield* DateTime.now; + const reason = trimText(input.reason); const { owner, subagent } = approvalOwnerCodexTurn(input.context); const parentNodeId = subagent?.subagentNodeId ?? @@ -4935,6 +4986,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(input.prompt === null || input.prompt === undefined ? {} : { prompt: input.prompt }), + ...(reason === undefined ? {} : { reason }), ...(input.appName === undefined ? {} : { appName: input.appName }), ...(input.options === undefined ? {} : { options: input.options }), }; @@ -6117,9 +6169,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId, requestKind: "command", - ...((payload.reason ?? payload.command) === undefined - ? {} - : { prompt: payload.reason ?? payload.command }), + prompt: codexCommandApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6192,6 +6243,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...payload, fileChanges: context.fileChangeKindsByItem.get(payload.itemId) ?? {}, }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6254,7 +6306,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId: payload.itemId, requestKind, - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), + prompt: codexPermissionsApprovalPrompt(payload.permissions) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6405,7 +6458,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.callId, nativeRequestId, requestKind: "command", - prompt: payload.reason ?? payload.command.join(" "), + prompt: + codexCommandApprovalPrompt({ + command: payload.command.join(" "), + cwd: payload.cwd, + }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6474,6 +6532,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeRequestId: payload.callId, requestKind: "file-change", prompt: codexFileChangeApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 5d46c916c3990..e8efe5d2f91bc 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -2425,6 +2425,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" assert.isFalse(settings.projectSettingsFolded); assert.isFalse(settings.continueThreadsAfterServerUpdate); assert.equal(settings.usageHistoryRetentionDays, "unlimited"); + assert.isTrue(settings.requireConnectDeviceApproval); + assert.isFalse(settings.enablePreviewTunnel); + assert.isFalse(settings.enableAgentBrowserAccess); + assert.equal(settings.defaultRuntimeMode, "approval-required"); assert.deepEqual(settings.projectSettingsOverrides, {}); assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), broken); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 14a64a1aa783c..822254afcca14 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -426,11 +426,15 @@ function decodeSettingsFile( const settings: ServerSettings = Exit.isSuccess(decoded) && failure === undefined ? decoded.value - : // The file may hold an opt-out we can no longer read; never resume threads on a guess. + : // The file may hold choices we can no longer read, so opt-in behaviour stays off. { ...managed.defaults, continueThreadsAfterServerUpdate: false, usageHistoryRetentionDays: "unlimited", + requireConnectDeviceApproval: true, + enablePreviewTunnel: false, + enableAgentBrowserAccess: false, + defaultRuntimeMode: "approval-required", }; return { settings, legacy: Exit.isSuccess(legacy) ? legacy.value : undefined, failure }; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d56564f907b4b..c409788e8707c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2,6 +2,7 @@ import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { useGT, useMessages } from "gt-react"; import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; +import { draftSupportedRuntimeModes } from "./chat/runtimeModeConfig"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; @@ -4035,9 +4036,11 @@ export default function ChatView(props: ChatViewProps) { ), diff --git a/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx b/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx new file mode 100644 index 0000000000000..d740f77d8c3dc --- /dev/null +++ b/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx @@ -0,0 +1,36 @@ +import { AsyncResult } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const state = vi.hoisted(() => ({ connect: vi.fn() })); + +vi.mock("../../connection/onboarding", () => ({ connectPairing: {} })); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.connect })); +vi.mock("../../environments/primary", () => ({ + peekPairingTokenFromUrl: () => null, + stripPairingTokenFromUrl: () => undefined, + submitServerAuthCredential: () => Promise.resolve(), +})); +vi.mock("../../hostedPairing", () => ({ + readHostedPairingRequest: () => ({ host: "backend.example.com", token: "one-time", label: "" }), +})); + +import { HostedPairingRouteSurface } from "./PairingRouteSurface"; + +it("sends a link's pairing token only after the user confirms the backend", async () => { + state.connect.mockReset(); + state.connect.mockResolvedValue(AsyncResult.success(undefined)); + await using screen = await render(); + + await expect.element(screen.getByText("https://backend.example.com")).toBeVisible(); + expect(state.connect).not.toHaveBeenCalled(); + + await screen.getByRole("button", { name: "Add backend" }).click(); + await vi.waitFor(() => + expect(state.connect).toHaveBeenCalledExactlyOnceWith({ + host: "backend.example.com", + pairingCode: "one-time", + }), + ); +}); diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index 57a5e79241ac3..f6ec70432ad8b 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -11,6 +11,7 @@ import { submitServerAuthCredential, } from "../../environments/primary"; import { readHostedPairingRequest } from "../../hostedPairing"; +import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; @@ -146,17 +147,31 @@ export function HostedPairingRouteSurface() { reportFailure: false, }); const [request] = useState(readHostedPairingRequest); + // The origin shows the scheme along with the host. + const [origin] = useState(() => { + if (!request) return null; + try { + return new URL( + resolveRemotePairingTarget({ host: request.host, pairingCode: request.token }).httpBaseUrl, + ).origin; + } catch { + return null; + } + }); const gt = useGT(); - const [status, setStatus] = useState<"pairing" | "paired" | "error">( - request ? "pairing" : "error", + const [status, setStatus] = useState<"confirm" | "pairing" | "paired" | "error">( + origin ? "confirm" : "error", ); const [message, setMessage] = useState(() => - request - ? m(msg("Connecting to this backend.")) - : m(msg("This pairing link is missing its backend host or token.")), + origin + ? m(msg("This link adds a backend to this browser. Continue only if you trust it.")) + : request + ? m(msg("This pairing link has an invalid backend host.")) + : m(msg("This pairing link is missing its backend host or token.")), ); const [canRetry, setCanRetry] = useState(false); - const submitAttemptedRef = useRef(false); + // Nothing is sent to the link's host until the user confirms. + // The token stays in the URL until then: the root route picks this page from it. const tokenSubmittedRef = useRef(false); const submitHostedPairingRequest = async () => { @@ -180,6 +195,7 @@ export function HostedPairingRouteSurface() { setMessage(gt("Connecting to this backend.")); setCanRetry(false); tokenSubmittedRef.current = true; + stripPairingTokenFromUrl(); const result = await connectPairingEnvironment({ host: request.host, @@ -206,21 +222,6 @@ export function HostedPairingRouteSurface() { ); }; - const submitOnMount = useEffectEvent(() => { - void submitHostedPairingRequest(); - }); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits the hosted pairing request once on mount - useEffect(() => { - if (submitAttemptedRef.current) { - return; - } - submitAttemptedRef.current = true; - - stripPairingTokenFromUrl(); - submitOnMount(); - }, []); - return ( @@ -239,7 +242,7 @@ export function HostedPairingRouteSurface() { Host:{" "} - {request.host} + {origin ?? request.host} @@ -257,7 +260,23 @@ export function HostedPairingRouteSurface() { ) : null}
- {status === "pairing" ? ( + {status === "confirm" ? ( + <> + + + + ) : status === "pairing" ? ( diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 5b540f48c483e..06330d75b3cca 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,6 +6,7 @@ import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { + draftSupportedRuntimeModes, resolveCompatibleRuntimeMode, runtimeModeConfig, resolveRuntimeModeOptions, @@ -1000,7 +1001,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, - selectedProviderEntry?.snapshot.supportedRuntimeModes, + draftSupportedRuntimeModes( + selectedProviderEntry?.snapshot.supportedRuntimeModes, + multipleModelSelections, + providerStatuses, + ), ); // Modes above an administrator's ceiling stay listed, disabled with the reason. const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( diff --git a/apps/web/src/components/chat/runtimeModeConfig.test.ts b/apps/web/src/components/chat/runtimeModeConfig.test.ts new file mode 100644 index 0000000000000..580fe7e43a268 --- /dev/null +++ b/apps/web/src/components/chat/runtimeModeConfig.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { draftSupportedRuntimeModes, resolveCompatibleRuntimeMode } from "./runtimeModeConfig"; + +describe("draftSupportedRuntimeModes", () => { + const supervisedOnly = { + instanceId: "fx", + supportedRuntimeModes: ["approval-required"], + } as const; + const noAuto = { + instanceId: "muse", + supportedRuntimeModes: ["approval-required", "full-access"], + } as const; + const everyMode = { instanceId: "codex" }; + const providers = [supervisedOnly, noAuto, everyMode]; + + it.each([ + { label: "one provider that supports it", selections: [supervisedOnly, noAuto] }, + { label: "a provider that reports no modes", selections: [supervisedOnly, everyMode] }, + ])("shows Full access when a multi-model draft includes $label", ({ selections }) => { + const modes = draftSupportedRuntimeModes( + supervisedOnly.supportedRuntimeModes, + selections, + providers, + ); + expect(resolveCompatibleRuntimeMode("full-access", modes).mode).toBe("full-access"); + }); + + it("falls back only when no selected provider can run the mode", () => { + const modes = draftSupportedRuntimeModes(undefined, [supervisedOnly, noAuto], providers); + expect(resolveCompatibleRuntimeMode("auto", modes).mode).toBe("approval-required"); + }); +}); diff --git a/apps/web/src/components/chat/runtimeModeConfig.ts b/apps/web/src/components/chat/runtimeModeConfig.ts index b4f77f2ca5d62..89655258ff935 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.ts @@ -51,6 +51,31 @@ export function resolveCompatibleRuntimeMode( return { modes, mode: modes.includes(runtimeMode) ? runtimeMode : (modes[0] ?? runtimeMode) }; } +/** + * The modes a draft's send can run in. A multi-model send gives every thread the draft's mode + * and only that thread's provider narrows it, so the composer offers what any of them supports. + */ +export function draftSupportedRuntimeModes( + activeProviderModes: ReadonlyArray | undefined, + multipleModelSelections: ReadonlyArray<{ readonly instanceId: string }> | null, + providers: ReadonlyArray<{ + readonly instanceId: string; + readonly supportedRuntimeModes?: ReadonlyArray | undefined; + }>, +) { + if (multipleModelSelections === null || multipleModelSelections.length === 0) { + return activeProviderModes; + } + const supported = multipleModelSelections.map( + (selection) => + providers.find((provider) => provider.instanceId === selection.instanceId) + ?.supportedRuntimeModes ?? [], + ); + // A provider that reports no modes supports them all. + if (supported.some((modes) => modes.length === 0)) return undefined; + return runtimeModeOptions.filter((mode) => supported.some((modes) => modes.includes(mode))); +} + export function resolveRuntimeModeOption( mode: RuntimeMode, resolve: MessageResolver = m, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 761473fabb358..36f57764ea37a 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3239,7 +3239,8 @@ "49e3cf16b3ac3e5f": "Zugriff", "9699d255b374e215": "Was es tun darf", "86f5769278f5fa4d": "Über das reine Lesen hinaus kann es Threads starten, Nachrichten senden und Threads stoppen, und keiner davon kann mit mehr als dem gewählten Modus laufen.", - "693a1983e099523a": "Verbindung mit diesem Backend.", + "4f3982f640dfed5b": "Dieser Link fügt diesem Browser ein Backend hinzu. Fahre nur fort, wenn du ihm vertraust.", + "41b32a424841adb7": "Dieser Kopplungslink enthält einen ungültigen Backend-Host.", "ec2a82b05e616aa0": "Diesem Kopplungslink fehlen Backend-Host oder Token.", "630d4f04309bc19a": "Authentifizierung fehlgeschlagen.", "63bc32e8544f4de1": "Diese Umgebung erwartet vertrauenswürdige Kopplungsdaten, bevor die App sich verbinden kann.", @@ -3253,11 +3254,13 @@ "55c59743f7fdd7fa": "Einmaltoken oder Kopplungsgeheimnis einfügen", "ca6a0c94398d763d": "Wird gekoppelt...", "989f56b8297dd684": "Dieses einmalige Kopplungstoken wurde bereits übermittelt. Fordere einen neuen Kopplungslink an.", + "693a1983e099523a": "Verbindung mit diesem Backend.", "db3dcafc90d10405": "{environment} ist in diesem Browser gespeichert.", "47d4ab320c4c394c": "Die Umgebung ist in diesem Browser gespeichert.", "d235c6bfa25870a4": "{error} Falls das Backend dieses Einmaltoken akzeptiert hat, fordere vor einem neuen Versuch einen neuen Kopplungslink an.", "00c1dcaef4762f18": "Backend gekoppelt", "aac4a30e5912c01c": "Kopplung fehlgeschlagen", + "c142c3f3bed15f8d": "Dieses Backend hinzufügen?", "dbb27f4ee8ecfa8e": "Backend wird gekoppelt", "8049e9ba2e8b4867": "Kopplungstoken", "0528294df7656322": [ @@ -3274,6 +3277,7 @@ } ], "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", + "984c25ffcae69300": "Backend hinzufügen", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2764010f88414..22791e2badd65 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Access", "9699d255b374e215": "What it may do", "86f5769278f5fa4d": "Beyond read only, it can start, message and stop threads, and none of them can run with more than the mode you pick.", - "693a1983e099523a": "Connecting to this backend.", + "4f3982f640dfed5b": "This link adds a backend to this browser. Continue only if you trust it.", + "41b32a424841adb7": "This pairing link has an invalid backend host.", "ec2a82b05e616aa0": "This pairing link is missing its backend host or token.", "630d4f04309bc19a": "Authentication failed.", "63bc32e8544f4de1": "This environment expects a trusted pairing credential before the app can connect.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Paste a one-time token or pairing secret", "ca6a0c94398d763d": "Pairing...", "989f56b8297dd684": "This one-time pairing token was already submitted. Request a new pairing link.", + "693a1983e099523a": "Connecting to this backend.", "db3dcafc90d10405": "{environment} is saved in this browser.", "47d4ab320c4c394c": "The environment is saved in this browser.", "d235c6bfa25870a4": "{error} If the backend accepted this one-time token, request a new pairing link before retrying.", "00c1dcaef4762f18": "Backend paired", "aac4a30e5912c01c": "Pairing failed", + "c142c3f3bed15f8d": "Add this backend?", "dbb27f4ee8ecfa8e": "Pairing backend", "8049e9ba2e8b4867": "Pairing token", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", + "984c25ffcae69300": "Add backend", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", "49cc06e79f21f85a": "{seconds}s", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index f7bd7ecb09588..2c68ad496ac5f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Acceso", "9699d255b374e215": "Lo que puede hacer", "86f5769278f5fa4d": "Además de leer, puede iniciar, enviar mensajes a y detener hilos, y ninguno puede ejecutarse con más permisos que el modo que elijas.", - "693a1983e099523a": "Conectando con este backend.", + "4f3982f640dfed5b": "Este enlace añade un backend a este navegador. Continúa solo si confías en él.", + "41b32a424841adb7": "Este enlace de emparejamiento tiene un host de backend no válido.", "ec2a82b05e616aa0": "A este enlace de emparejamiento le falta el host del backend o el token.", "630d4f04309bc19a": "Falló la autenticación.", "63bc32e8544f4de1": "Este entorno espera una credencial de emparejamiento de confianza antes de que la app pueda conectarse.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Pega un token de un solo uso o un secreto de emparejamiento", "ca6a0c94398d763d": "Emparejando...", "989f56b8297dd684": "Este token de emparejamiento de un solo uso ya se envió. Solicita un enlace de emparejamiento nuevo.", + "693a1983e099523a": "Conectando con este backend.", "db3dcafc90d10405": "{environment} está guardado en este navegador.", "47d4ab320c4c394c": "El entorno está guardado en este navegador.", "d235c6bfa25870a4": "{error} Si el backend aceptó este token de un solo uso, solicita un enlace de emparejamiento nuevo antes de reintentarlo.", "00c1dcaef4762f18": "Backend emparejado", "aac4a30e5912c01c": "Falló el emparejamiento", + "c142c3f3bed15f8d": "¿Añadir este backend?", "dbb27f4ee8ecfa8e": "Backend de emparejamiento", "8049e9ba2e8b4867": "Token de emparejamiento", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", + "984c25ffcae69300": "Añadir backend", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 209553a0cda86..cb4db84726d56 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Accès", "9699d255b374e215": "Ce qu’il peut faire", "86f5769278f5fa4d": "Au-delà de la lecture seule, il peut démarrer, arrêter des fils et leur envoyer des messages, et aucun ne peut s’exécuter avec plus que le mode que vous choisissez.", - "693a1983e099523a": "Connexion à ce backend.", + "4f3982f640dfed5b": "Ce lien ajoute un backend à ce navigateur. Ne continuez que si vous lui faites confiance.", + "41b32a424841adb7": "L’hôte du backend de ce lien d’appairage n’est pas valide.", "ec2a82b05e616aa0": "Il manque l’hôte du backend ou le jeton dans ce lien d’appairage.", "630d4f04309bc19a": "Échec de l’authentification.", "63bc32e8544f4de1": "Cet environnement attend un identifiant d’appairage de confiance avant que l’app puisse se connecter.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Collez un jeton à usage unique ou un secret d’appairage", "ca6a0c94398d763d": "Appairage...", "989f56b8297dd684": "Ce jeton d’appairage à usage unique a déjà été envoyé. Demandez un nouveau lien d’appairage.", + "693a1983e099523a": "Connexion à ce backend.", "db3dcafc90d10405": "{environment} est enregistré dans ce navigateur.", "47d4ab320c4c394c": "L’environnement est enregistré dans ce navigateur.", "d235c6bfa25870a4": "{error} Si le backend a accepté ce jeton à usage unique, demandez un nouveau lien d’appairage avant de réessayer.", "00c1dcaef4762f18": "Backend appairé", "aac4a30e5912c01c": "Échec de l’appairage", + "c142c3f3bed15f8d": "Ajouter ce backend ?", "dbb27f4ee8ecfa8e": "Backend d’appairage", "8049e9ba2e8b4867": "Jeton d’appairage", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", + "984c25ffcae69300": "Ajouter le backend", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c9e97b9e3f263..01c10337742d3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3236,7 +3236,8 @@ "49e3cf16b3ac3e5f": "アクセス", "9699d255b374e215": "許可する操作", "86f5769278f5fa4d": "読み取り専用に加えて、スレッドの開始、メッセージ送信、停止ができます。どのスレッドも、選択したモードを超える権限では実行できません。", - "693a1983e099523a": "このバックエンドに接続しています。", + "4f3982f640dfed5b": "このリンクはこのブラウザにバックエンドを追加します。信頼できる場合のみ続行してください。", + "41b32a424841adb7": "このペアリングリンクのバックエンドホストが無効です。", "ec2a82b05e616aa0": "このペアリングリンクにはバックエンドのホストまたはトークンがありません。", "630d4f04309bc19a": "認証に失敗しました。", "63bc32e8544f4de1": "この環境では、アプリが接続する前に信頼されたペアリング資格情報が必要です。", @@ -3250,11 +3251,13 @@ "55c59743f7fdd7fa": "ワンタイムトークンまたはペアリングシークレットを貼り付け", "ca6a0c94398d763d": "ペアリングしています...", "989f56b8297dd684": "このワンタイムペアリングトークンはすでに送信されています。新しいペアリングリンクをリクエストしてください。", + "693a1983e099523a": "このバックエンドに接続しています。", "db3dcafc90d10405": "{environment} はこのブラウザーに保存されています。", "47d4ab320c4c394c": "環境はこのブラウザーに保存されています。", "d235c6bfa25870a4": "{error} バックエンドがこのワンタイムトークンを受け付けた場合は、再試行する前に新しいペアリングリンクをリクエストしてください。", "00c1dcaef4762f18": "バックエンドとペアリングしました", "aac4a30e5912c01c": "ペアリングに失敗しました", + "c142c3f3bed15f8d": "このバックエンドを追加しますか?", "dbb27f4ee8ecfa8e": "ペアリング先のバックエンド", "8049e9ba2e8b4867": "ペアリングトークン", "0528294df7656322": [ @@ -3271,6 +3274,7 @@ } ], "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", + "984c25ffcae69300": "バックエンドを追加", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", "49cc06e79f21f85a": "{seconds}秒", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 7d528f7527d27..eb4cf8b1c5273 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3237,7 +3237,8 @@ "49e3cf16b3ac3e5f": "액세스", "9699d255b374e215": "허용할 작업", "86f5769278f5fa4d": "읽기 전용 외에 스레드를 시작하고, 메시지를 보내고, 중지할 수 있으며, 어떤 스레드도 선택한 모드보다 높은 권한으로 실행할 수 없습니다.", - "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", + "4f3982f640dfed5b": "이 링크는 이 브라우저에 백엔드를 추가합니다. 신뢰하는 경우에만 계속하세요.", + "41b32a424841adb7": "이 페어링 링크의 백엔드 호스트가 올바르지 않습니다.", "ec2a82b05e616aa0": "이 페어링 링크에 백엔드 호스트 또는 토큰이 없습니다.", "630d4f04309bc19a": "인증에 실패했습니다.", "63bc32e8544f4de1": "앱이 연결하려면 이 환경에 신뢰할 수 있는 페어링 자격 증명이 필요합니다.", @@ -3251,11 +3252,13 @@ "55c59743f7fdd7fa": "일회용 토큰 또는 페어링 시크릿 붙여 넣기", "ca6a0c94398d763d": "페어링하는 중...", "989f56b8297dd684": "이 일회용 페어링 토큰은 이미 제출되었습니다. 새 페어링 링크를 요청하세요.", + "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", "db3dcafc90d10405": "{environment}이(가) 이 브라우저에 저장되었습니다.", "47d4ab320c4c394c": "환경이 이 브라우저에 저장되었습니다.", "d235c6bfa25870a4": "{error} 백엔드가 이 일회용 토큰을 수락했다면 다시 시도하기 전에 새 페어링 링크를 요청하세요.", "00c1dcaef4762f18": "백엔드 페어링됨", "aac4a30e5912c01c": "페어링 실패", + "c142c3f3bed15f8d": "이 백엔드를 추가할까요?", "dbb27f4ee8ecfa8e": "백엔드 페어링 중", "8049e9ba2e8b4867": "페어링 토큰", "0528294df7656322": [ @@ -3272,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", + "984c25ffcae69300": "백엔드 추가", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", "49cc06e79f21f85a": "{seconds}초", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 33e0262600d4a..06eea3c29b995 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Acesso", "9699d255b374e215": "O que ele pode fazer", "86f5769278f5fa4d": "Além da leitura, ele pode iniciar, enviar mensagens e parar threads, e nenhuma delas pode rodar com mais do que o modo que você escolher.", - "693a1983e099523a": "Conectando a este backend.", + "4f3982f640dfed5b": "Este link adiciona um backend a este navegador. Continue somente se você confia nele.", + "41b32a424841adb7": "Este link de pareamento tem um host de backend inválido.", "ec2a82b05e616aa0": "Falta o host do backend ou o token neste link de pareamento.", "630d4f04309bc19a": "Falha na autenticação.", "63bc32e8544f4de1": "Este ambiente exige uma credencial de pareamento confiável antes que o app possa se conectar.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Cole um token de uso único ou um segredo de pareamento", "ca6a0c94398d763d": "Pareando...", "989f56b8297dd684": "Este token de pareamento de uso único já foi enviado. Solicite um novo link de pareamento.", + "693a1983e099523a": "Conectando a este backend.", "db3dcafc90d10405": "{environment} está salvo neste navegador.", "47d4ab320c4c394c": "O ambiente está salvo neste navegador.", "d235c6bfa25870a4": "{error} Se o backend aceitou este token de uso único, solicite um novo link de pareamento antes de tentar novamente.", "00c1dcaef4762f18": "Backend pareado", "aac4a30e5912c01c": "Falha no pareamento", + "c142c3f3bed15f8d": "Adicionar este backend?", "dbb27f4ee8ecfa8e": "Pareando o backend", "8049e9ba2e8b4867": "Token de pareamento", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", + "984c25ffcae69300": "Adicionar backend", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds}s", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index a93a2ce219ea2..44148970bd468 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Доступ", "9699d255b374e215": "Что ему разрешено", "86f5769278f5fa4d": "Помимо чтения, он может запускать треды, отправлять в них сообщения и останавливать их, и ни один не будет работать с режимом выше выбранного.", - "693a1983e099523a": "Подключение к этому бэкенду.", + "4f3982f640dfed5b": "Эта ссылка добавляет бэкенд в этот браузер. Продолжайте, только если доверяете ему.", + "41b32a424841adb7": "В ссылке для сопряжения указан недопустимый хост бэкенда.", "ec2a82b05e616aa0": "В ссылке для сопряжения нет хоста бэкенда или токена.", "630d4f04309bc19a": "Ошибка аутентификации.", "63bc32e8544f4de1": "Этому окружению нужны доверенные учётные данные сопряжения, прежде чем приложение сможет подключиться.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Вставьте одноразовый токен или секрет сопряжения", "ca6a0c94398d763d": "Сопряжение...", "989f56b8297dd684": "Этот одноразовый токен сопряжения уже отправлен. Запросите новую ссылку для сопряжения.", + "693a1983e099523a": "Подключение к этому бэкенду.", "db3dcafc90d10405": "{environment} сохранено в этом браузере.", "47d4ab320c4c394c": "Окружение сохранено в этом браузере.", "d235c6bfa25870a4": "{error} Если бэкенд принял этот одноразовый токен, запросите новую ссылку для сопряжения перед повтором.", "00c1dcaef4762f18": "Сопряжение с бэкендом выполнено", "aac4a30e5912c01c": "Ошибка сопряжения", + "c142c3f3bed15f8d": "Добавить этот бэкенд?", "dbb27f4ee8ecfa8e": "Бэкенд сопряжения", "8049e9ba2e8b4867": "Токен сопряжения", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", + "984c25ffcae69300": "Добавить бэкенд", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", "49cc06e79f21f85a": "{seconds} с", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 2b15a6570f9ab..2bb20d01df420 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Åtkomst", "9699d255b374e215": "Vad den får göra", "86f5769278f5fa4d": "Utöver endast läsning kan den starta, skicka meddelanden till och stoppa trådar, och ingen av dem kan köras med mer än det läge du väljer.", - "693a1983e099523a": "Ansluter till den här backenden.", + "4f3982f640dfed5b": "Den här länken lägger till en backend i den här webbläsaren. Fortsätt bara om du litar på den.", + "41b32a424841adb7": "Den här parkopplingslänken har en ogiltig backend-värd.", "ec2a82b05e616aa0": "Den här parkopplingslänken saknar backend-värd eller token.", "630d4f04309bc19a": "Autentiseringen misslyckades.", "63bc32e8544f4de1": "Den här miljön kräver en betrodd parkopplingsuppgift innan appen kan ansluta.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Klistra in en engångstoken eller en parkopplingshemlighet", "ca6a0c94398d763d": "Parkopplar...", "989f56b8297dd684": "Den här engångstoken för parkoppling har redan skickats. Begär en ny parkopplingslänk.", + "693a1983e099523a": "Ansluter till den här backenden.", "db3dcafc90d10405": "{environment} är sparad i den här webbläsaren.", "47d4ab320c4c394c": "Miljön är sparad i den här webbläsaren.", "d235c6bfa25870a4": "{error} Om backenden godtog den här engångstoken, begär en ny parkopplingslänk innan du försöker igen.", "00c1dcaef4762f18": "Backenden parkopplades", "aac4a30e5912c01c": "Parkopplingen misslyckades", + "c142c3f3bed15f8d": "Lägga till den här backenden?", "dbb27f4ee8ecfa8e": "Parkopplar backend", "8049e9ba2e8b4867": "Parkopplingstoken", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", + "984c25ffcae69300": "Lägg till backend", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index fc0cbe1297c4f..0def42b8dda67 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3242,7 +3242,8 @@ "49e3cf16b3ac3e5f": "访问权限", "9699d255b374e215": "允许它做什么", "86f5769278f5fa4d": "除只读外,它还可以启动会话、向会话发消息和停止会话,且任何会话的权限都不会超过你选择的模式。", - "693a1983e099523a": "正在连接此后端。", + "4f3982f640dfed5b": "此链接会向此浏览器添加一个后端。仅在你信任它时继续。", + "41b32a424841adb7": "此配对链接中的后端主机无效。", "ec2a82b05e616aa0": "此配对链接缺少后端主机或 token。", "630d4f04309bc19a": "身份验证失败。", "63bc32e8544f4de1": "此环境需要可信的配对凭据,应用才能连接。", @@ -3256,11 +3257,13 @@ "55c59743f7fdd7fa": "粘贴一次性 token 或配对凭据", "ca6a0c94398d763d": "正在配对…", "989f56b8297dd684": "此一次性配对 token 已提交过。请申请新的配对链接。", + "693a1983e099523a": "正在连接此后端。", "db3dcafc90d10405": "{environment} 已保存在此浏览器中。", "47d4ab320c4c394c": "该环境已保存在此浏览器中。", "d235c6bfa25870a4": "{error} 如果后端已接受此一次性 token,请先申请新的配对链接再重试。", "00c1dcaef4762f18": "后端已配对", "aac4a30e5912c01c": "配对失败", + "c142c3f3bed15f8d": "要添加此后端吗?", "dbb27f4ee8ecfa8e": "正在配对后端", "8049e9ba2e8b4867": "配对 token", "0528294df7656322": [ @@ -3277,6 +3280,7 @@ } ], "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", + "984c25ffcae69300": "添加后端", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", "49cc06e79f21f85a": "{seconds} 秒", diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index bdcd2281ccd08..3518382d2026e 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -235,7 +235,8 @@ If that port is already in use, choose another with [app.t3.codes](https://app.t3.codes) needs an HTTPS endpoint. It connects directly to your server; a hosted pairing link does not make an unreachable backend -reachable or convert HTTP to HTTPS. +reachable or convert HTTP to HTTPS. Opening a hosted pairing link shows the +server address and asks you to confirm before adding it. For a plain HTTP LAN endpoint, use the direct pairing URL in a browser that can open it, or pair from the desktop app. On mobile, an IP address entered without a From 7c95302f7a87cb8462c0fd71f2122aeaadb5c967 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:13:14 -0800 Subject: [PATCH 217/288] ci: release and preview credentials are scoped to the steps and jobs that use them (#41765) Co-authored-by: Claude Fable 5.2 --- .github/actions/record-build-tag/action.yml | 20 +- .github/actions/setup-ci-deps/action.yml | 21 +- .github/scripts/set-mobile-version.cjs | 30 ++ .../scripts/vercel-deployment-output.test.cjs | 2 +- .github/scripts/workflow-credentials.test.cjs | 269 +++++++++++++++++ .github/workflows/ci.yml | 2 +- .../workflows/mobile-eas-preview-build.yml | 198 +++++++++++++ .github/workflows/mobile-eas-preview-fork.yml | 17 +- .github/workflows/mobile-eas-preview.yml | 170 +---------- .../workflows/mobile-eas-production-build.yml | 196 +++++++++++++ .github/workflows/mobile-eas-production.yml | 277 ++++++------------ .github/workflows/release.yml | 17 +- .github/workflows/web-preview.yml | 13 +- docs/operations/03_release.md | 2 +- 14 files changed, 869 insertions(+), 365 deletions(-) create mode 100644 .github/scripts/set-mobile-version.cjs create mode 100644 .github/scripts/workflow-credentials.test.cjs create mode 100644 .github/workflows/mobile-eas-preview-build.yml create mode 100644 .github/workflows/mobile-eas-production-build.yml diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml index 2086d004b295c..a45f83e1263a8 100644 --- a/.github/actions/record-build-tag/action.yml +++ b/.github/actions/record-build-tag/action.yml @@ -8,6 +8,9 @@ inputs: message: description: Annotated tag message; empty makes a lightweight tag default: "" + commit: + description: Commit to tag, 40 hex characters and reachable from the workflow's ref; empty tags HEAD + default: "" replace: description: "true replaces an existing tag; otherwise an existing tag counts as recorded" default: "false" @@ -22,6 +25,7 @@ runs: shell: bash env: TAG: ${{ inputs.tag }} + COMMIT: ${{ inputs.commit }} MESSAGE: ${{ inputs.message }} REPLACE: ${{ inputs.replace }} GH_TOKEN: ${{ inputs.token }} @@ -29,6 +33,18 @@ runs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # A named commit is tagged only when it is on the ref this workflow runs for. + if [ -n "$COMMIT" ]; then + if ! [[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The commit to tag is not a full SHA." + exit 1 + fi + git fetch --quiet "$remote" "$GITHUB_REF" + if ! git merge-base --is-ancestor "$COMMIT" FETCH_HEAD 2>/dev/null; then + echo "::error::$COMMIT is not on $GITHUB_REF." + exit 1 + fi + fi # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). for attempt in 1 2 3; do if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then @@ -40,9 +56,9 @@ runs: exit 0 fi if [ -n "$MESSAGE" ]; then - git tag -f -a "$TAG" -m "$MESSAGE" + git tag -f -a "$TAG" -m "$MESSAGE" ${COMMIT:+"$COMMIT"} else - git tag -f "$TAG" + git tag -f "$TAG" ${COMMIT:+"$COMMIT"} fi # An empty lease means the tag must not exist yet. if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index cc6dc80511aca..b2236f6a15cf8 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -31,14 +31,16 @@ runs: echo "node=$(jq -r '.engines.node' package.json)" >> "$GITHUB_OUTPUT" echo "pnpm=$(jq -r '.packageManager' package.json)" >> "$GITHUB_OUTPUT" + # Restore only: "Save Vite+" below writes the toolchain before this job + # installs or runs project code. # Pinned because release-desktop.yml signs builds with this action in the job. - - name: Cache Vite+ + - name: Restore Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.vite-plus - key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} + key: vite-plus-home-v3-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} # setup-vp always runs the installer, which fetches vp from npm even when # this exact version is installed. A cache hit already has everything, so @@ -64,6 +66,19 @@ runs: cache: false run-install: false + # vp downloads pnpm on first use, which would otherwise be after the save. + - name: Fetch pnpm + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + shell: bash + run: vp pm cache dir + + - name: Save Vite+ + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.vite-plus + key: ${{ steps.vp_cache.outputs.cache-primary-key }} + # A shared key lets whichever install saves first, often a small filtered # one, become every job's store. Each set of install args gets its own. - name: Resolve pnpm store diff --git a/.github/scripts/set-mobile-version.cjs b/.github/scripts/set-mobile-version.cjs new file mode 100644 index 0000000000000..bb45a524ed357 --- /dev/null +++ b/.github/scripts/set-mobile-version.cjs @@ -0,0 +1,30 @@ +const fs = require("node:fs"); + +const CONFIG_PATH = "apps/mobile/app.config.ts"; +const VERSION_LINE = /^( {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m; + +// Replaces one string literal, so the result needs no formatter. +function setMobileVersion(source, version) { + if (!/^[0-9]+(\.[0-9]+){1,2}$/.test(version)) { + throw new Error( + `Version override must contain two or three dot-separated integers; received '${version}'.`, + ); + } + if (!VERSION_LINE.test(source)) throw new Error("Could not update app version"); + return source.replace(VERSION_LINE, `$1${version}$2`); +} + +if (require.main === module) { + const { GITHUB_REF_TYPE, GITHUB_REF_NAME } = process.env; + if (GITHUB_REF_TYPE !== "branch") { + throw new Error( + `Version overrides require dispatching this workflow from a branch; received ${GITHUB_REF_TYPE} '${GITHUB_REF_NAME}'.`, + ); + } + fs.writeFileSync( + CONFIG_PATH, + setMobileVersion(fs.readFileSync(CONFIG_PATH, "utf8"), process.argv[2] ?? ""), + ); +} + +module.exports = { setMobileVersion }; diff --git a/.github/scripts/vercel-deployment-output.test.cjs b/.github/scripts/vercel-deployment-output.test.cjs index a249653350f22..b5a3ea7b94471 100644 --- a/.github/scripts/vercel-deployment-output.test.cjs +++ b/.github/scripts/vercel-deployment-output.test.cjs @@ -8,7 +8,7 @@ const { test } = require("node:test"); const release = readFileSync(join(__dirname, "../workflows/release.yml"), "utf8"); const preview = readFileSync(join(__dirname, "../workflows/web-preview.yml"), "utf8"); const stepPattern = - / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n run: \|\n((?: .*\n|\n)+)/g; + / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n(?: env:\n(?: .*\n)+)? run: \|\n((?: .*\n|\n)+)/g; const steps = [ ...Array.from(release.matchAll(stepPattern), (match, index) => [ index === 0 ? "hosted web" : "marketing", diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs new file mode 100644 index 0000000000000..7dc6018654e7e --- /dev/null +++ b/.github/scripts/workflow-credentials.test.cjs @@ -0,0 +1,269 @@ +const assert = require("node:assert/strict"); +const { execFileSync, spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { test } = require("node:test"); + +const { setMobileVersion } = require("./set-mobile-version.cjs"); + +const read = (path) => readFileSync(join(__dirname, "..", path), "utf8"); + +function jobs(path) { + const body = read(path).split(/^jobs:\n/m)[1]; + const found = {}; + for (const block of body.split(/^(?= [\w-]+:\n)/m)) { + const name = /^ ([\w-]+):\n/.exec(block)?.[1]; + if (name) found[name] = block; + } + return found; +} + +const steps = (block) => block.split(/^ {4,6}- /m).slice(1); +const runsProjectCode = (block) => + /setup-vp@|setup-ci-deps|eas-local-build|expo-github-action|\b(?:vp|pnpm|npm|npx|eas) /.test( + block, + ); + +test("npm publishing is bound to the environment that admits only main and v* tags", () => { + const publish = jobs("workflows/release.yml").publish_cli; + assert.match(publish, /^ {6}id-token: write$/m); + assert.match(publish, /^ {4}environment: production$/m); +}); + +test("the web preview gives the Vercel token to the deploy step only, after an install without lifecycle scripts", () => { + const deploy = jobs("workflows/web-preview.yml").deploy; + assert.doesNotMatch(deploy.split(/^ {4}steps:\n/m)[0], /secrets\./); + const withSecrets = steps(deploy).filter((step) => step.includes("secrets.")); + assert.equal(withSecrets.length, 1); + assert.match(withSecrets[0], /name: Deploy preview/); + assert.match(deploy, /run-install: \|\n {12}args:\n {14}- --ignore-scripts\n/); +}); + +const mobileWorkflows = [ + "workflows/mobile-eas-preview.yml", + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production.yml", + "workflows/mobile-eas-production-build.yml", +]; + +for (const path of mobileWorkflows) { + test(`${path}: no job that installs or builds can push to the repository`, () => { + for (const [name, block] of Object.entries(jobs(path))) { + if (/^ {4}uses: /m.test(block)) continue; + const writes = /contents: write|record-build-tag|create-github-app-token/.test(block); + assert.ok(!(writes && runsProjectCode(block)), `${name} holds a write token and runs code`); + } + }); +} + +test("the build record is pushed by the record job of each build workflow", () => { + for (const path of [ + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production-build.yml", + ]) { + const { record, ...builds } = jobs(path); + assert.match(record, /uses: \.\/\.github\/actions\/record-build-tag/); + assert.match(record, /^ {6}contents: write/m); + for (const block of Object.values(builds)) assert.match(block, /^ {6}contents: read$/m); + } +}); + +test("jobs that push run this workflow's own actions", () => { + for (const file of mobileWorkflows) { + for (const [name, block] of Object.entries(jobs(file))) { + if (!/contents: write|create-github-app-token/.test(block)) continue; + const jobSteps = steps(block); + const checkout = jobSteps.findIndex((step) => /^ +ref: .*\b(?:inputs|needs)\./m.test(step)); + if (checkout === -1) continue; + const local = jobSteps.slice(checkout).filter((step) => /^ +uses: \.\//m.test(step)); + assert.equal(local.length, 0, `${file} ${name} runs a local action from another checkout`); + } + } +}); + +const recordScript = read("actions/record-build-tag/action.yml") + .split(/^ {6}run: \|\n/m)[1] + .replace(/^ {8}/gm, "") + .replace(/^remote=.*$/m, 'remote="$TEST_REMOTE"'); + +function recordTag(commitOf) { + const directory = mkdtempSync(join(tmpdir(), "t3-record-tag-")); + const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + try { + const remote = join(directory, "remote.git"); + const work = join(directory, "work"); + git(directory, "init", "--quiet", "--bare", remote); + git(directory, "init", "--quiet", "--initial-branch=main", work); + const commit = (message) => { + git( + work, + "-c", + "user.name=t", + "-c", + "user.email=t@example.com", + "commit", + "--quiet", + "--allow-empty", + "-m", + message, + ); + return git(work, "rev-parse", "HEAD"); + }; + const shas = { first: commit("first") }; + shas.head = commit("second"); + git(work, "push", "--quiet", remote, "main"); + git(work, "checkout", "--quiet", "--detach"); + shas.elsewhere = commit("not on main"); + git(work, "push", "--quiet", remote, "HEAD:refs/heads/other"); + git(work, "checkout", "--quiet", "main"); + const result = spawnSync("bash", ["-c", recordScript], { + cwd: work, + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOME: directory, + TEST_REMOTE: remote, + GITHUB_REF: "refs/heads/main", + TAG: "build/1", + MESSAGE: "", + REPLACE: "false", + COMMIT: commitOf(shas), + }, + }); + const tagged = git(directory, "ls-remote", remote, "refs/tags/build/1").split(/\s/)[0]; + return { status: result.status, tagged, shas }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +test("the build record tags the named commit only when it is on the workflow's ref", () => { + const onRef = recordTag((shas) => shas.first); + assert.deepEqual([onRef.status, onRef.tagged], [0, onRef.shas.first]); + const head = recordTag(() => ""); + assert.deepEqual([head.status, head.tagged], [0, head.shas.head]); + for (const commitOf of [(shas) => shas.elsewhere, () => "main", () => "0".repeat(40)]) { + const refused = recordTag(commitOf); + assert.deepEqual([refused.status, refused.tagged], [1, ""]); + } +}); + +test("the store build record job runs the workflow's own action and passes the built commit as data", () => { + const { record } = jobs("workflows/mobile-eas-production-build.yml"); + assert.doesNotMatch(record, /^ +ref: /m); + assert.match(record, /^ {10}commit: \$\{\{ inputs\.sha \}\}$/m); +}); + +test("release deploys give the Vercel token to the deploy step only", () => { + const all = jobs("workflows/release.yml"); + for (const name of ["build_web", "build_marketing"]) { + assert.doesNotMatch(all[name].split(/^ {4}steps:\n/m)[0], /secrets\.VERCEL/); + const withToken = steps(all[name]).filter((step) => step.includes("secrets.VERCEL_TOKEN")); + assert.equal(withToken.length, 1); + assert.match(withToken[0], /name: Build staged deployment/); + } +}); + +test("the version override token covers this repository only", () => { + const { version, production } = jobs("workflows/mobile-eas-production.yml"); + const mint = steps(version).find((step) => step.includes("create-github-app-token")); + assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m); + assert.match(mint, /^\s+permission-contents: write$/m); + assert.doesNotMatch(production, /RELEASE_APP|create-github-app-token/); +}); + +test("the Vite+ toolchain is cached before the job installs or runs project code", () => { + const names = Array.from( + read("actions/setup-ci-deps/action.yml").matchAll( + /^ {4}- name: (.+)\n(?: {6}.*\n)*? {6}uses: (\S+)|^ {4}- name: (.+)$/gm, + ), + (match) => ({ name: match[1] ?? match[3], uses: match[2] ?? "" }), + ); + const index = (name) => names.findIndex((step) => step.name === name); + assert.match(names[index("Restore Vite+")].uses, /^actions\/cache\/restore@/); + assert.match(names[index("Save Vite+")].uses, /^actions\/cache\/save@/); + assert.ok(index("Save Vite+") < index("Resolve pnpm store")); + assert.ok(index("Save Vite+") < index("Install dependencies")); + // The combined action saves at the end of the job, after everything ran. + assert.ok(names.every((step) => !step.uses.startsWith("actions/cache@"))); +}); + +const consumeScript = steps(jobs("workflows/mobile-eas-preview-fork.yml").preview) + .find((step) => step.startsWith("id: consume\n")) + .split(/^ {10}script: \|\n/m)[1] + .replace(/^ {12}/gm, ""); +const consume = new (Object.getPrototypeOf(async () => {}).constructor)( + "github", + "context", + "core", + consumeScript, +); + +async function runConsume(permission, removeStatus) { + const outputs = {}; + const removed = []; + await consume( + { + rest: { + repos: { + async getCollaboratorPermissionLevel({ username }) { + assert.equal(username, "labeler"); + return { data: { permission } }; + }, + }, + issues: { + async removeLabel(params) { + if (removeStatus) throw Object.assign(new Error("gone"), { status: removeStatus }); + removed.push(params.name); + }, + }, + }, + }, + { + repo: { owner: "example", repo: "app" }, + payload: { + sender: { login: "labeler" }, + label: { name: "deploy" }, + pull_request: { number: 7 }, + }, + }, + { info() {}, warning() {}, setOutput: (name, value) => (outputs[name] = value) }, + ); + return { outputs, removed }; +} + +for (const [permission, consumed] of [ + ["admin", "true"], + ["maintain", "true"], + ["write", "true"], + ["triage", "false"], + ["read", "false"], + ["none", "false"], +]) { + test(`a fork preview label from ${permission} access is removed and ${consumed === "true" ? "builds" : "builds nothing"}`, async () => { + assert.deepEqual(await runConsume(permission), { + outputs: { consumed }, + removed: ["deploy"], + }); + }); +} + +test("a fork preview label removed before the run builds nothing", async () => { + assert.deepEqual(await runConsume("admin", 404), { outputs: { consumed: "false" }, removed: [] }); +}); + +test("a version override rewrites only the app version", () => { + const config = read("../apps/mobile/app.config.ts"); + const next = setMobileVersion(config, "9.8.7"); + assert.match(next, /^ {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? "9\.8\.7",$/m); + assert.equal(setMobileVersion(next, "9.8.7"), next); + assert.deepEqual( + next.split("\n").filter((line, index) => line !== config.split("\n")[index]).length, + 1, + ); + for (const version of ["", "1", "1.2.3.4", "1.2-beta", '1.2", extra: "x']) { + assert.throws(() => setMobileVersion(config, version), /two or three dot-separated integers/); + } + assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4c0cfc691b37..70208c7a16479 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -339,7 +339,7 @@ jobs: run: python3 -B .github/scripts/stage-preview-bundle.test.py - name: Test release checks - run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs + run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs .github/scripts/workflow-credentials.test.cjs - name: Finish installing browser secret helper build libraries timeout-minutes: 5 diff --git a/.github/workflows/mobile-eas-preview-build.yml b/.github/workflows/mobile-eas-preview-build.yml new file mode 100644 index 0000000000000..a7774c24bd0af --- /dev/null +++ b/.github/workflows/mobile-eas-preview-build.yml @@ -0,0 +1,198 @@ +name: Mobile EAS Preview Build + +# One preview client and its build record, called per platform by +# mobile-eas-preview.yml. The build job runs dependency and build scripts with a +# read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a build queued for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + fingerprint: + required: true + type: string + secrets: + EXPO_PREVIEW_TOKEN: + required: true + outputs: + client: + description: Install link for the client with this fingerprint + value: ${{ jobs.android.outputs.client || jobs.ios.outputs.client }} + +jobs: + android: + name: Build + if: inputs.platform == 'android' + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, which is the install link. + record: ${{ steps.build.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-android-preview-build/${{ inputs.fingerprint }} + # Phones only: emulators use the development client from the native-client cache. + ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + + # `eas upload` hosts the APK on EAS and returns the page testers install from. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + ios: + name: Build + if: inputs.platform == 'ios' + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, the install link and profile expiry. + record: ${{ steps.profile.outputs.record }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-ios-preview-build/${{ inputs.fingerprint }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" + if [ -n "$link" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$link" >> "$GITHUB_OUTPUT" + fi + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa + + # EAS hosts the signed client and returns its install page. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + # The tag stores the install link and provisioning-profile expiry. + - id: profile + name: Read the provisioning profile + if: steps.record.outputs.built != 'true' + env: + LINK: ${{ steps.build.outputs.link }} + run: | + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" + unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" + security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" + record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" + echo "record=$record" >> "$GITHUB_OUTPUT" + + # The tag is the record later runs look up. Android's message is the install + # link and is never replaced; iOS replaces an expired record for the fingerprint. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.record != '' || needs.ios.outputs.record != '') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + steps: + # The commit the build job built. No build ran in this checkout. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: mobile-${{ inputs.platform }}-preview-build/${{ inputs.fingerprint }} + message: ${{ needs.android.outputs.record || needs.ios.outputs.record }} + replace: ${{ inputs.platform == 'ios' }} + token: ${{ github.token }} diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 890bd0c2aecd9..7a8d784f9d73d 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -43,12 +43,21 @@ jobs: NODE_OPTIONS: --max-old-space-size=8192 MOBILE_VERSION_POLICY: fingerprint steps: - # If a maintainer removed the label first, that removal wins. + # The label counts only from someone with write access, who could push a + # same-repo branch and get this build anyway. If a maintainer removed the + # label first, that removal wins. - id: consume name: Consume the deployment label uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | + const sender = context.payload.sender.login; + const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: sender, + }); + const authorized = ["admin", "maintain", "write"].includes(access.permission); try { await github.rest.issues.removeLabel({ owner: context.repo.owner, @@ -56,12 +65,16 @@ jobs: issue_number: context.payload.pull_request.number, name: context.payload.label.name, }); - core.setOutput("consumed", "true"); } catch (error) { if (error.status !== 404) throw error; core.info("The label was removed before this run could consume it. Skipping."); core.setOutput("consumed", "false"); + return; } + if (!authorized) { + core.warning(`${sender} has ${access.permission} access; a fork preview needs write access. Label removed, nothing built.`); + } + core.setOutput("consumed", String(authorized)); - id: expo-token name: Check for EXPO_PREVIEW_TOKEN diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 53061f25e9c48..5aeb32d647763 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -247,181 +247,43 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" + # Each build runs in mobile-eas-preview-build.yml, whose record job alone gets + # the token that pushes the tag. The group covers both of its jobs. android-build: name: Android preview client needs: android if: needs.android.outputs.build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-android-preview-build-${{ needs.android.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.android.outputs.fingerprint }} - BUILD_TAG: mobile-android-preview-build/${{ needs.android.outputs.fingerprint }} - # Phones only: emulators use the development client from the native-client cache. - ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.apk - - # `eas upload` hosts the APK on EAS and returns the page testers install from. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag is the record later runs look up; its message is the install link. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.build.outputs.link }} - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: android + fingerprint: ${{ needs.android.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} ios-build: name: iOS preview client needs: ios if: needs.ios.outputs.build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-ios-preview-build-${{ needs.ios.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} - BUILD_TAG: mobile-ios-preview-build/${{ needs.ios.outputs.fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" - if [ -n "$link" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$link" >> "$GITHUB_OUTPUT" - fi - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.ipa - - # EAS hosts the signed client and returns its install page. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag stores the install link and provisioning-profile expiry. - - id: profile - name: Read the provisioning profile - if: steps.record.outputs.built != 'true' - env: - LINK: ${{ steps.build.outputs.link }} - run: | - profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" - unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" - security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" - record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" - echo "record=$record" >> "$GITHUB_OUTPUT" - - # Replaces an expired record for the same fingerprint. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.profile.outputs.record }} - replace: "true" - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: ios + fingerprint: ${{ needs.ios.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} comment: name: Mobile preview comment diff --git a/.github/workflows/mobile-eas-production-build.yml b/.github/workflows/mobile-eas-production-build.yml new file mode 100644 index 0000000000000..54289e4dc7e72 --- /dev/null +++ b/.github/workflows/mobile-eas-production-build.yml @@ -0,0 +1,196 @@ +name: Mobile EAS Production Build + +# One store build and its build record, called per platform by +# mobile-eas-production.yml. The build job runs dependency and build scripts with +# a read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a queued run for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + profile: + description: eas.json build and submit profile + required: true + type: string + sha: + description: Commit to build and tag + required: true + type: string + tag: + description: Build record tag, without refs/tags/ + required: true + type: string + secrets: + EXPO_PRODUCTION_TOKEN: + required: true + MOBILE_SOURCEMAPS_R2: + required: false + +jobs: + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state on a sticky disk. + android: + name: Build + if: ${{ !cancelled() && inputs.platform == 'android' }} + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs + if: steps.record.outputs.built != 'true' + run: | + abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" + if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then + echo "::error::Expected only ARM native libraries in the AAB, found $abis" + exit 1 + fi + + # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. + - name: Keep the AAB + if: steps.record.outputs.built != 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/t3code.aab + retention-days: 14 + if-no-files-found: error + + - id: submit + name: Submit to Google Play + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive + + # No sticky disk: it mounts ext4 and only works on Linux runners. + ios: + name: Build + if: ${{ !cancelled() && inputs.platform == 'ios' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + PROFILE: ${{ inputs.profile }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: ${{ env.PROFILE }} + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.ipa + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - id: submit + name: Submit to App Store Connect + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive + + # The tag means "delivered", so it follows the submit. If it can't be + # pushed, the next merge rebuilds with a new build number; nothing is lost. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.submitted == 'true' || needs.ios.outputs.submitted == 'true') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + env: + BUILD_TAG: ${{ inputs.tag }} + steps: + # The workflow's own commit, so the action below is this workflow's. The + # built commit is passed as data. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: ${{ inputs.tag }} + commit: ${{ inputs.sha }} + token: ${{ github.token }} + + - name: Summarize + env: + PLATFORM: ${{ inputs.platform }} + run: | + echo ":rocket: $PLATFORM: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index fe4d7456acdf4..0bfe62444d81b 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -68,6 +68,7 @@ on: - pnpm-lock.yaml - pnpm-workspace.yaml - .github/workflows/mobile-eas-production.yml + - .github/workflows/mobile-eas-production-build.yml jobs: production: @@ -83,6 +84,7 @@ jobs: permissions: contents: read outputs: + version_override: ${{ steps.version_override.outputs.applied }} android_build: ${{ steps.reconcile.outputs.android_build || steps.android_manual.outputs.android_build }} android_fingerprint: ${{ steps.reconcile.outputs.android_fingerprint || steps.android_manual.outputs.android_fingerprint }} android_version: ${{ steps.reconcile.outputs.android_version || steps.android_manual.outputs.android_version }} @@ -119,21 +121,11 @@ jobs: echo "EXPO_PRODUCTION_TOKEN is not available; skipping EAS production job." fi - - id: version_app_token - name: Mint release app token for version override - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' - uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 - with: - app-id: ${{ secrets.RELEASE_APP_ID }} - private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} - - name: Checkout if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 - token: ${{ steps.version_app_token.outputs.token || github.token }} # No sparse-checkout here: it makes actions/checkout fetch with # --filter=blob:none, and eas-cli archives the project via # `git clone --depth 1 file://`, which fails (exit 128) @@ -188,48 +180,21 @@ jobs: appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); NODE - - name: Apply manual version override - if: steps.version_app_token.outcome == 'success' + # Only so the versions and fingerprints below are read from the tree that + # will be built. This job installs dependencies, so it gets no token that can + # push: the version job makes the same commit as the Release App afterwards. + - id: version_override + name: Apply manual version override + if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' env: - GH_TOKEN: ${{ steps.version_app_token.outputs.token }} - APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }} RELEASE_VERSION: ${{ inputs.version }} run: | - if [ "$GITHUB_REF_TYPE" != "branch" ]; then - echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2 - exit 1 - fi - if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then - echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2 - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if ! git diff --quiet -- apps/mobile/app.config.ts; then + git -c user.name=mobile-version -c user.email=mobile-version@users.noreply.github.com \ + commit --no-verify --quiet -m "chore(mobile): bump app version to $RELEASE_VERSION" -- apps/mobile/app.config.ts fi - - node --input-type=module -e ' - import fs from "node:fs"; - const path = "apps/mobile/app.config.ts"; - const source = fs.readFileSync(path, "utf8"); - const next = source.replace( - /^( version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m, - `$1${process.env.RELEASE_VERSION}$2`, - ); - if (next === source && !source.includes(` version: repoEnv.T3CODE_MOBILE_VERSION ?? "${process.env.RELEASE_VERSION}"`)) { - throw new Error("Could not update app version"); - } - fs.writeFileSync(path, next); - ' - vp fmt apps/mobile/app.config.ts - - if git diff --quiet -- apps/mobile/app.config.ts; then - echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." - exit 0 - fi - - user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" - git config user.name "${APP_SLUG}[bot]" - git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" - git add apps/mobile/app.config.ts - git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" - git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" + echo "applied=true" >> "$GITHUB_OUTPUT" - name: Summarize manual build version if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' @@ -453,165 +418,95 @@ jobs: fi done - # ARM-only, without release lint (see the production profile in eas.json), - # with Gradle, ccache, and pnpm state on a sticky disk. Its own concurrency - # group keeps later OTAs from waiting on it. - android: - name: Android store build + # Commits a store version override as the Release App. It installs nothing and + # runs no dependency code, so that token never shares a runner with any. It + # runs after the production job so the push's own run queues behind this one. + version: + name: Commit version override needs: production - # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.android_build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 - concurrency: - group: mobile-android-store-build - cancel-in-progress: false + if: ${{ !cancelled() && needs.production.result == 'success' && needs.production.outputs.version_override == 'true' }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - BUILD_TAG: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + contents: read + outputs: + sha: ${{ steps.commit.outputs.sha }} steps: + # No owner input: the token covers this repository only, with contents write. + - id: app_token + name: Mint release app token + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ secrets.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ needs.production.outputs.android_sha }} - fetch-depth: 0 + token: ${{ steps.app_token.outputs.token }} - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record + - id: commit + name: Commit and push the version env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: production - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.aab - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Check ABIs - if: steps.record.outputs.built != 'true' + GH_TOKEN: ${{ steps.app_token.outputs.token }} + APP_SLUG: ${{ steps.app_token.outputs.app-slug }} + RELEASE_VERSION: ${{ inputs.version }} run: | - abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" - if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then - echo "::error::Expected only ARM native libraries in the AAB, found $abis" - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if git diff --quiet -- apps/mobile/app.config.ts; then + echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." + else + user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" + git config user.name "${APP_SLUG}[bot]" + git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" + git add apps/mobile/app.config.ts + git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" + git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" fi + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. - - name: Keep the AAB - if: steps.record.outputs.built != 'true' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/t3code.aab - retention-days: 14 - if-no-files-found: error - - - name: Submit to Google Play - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + # Each store build runs in mobile-eas-production-build.yml, whose record job + # alone gets the token that pushes the tag. The group covers both of its jobs, + # and being its own group keeps later OTAs from waiting on a build. + android: + name: Android store build + needs: [production, version] + # Skipped when the production job failed: no store build after a failed OTA. + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.android_build == 'true' }} + concurrency: + group: mobile-android-store-build + cancel-in-progress: false + permissions: + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: android + profile: production + sha: ${{ needs.version.outputs.sha || needs.production.outputs.android_sha }} + tag: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build - needs: production + needs: [production, version] # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.ios_build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.ios_build == 'true' }} concurrency: group: mobile-ios-store-build cancel-in-progress: false permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - PROFILE: ${{ needs.production.outputs.ios_profile }} - BUILD_TAG: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - ref: ${{ needs.production.outputs.ios_sha }} - fetch-depth: 0 - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record - env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: ${{ env.PROFILE }} - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.ipa - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Submit to App Store Connect - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: ios: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: ios + profile: ${{ needs.production.outputs.ios_profile }} + sha: ${{ needs.version.outputs.sha || needs.production.outputs.ios_sha }} + tag: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8693e959055bf..92ec860dbe33c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1103,6 +1103,9 @@ jobs: if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }} runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 + # npm's trusted publisher for `t3` names this environment, which admits only + # main and v* tags. + environment: production permissions: contents: read id-token: write @@ -1191,9 +1194,6 @@ jobs: T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: @@ -1231,9 +1231,14 @@ jobs: - name: Refresh release lockfile run: vp install --lockfile-only --ignore-scripts + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} run: | set -euo pipefail @@ -1364,8 +1369,6 @@ jobs: deployment_url: ${{ steps.deploy.outputs.deployment_url }} project_id: ${{ steps.deploy.outputs.project_id }} env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout @@ -1382,9 +1385,13 @@ jobs: with: install-args: --filter=@t3tools/marketing... + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} run: | set -euo pipefail diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index 69db6b6025e8f..7d3f1efd57c13 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -39,11 +39,6 @@ jobs: (github.event.action != 'labeled' || github.event.label.name == 'preview:web') runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 - env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} - VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -54,6 +49,8 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false + # The Vercel CLI imports @vercel/config from here to read apps/web/vercel.ts. + # No dependency lifecycle script runs in this job. - name: Setup Vite+ uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: @@ -61,12 +58,18 @@ jobs: cache: true run-install: | args: + - --ignore-scripts - --filter=@t3tools/scripts... - --filter=@t3tools/web... - id: deploy name: Deploy preview shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} + VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} run: | set -euo pipefail diff --git a/docs/operations/03_release.md b/docs/operations/03_release.md index d213041d57eb5..73a63fdfd4dd3 100644 --- a/docs/operations/03_release.md +++ b/docs/operations/03_release.md @@ -47,7 +47,7 @@ Windows packages the bundled server and its unpacked native modules in `resource ### npm OIDC trusted publishing -Configure `t3` on npm with GitHub Actions Trusted Publishing for `.github/workflows/release.yml` (the workflow publishes only the `t3` launcher tarball via `npm publish --provenance`). +Configure `t3` on npm with GitHub Actions Trusted Publishing for `.github/workflows/release.yml` (the workflow publishes only the `t3` launcher tarball via `npm publish --provenance`). Set the publisher's environment to `production`, which `publish_cli` declares. ### Apple signing and notarization (macOS) From 784da01b2906aca88918c6221cb86fe332ab0f60 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 18:15:41 -0600 Subject: [PATCH 218/288] fix(web): Esc in Find in PDF clears it without closing the sheet (#41749) Co-authored-by: Julius Marminge --- .../files/PdfViewer.browser.test.tsx | 50 ++++++++++++++++++- apps/web/src/components/files/PdfViewer.tsx | 11 +++- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsx index 81bf3bcf91364..1563088cf32f4 100644 --- a/apps/web/src/components/files/PdfViewer.browser.test.tsx +++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx @@ -1,5 +1,8 @@ import { expect, it, vi } from "vite-plus/test"; -import { render } from "../../../test/render"; +import { userEvent } from "vite-plus/test/browser"; + +import { RightPanelSheet } from "~/components/RightPanelSheet"; +import { act, render } from "../../../test/render"; import "~/index.css"; // Vite serves the worker module through its transform with an inline source map (6.8 MB for @@ -333,3 +336,48 @@ it("follows a link to another page and exposes a web link", async () => { URL.revokeObjectURL(url); } }); + +it("Escape in Find in PDF clears it without closing the panel sheet", async () => { + const url = URL.createObjectURL(testPdf()); + const onCloseSheet = vi.fn(); + try { + await using screen = await render( + + + , + ); + const find = screen.getByRole("searchbox", { name: "Find in PDF" }); + await find.fill("quarterly"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + find.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + find + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(find).toHaveValue("quarterly"); + } + expect(find.element().getAttribute("type")).toBe("text"); + + await userEvent.keyboard("{Escape}"); + await expect.element(find).toHaveValue(""); + // Holding Escape repeats the keydown, which must not also close the sheet. + await act(() => { + find + .element() + .dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true }), + ); + }); + expect(onCloseSheet).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(onCloseSheet).toHaveBeenCalledOnce()); + } finally { + URL.revokeObjectURL(url); + } +}); diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index 9842a621c0302..3f0368d67cfb4 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -522,10 +522,12 @@ export default function PdfViewer(props: {
+ {/* Native search inputs clear on Escape even during IME composition. */} { + if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) + return; + if (!query && !event.repeat) return; + event.stopPropagation(); + setQuery(""); + }} />
{query ? ( From e3b79cd0bf9cdffd8d7dff24f43e77704ee621b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:17:50 -0800 Subject: [PATCH 219/288] fix: Windows system tools run by absolute path, and mobile links and shares are handled more strictly (#41767) Co-authored-by: Claude Fable 5.2 --- .../features/files/FileMarkdownPreview.tsx | 4 +- .../sharing/IncomingShareProvider.tsx | 30 +++++++----- .../sharing/incoming-share-model.test.ts | 29 +++++++++++ .../features/sharing/incoming-share-model.ts | 28 +++++++++++ apps/mobile/src/lib/appLinking.test.ts | 10 ++++ apps/mobile/src/lib/appLinking.ts | 9 +++- apps/mobile/src/lib/openExternalUrl.test.ts | 15 +++++- apps/mobile/src/lib/openExternalUrl.ts | 11 +++++ apps/mobile/src/native/useOpenPullRequest.ts | 6 +-- apps/server/src/background/KeepAwake.test.ts | 9 ++++ apps/server/src/background/KeepAwake.ts | 8 +-- apps/server/src/cli/uninstall.ts | 6 ++- apps/server/src/cloud/bootService.test.ts | 42 ++++++++-------- apps/server/src/cloud/bootService.ts | 24 +++++---- apps/server/src/cloud/pinnedRuntime.ts | 3 +- .../src/device/deviceToolMaintenance.ts | 2 +- apps/server/src/legacyServerOwner.ts | 9 +++- .../src/mcp/toolkits/project/handlers.test.ts | 10 +++- .../src/mcp/toolkits/project/handlers.ts | 49 ++++++++++++------- apps/server/src/preview/PortScanner.test.ts | 2 +- apps/server/src/preview/PortScanner.ts | 4 +- apps/server/src/process/SpawnWorker.ts | 13 +++-- apps/server/src/serverOwnership.ts | 2 +- apps/server/src/serviceLauncher.ts | 9 ++-- apps/server/src/terminal/Manager.ts | 3 +- apps/server/src/workspace/TaskFolders.ts | 3 +- apps/web/src/workspaceBasenameLookup.test.ts | 9 ++++ .../src/workspaceBasenameLookup.ts | 3 ++ .../src/server/AcpSessionRuntime.ts | 8 ++- packages/provider-pi/src/server/rpc.ts | 8 ++- packages/shared/package.json | 4 ++ packages/shared/src/windowsSystem.ts | 8 +++ 32 files changed, 291 insertions(+), 89 deletions(-) create mode 100644 packages/shared/src/windowsSystem.ts diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 23035511a5c2d..2e8d030d2b2f8 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -16,7 +16,7 @@ import { import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { tryOpenWebLink } from "../../lib/openExternalUrl"; import { FONT_FAMILIES } from "../../lib/fontFamilies"; import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; @@ -228,7 +228,7 @@ export function FileMarkdownPreview(props: { openMedia(href, true); }; const onLinkPress = (href: string) => { - if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link"); + if (!openMedia(href)) void tryOpenWebLink(href, "markdown-link"); }; const refreshControl = props.onRefresh ? ( diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx index 134e92e62f43a..dcfc3b99643b6 100644 --- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -18,7 +18,7 @@ import { CommonActions } from "@react-navigation/native"; import { buildIncomingShareDraft, - isShareFileUriUnderOwnedRoots, + isOwnedShareFileUri, selectIncomingShareAttachmentsForServer, type IncomingShareDestination, type IncomingShareDraft, @@ -98,19 +98,25 @@ async function readFileSize(uri: string): Promise { return new File(uri).size ?? null; } -async function removeOwnedFile(uri: string): Promise { +/** `persisted` marks a copy this app saved itself, which needs no ownership check. */ +async function removeOwnedFile(uri: string, persisted = false): Promise { if (!uri.startsWith("file:")) { return; } try { const { File, Paths } = await import("expo-file-system"); // Delete only app-owned files; iOS open-in-place shares can reference the sender's original. - const ownedRootUris = [ - Paths.document.uri, - Paths.cache.uri, - ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), - ]; - if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) { + const owned = + persisted || + isOwnedShareFileUri(uri, { + platform: Platform.OS, + cacheUri: Paths.cache.uri, + otherRootUris: [ + Paths.document.uri, + ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), + ], + }); + if (!owned) { return; } const file = new File(uri); @@ -142,7 +148,7 @@ async function removeReplayedPayloadFiles(payloads: ReadonlyArray) uris.add(payload.contentUri); } } - await Promise.all([...uris].map(removeOwnedFile)); + await Promise.all([...uris].map((uri) => removeOwnedFile(uri))); } // Share the queue across remounts so lifecycle notifications cannot ingest one handoff twice. @@ -187,10 +193,12 @@ const incomingShareInbox = new IncomingShareInbox({ return { draft, cleanup: async () => { - await Promise.all([...cleanupUris].map(removeOwnedFile)); + await Promise.all( + [...cleanupUris].map((uri) => removeOwnedFile(uri, persistedUris.has(uri))), + ); }, rollback: async () => { - await Promise.all([...persistedUris].map(removeOwnedFile)); + await Promise.all([...persistedUris].map((uri) => removeOwnedFile(uri, true))); }, }; }, diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 7ca92b23c3208..7cab7a84da14e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -8,6 +8,7 @@ import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; import { buildIncomingShareDraft, hasIncomingShareContent, + isOwnedShareFileUri, isShareFileUriUnderOwnedRoots, selectIncomingShareAttachments, selectIncomingShareAttachmentsForServer, @@ -671,6 +672,34 @@ describe("share cleanup ownership", () => { ).toBe(false); }); + it("deletes only the resolver's share copies on Android", () => { + const data = "file:///data/user/0/codes.t3.app"; + const owned = (uri: string, platform = "android") => + isOwnedShareFileUri(uri, { + platform, + cacheUri: `${data}/cache/`, + otherRootUris: [`${data}/files/`], + }); + const copy = `${data}/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11`; + expect(owned(`file:${copy.slice("file://".length)}/report.pdf`)).toBe(true); + expect( + owned( + "file:///data/data/codes.t3.app/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11/a.png", + ), + ).toBe(true); + for (const uri of [ + `${data}/files/t3-composer-attachments/id-report.pdf`, + `${data}/files/SQLite/state.db`, + `${data}/cache/http-cache/journal`, + `${data}/cache/shared-notes/notes.txt`, + `${copy}/..%2F..%2Ffiles%2FSQLite%2Fstate.db`, + copy, + ]) { + expect(owned(uri)).toBe(false); + } + expect(owned(`${data}/files/SQLite/state.db`, "ios")).toBe(true); + }); + it("refuses non-file URIs and the owned root itself", () => { expect(isShareFileUriUnderOwnedRoots("content://shared/report", ownedRoots)).toBe(false); expect( diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 86c17c6059e0e..30a334ca46aaf 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -93,6 +93,34 @@ export function isShareFileUriUnderOwnedRoots( }); } +/** + * On Android only the native resolver's `shared-` copies are this app's to delete; other + * shared URIs are not copies. + */ +export function isOwnedShareFileUri( + uri: string, + owned: { + readonly platform: string; + readonly cacheUri: string; + readonly otherRootUris: ReadonlyArray; + }, +): boolean { + if (owned.platform !== "android") { + return isShareFileUriUnderOwnedRoots(uri, [owned.cacheUri, ...owned.otherRootUris]); + } + // The resolver reports its copy by canonical path, where `/data/user/0` is `/data/data`. + const canonical = (fileUri: string) => + normalizedFileUriPath(fileUri)?.replace(/^\/data\/user\/0\//, "/data/data/"); + const path = canonical(uri); + const cachePath = canonical(owned.cacheUri)?.replace(/\/*$/, "/"); + return ( + path !== undefined && + cachePath !== undefined && + path.startsWith(cachePath) && + /^shared-[\da-f-]{36}\/[^/]+$/i.test(path.slice(cachePath.length)) + ); +} + export interface IncomingShareFileReader { readonly readBase64: (uri: string) => Promise; readonly removeOwnedFile: (uri: string) => Promise | void; diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts index 75db18a2337b8..09db1de62056a 100644 --- a/apps/mobile/src/lib/appLinking.test.ts +++ b/apps/mobile/src/lib/appLinking.test.ts @@ -91,6 +91,16 @@ describe("draft deep links", () => { }); }); + it.each(["/new/draft", "/new/draft/branch"])("drops the checkout a %s link names", (path) => { + const project = { environmentId: "env-1", projectId: "project-1" }; + const linked = { ...project, branch: "other", worktreePath: "/elsewhere" }; + const name = path === "/new/draft" ? "Thread" : "NewTaskBranch"; + expect(restoreDraftLinkState({ routes: [{ name, params: linked }] }, path)?.routes[0]).toEqual({ + name: "Thread", + params: { draft: project }, + }); + }); + it("leaves live-thread and project-selection links unchanged", () => { const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] }; expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state); diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts index 570c86b36abf4..fc448b4d02ac4 100644 --- a/apps/mobile/src/lib/appLinking.ts +++ b/apps/mobile/src/lib/appLinking.ts @@ -35,7 +35,14 @@ export function restoreDraftLinkState( if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state; const target = state.routes.at(-1); if (!target) return state; - const draft = target.params ?? {}; + // The draft screen checks out its branch on mount; the checkout comes from the draft, not the link. + const { + branch: _branch, + worktreePath: _worktreePath, + ...draft + } = (target.params ?? {}) as { + readonly [param: string]: unknown; + }; const routes = state.routes.slice(0, -1); routes.push({ name: "Thread", params: { draft } }); if (pathname !== "new/draft") routes.push(target); diff --git a/apps/mobile/src/lib/openExternalUrl.test.ts b/apps/mobile/src/lib/openExternalUrl.test.ts index 1dd1ff7db002b..f14037d99205f 100644 --- a/apps/mobile/src/lib/openExternalUrl.test.ts +++ b/apps/mobile/src/lib/openExternalUrl.test.ts @@ -1,7 +1,7 @@ import { Linking } from "react-native"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { tryOpenExternalUrl } from "./openExternalUrl"; +import { tryOpenExternalUrl, tryOpenWebLink } from "./openExternalUrl"; vi.mock("react-native", () => ({ Linking: { openURL: vi.fn() }, @@ -34,3 +34,16 @@ describe("tryOpenExternalUrl", () => { expect(diagnostics).not.toContain("43123"); }); }); + +describe("tryOpenWebLink", () => { + it("opens web, mail and phone links only", async () => { + openURL.mockResolvedValue(undefined); + for (const url of ["https://example.com/a", "HTTP://example.com", "mailto:a@example.com"]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(true); + } + for (const url of ["otherapp://open", "intent://x#Intent;end", "/owner/repo", ""]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(false); + } + expect(openURL).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index 962769b184e33..d57442ac78045 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -61,3 +61,14 @@ export async function tryOpenExternalUrl( return false; } } + +/** + * For a link in rendered text, such as a pull request body: opens web, mail and phone links + * only. + */ +export async function tryOpenWebLink( + url: string, + target: ExternalUrlTarget = "external-link", +): Promise { + return /^(?:https?|mailto|tel):/i.test(url) && (await tryOpenExternalUrl(url, target)); +} diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.ts index b492ece6fbef5..aac80fb3004a4 100644 --- a/apps/mobile/src/native/useOpenPullRequest.ts +++ b/apps/mobile/src/native/useOpenPullRequest.ts @@ -7,7 +7,7 @@ import { import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useProjects, useThreadShell } from "../state/entities"; -import { tryOpenExternalUrl } from "../lib/openExternalUrl"; +import { tryOpenWebLink } from "../lib/openExternalUrl"; import { appAtomRegistry } from "../state/atom-registry"; import { environmentServerConfigsAtom } from "../state/server"; import { issueTrackerEnvironment } from "../state/issueTrackers"; @@ -59,7 +59,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean trackers: connections?._tag === "Success" ? connections.value : undefined, }) : null; - if (!issue || !environmentId) return tryOpenExternalUrl(url, "pull-request"); + if (!issue || !environmentId) return tryOpenWebLink(url, "pull-request"); const candidate = pullRequestCandidateForIssueLink(url, issue.ref); if (candidate) { const preview = await readPreview({ environmentId, input: candidate.target }); @@ -76,7 +76,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean return true; } // A dropped connection says nothing about what the link names; the browser knows. - if (isAtomCommandInterrupted(preview)) return tryOpenExternalUrl(url, "pull-request"); + if (isAtomCommandInterrupted(preview)) return tryOpenWebLink(url, "pull-request"); } const issueParams = { environmentId, diff --git a/apps/server/src/background/KeepAwake.test.ts b/apps/server/src/background/KeepAwake.test.ts index 8984102729cec..628590930e470 100644 --- a/apps/server/src/background/KeepAwake.test.ts +++ b/apps/server/src/background/KeepAwake.test.ts @@ -34,3 +34,12 @@ describe("KeepAwake.holdWhileWanted", () => { }), ); }); + +describe("KeepAwake.inhibitorCommand", () => { + it("runs PowerShell by its System32 path on Windows", () => { + expect( + KeepAwake.inhibitorCommand("win32", 1, false, { SYSTEMROOT: String.raw`D:\Windows` }) + ?.command, + ).toBe(String.raw`D:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`); + }); +}); diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index f9d2cf3da7532..72e5c1fbf031b 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -14,6 +14,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { forkParked } from "../serverActivation.ts"; import * as Settings from "../serverSettings.ts"; @@ -27,10 +28,11 @@ const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru - * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and * exits on its own if the server dies. */ -function inhibitorCommand( +export function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, isWsl: boolean, + env: NodeJS.ProcessEnv, ): | { readonly command: string; @@ -77,7 +79,7 @@ function inhibitorCommand( }; case "win32": return { - command: "powershell.exe", + command: windowsPowerShellPath(env), args: [ "-NoProfile", "-NonInteractive", @@ -145,7 +147,7 @@ export const layer = Layer.effectDiscard( Effect.map((release) => release.toLowerCase().includes("microsoft")), Effect.orElseSucceed(() => false), )); - const command = inhibitorCommand(platform, process.pid, isWsl); + const command = inhibitorCommand(platform, process.pid, isWsl, yield* HostProcess.Environment); if (command === undefined) return; const settings = yield* Settings.ServerSettingsService; const events = yield* OrchestrationEventStore.OrchestrationEventStore; diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index ae884caa63fe7..07978299b4642 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -23,6 +23,7 @@ import { import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( @@ -281,7 +282,10 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { // Windows refuses to unlink this running executable; a detached shell removes it after exit. if (platform === "win32") { const runtimeDir = plan.runtimeDir; - const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe"; + const comspec = + environment["ComSpec"] ?? + environment["COMSPEC"] ?? + windowsSystem32Path(environment, "cmd.exe"); const notScheduled = () => new CliUninstallError({ reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index c327464ddfa24..309f90f4bd26a 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -53,6 +53,8 @@ vi.mock("node:fs", async (importOriginal) => { }; }); +const SCHTASKS = "C:\\Windows\\System32\\schtasks.exe"; + const windowsTaskOptions = { userId: "PC\\theo", homeDir: "C:\\Users\\theo", @@ -251,13 +253,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( command === "systemctl --user disable --now t3code.service" || command === "systemctl --user restart --no-block t3code.service" || command.startsWith("launchctl bootout --wait ") || - (input.command === "schtasks" && input.args[0] === "/End") + (input.command === SCHTASKS && input.args[0] === "/End") ) { markersAtStop.push(yield* fs.exists(marker)); } if ( command === "systemctl --user daemon-reload" || - (input.command === "schtasks" && input.args[0] === "/Create") + (input.command === SCHTASKS && input.args[0] === "/Create") ) { markersAtPreparation.push(yield* fs.exists(marker)); } @@ -276,8 +278,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( } if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; const taskMissing = - input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; - if (input.command === "schtasks" && !failed) { + input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; + if (input.command === SCHTASKS && !failed) { if (input.args[0] === "/Create") { const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; @@ -318,7 +320,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( }) : input.args[0] === "--version" ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n` - : input.command === "schtasks" && input.args.includes("/XML") + : input.command === SCHTASKS && input.args.includes("/XML") ? control.task?.enabled === false ? disabledServiceTask(control.task.xml) : (control.task?.xml ?? "") @@ -1581,9 +1583,9 @@ process.disconnect(); protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.2.3", }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /Run /TN t3code-PC-theo", + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual([ + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); // No launcher holds the lock here. expect(yield* service.status).toMatchObject({ @@ -1593,7 +1595,7 @@ process.disconnect(); }); // A task that Task Scheduler refuses to delete stays installed, so a retry finds it. - control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F"; + control.failCommand = `${SCHTASKS} /Delete /TN t3code-PC-theo /F`; expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect((yield* service.status).installed).toBe(true); control.failCommand = undefined; @@ -1601,9 +1603,9 @@ process.disconnect(); commands.length = 0; expect(yield* service.uninstall).toBe(true); expect(commands).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", - "schtasks /Delete /TN t3code-PC-theo /F", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Delete /TN t3code-PC-theo /F`, ]); expect(control.task).toBeUndefined(); expect((yield* service.status).installed).toBe(false); @@ -1643,11 +1645,11 @@ process.disconnect(); commands.length = 0; yield* service.withStopped(Effect.sync(() => commands.push("repair"))); expect(commands.filter((command) => !command.includes("/Query"))).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, "repair", - "schtasks /Change /TN t3code-PC-theo /ENABLE", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /ENABLE`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); }), ); @@ -1668,14 +1670,14 @@ process.disconnect(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const handoff = [ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /End /TN t3code-PC-theo", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]; commands.length = 0; expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff); + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual(handoff); expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4"); expect( yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 90d01b10526f3..f95bae2a811aa 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -482,6 +482,8 @@ interface WindowsTaskSteps { readonly remove: Effect.Effect; } +const schtasksPath = (systemRoot: string) => `${systemRoot}\\System32\\schtasks.exe`; + function schtasksManager(input: { readonly path: Path.Path; readonly homeDir: string; @@ -489,13 +491,14 @@ function schtasksManager(input: { readonly steps: WindowsTaskSteps; }): BootServiceManager { const unitPath = scheduledTaskPath(input.path, input.session.localAppData); + const schtasks = schtasksPath(input.session.systemRoot); const task = ["/TN", input.session.taskName]; const register = { step: "registering the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Create", "/XML", unitPath, ...task, "/F"], }; - const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] }; + const run = { step: "starting the service", command: schtasks, args: ["/Run", ...task] }; const stop: ReadonlyArray = [ { step: "disabling the scheduled task", run: input.steps.disable }, { @@ -519,7 +522,7 @@ function schtasksManager(input: { restart: [ { step: "enabling the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Change", ...task, "/ENABLE"], }, { ...run, step: "restarting the service after a failed update" }, @@ -531,7 +534,7 @@ function schtasksManager(input: { restart: [ { step: "ending the scheduled task", - command: "schtasks", + command: schtasks, args: ["/End", ...task], optional: true, }, @@ -903,6 +906,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir, ); const windowsTask = ["/TN", windowsSession.taskName]; + const schtasks = schtasksPath(windowsSession.systemRoot); /** Runs a command that changes the task; a task that is not registered has nothing to change. */ const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* ( step: string, @@ -911,12 +915,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const toError = (cause: unknown) => new BootServiceCommandError({ step, cause }); const changed = yield* runner - .run({ command: "schtasks", args: [verb, ...windowsTask, flag] }) + .run({ command: schtasks, args: [verb, ...windowsTask, flag] }) .pipe(Effect.mapError(toError)); if (changed.code === 0) return; const queried = yield* runner .run({ - command: "schtasks", + command: schtasks, args: ["/Query", ...windowsTask, "/HRESULT"], timeout: Duration.seconds(5), }) @@ -951,14 +955,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { unit: string, ) { const register = (xmlPath: string) => - runStep("registering the scheduled task", "schtasks", [ + runStep("registering the scheduled task", schtasks, [ "/Create", "/XML", xmlPath, ...windowsTask, "/F", ]); - const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]); + const registered = yield* probe(schtasks, ["/Query", ...windowsTask, "/XML"]); if ( Option.isSome(registered) && registered.value.code === 0 && @@ -981,7 +985,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Task Scheduler then reports the task stopped at once, so the lock says when it really is. const stopWindowsLauncher = Effect.gen(function* () { const unit = yield* readUnit().pipe(Effect.option); - yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); + yield* runner.run({ command: schtasks, args: ["/End", ...windowsTask] }).pipe(Effect.ignore); yield* Effect.tryPromise({ try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), catch: (cause) => @@ -1215,7 +1219,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const [task, running] = yield* Effect.all( [ - probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]), + probe(schtasks, ["/Query", "/TN", windowsSession.taskName, "/XML"]), Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))), ], { concurrency: "unbounded" }, diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index e544852ef3dcc..06e320bc314ad 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -25,6 +25,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts"; const PINNED_RUNTIME_DIR = "runtime"; @@ -792,7 +793,7 @@ const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables") .run({ ...(platform === "win32" ? { - command: "powershell.exe", + command: windowsPowerShellPath(yield* HostProcess.Environment), args: [ "-NoProfile", "-NonInteractive", diff --git a/apps/server/src/device/deviceToolMaintenance.ts b/apps/server/src/device/deviceToolMaintenance.ts index 2832071d099d0..7ff3a961eee9d 100644 --- a/apps/server/src/device/deviceToolMaintenance.ts +++ b/apps/server/src/device/deviceToolMaintenance.ts @@ -65,7 +65,7 @@ function pruneTools(root, specs, flat) { return withToolMaintenance(root, () => { // Keep installs used by any running helper, including older T3 releases. const scan = process.platform === 'win32' - ? require('node:child_process').spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) + ? require('node:child_process').spawnSync((process.env.SystemRoot || process.env.windir || 'C:\\Windows') + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) : require('node:child_process').spawnSync('ps', ['-ax', '-o', 'command='], { encoding: 'utf8', timeout: 10000 }); if (scan.status !== 0 || !scan.stdout) return; for (const [name, required] of specs) { diff --git a/apps/server/src/legacyServerOwner.ts b/apps/server/src/legacyServerOwner.ts index 9ed24c9c838f2..0b0b195ad38e7 100644 --- a/apps/server/src/legacyServerOwner.ts +++ b/apps/server/src/legacyServerOwner.ts @@ -1,9 +1,14 @@ // Effect-free so the service launcher shares the pre-lock owner identity check with server startup. +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; -export const legacyOwnerStartTimeCommand = (pid: number, platform: NodeJS.Platform) => { +export const legacyOwnerStartTimeCommand = ( + pid: number, + platform: NodeJS.Platform, + hostEnv: NodeJS.ProcessEnv, +) => { const windows = platform === "win32"; return { - command: windows ? "powershell.exe" : "ps", + command: windows ? windowsPowerShellPath(hostEnv) : "ps", args: windows ? [ "-NoProfile", diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index d03b038ee0780..37fbdcf12cbf8 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -567,10 +567,14 @@ it.effect("a launch binds only an existing checkout that is one of the project's Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }); + // Git registers resolved paths, and a launch keeps the registered one. + const root = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }), + ); const repo = path.join(root, "repo"); const worktree = path.join(root, "feature"); const outside = path.join(root, "outside"); + const alias = path.join(root, "alias"); yield* fileSystem.makeDirectory(repo); yield* fileSystem.makeDirectory(outside); @@ -615,9 +619,13 @@ it.effect("a launch binds only an existing checkout that is one of the project's code: "invalid_request", }); } + // The thread keeps the registered worktree path when launched through a link to it. + yield* fileSystem.symlink(worktree, alias); + expect((yield* launchInto(alias)).at(-1)?.result).toMatchObject({ projectId }); expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([ { type: "existing_worktree", worktreePath: worktree }, { type: "existing_worktree", worktreePath: repo }, + { type: "existing_worktree", worktreePath: worktree }, ]); yield* fileSystem.remove(worktree, { recursive: true }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 511dcfe26c3df..f92df228a422f 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -87,24 +87,29 @@ function worktreeCheckHint( }`; } -/** Require project worktrees so launches cannot target arbitrary host directories. */ -const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( +/** + * Require project worktrees so launches cannot target arbitrary host directories. Returns the + * path Git registered, so the thread stays bound to that worktree. + */ +const projectWorktreePath = Effect.fn("mcp.assertProjectWorktree")(function* ( workspaceRoot: string, worktreePath: string, ) { const git = yield* GitVcsDriver.GitVcsDriver; const fileSystem = yield* FileSystem.FileSystem; const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path)); - const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe( - Effect.flatMap((paths) => Effect.forEach(paths, real)), - Effect.orElseSucceed((): ReadonlyArray => []), - ); - if (!worktrees.includes(yield* real(worktreePath))) - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", - }); + const registered = yield* git + .listWorktreePaths(workspaceRoot) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const requested = yield* real(worktreePath); + for (const candidate of registered) { + if ((yield* real(candidate)) === requested) return candidate; + } + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", + }); }); /** The composer falls back to the project's t3.json when no setting picks the mode. */ @@ -307,15 +312,23 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }), ), ); - if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") - yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); + const workspaceStrategy = + project !== undefined && input.workspaceStrategy?.type === "existing_worktree" + ? { + ...input.workspaceStrategy, + worktreePath: yield* projectWorktreePath( + project.workspaceRoot, + input.workspaceStrategy.worktreePath, + ), + } + : input.workspaceStrategy; if (!replaying && input.modelSelection !== undefined) { const { instanceId, model } = input.modelSelection; const registry = yield* ProviderRegistry.ProviderRegistry; // The thread runs in this folder, whose own provider config can add models. const cwd = - input.workspaceStrategy?.type === "existing_worktree" - ? input.workspaceStrategy.worktreePath + workspaceStrategy?.type === "existing_worktree" + ? workspaceStrategy.worktreePath : project?.workspaceRoot; const requireModel = ( providers: ReadonlyArray, @@ -357,14 +370,14 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // An outside caller that names no workspace follows the new-threads-in-a-worktree // default, as the composer does. const requestedStrategy = - input.workspaceStrategy === undefined && + workspaceStrategy === undefined && caller === undefined && project !== undefined && projectSettings !== undefined && (projectSettings.defaultThreadEnvMode ?? (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree" ? yield* defaultWorktreeStrategy(project.workspaceRoot) - : input.workspaceStrategy; + : workspaceStrategy; // An omitted startFromOrigin follows the new-worktree setting, as the composer and // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base. const strategy = diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 52636a342900f..b7f2f139e2011 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -685,7 +685,7 @@ effectIt.effect("ignores a partial Windows netstat snapshot when one query exits layerNoProc, Layer.succeed(ProcessRunner.ProcessRunner, { run: (input) => { - if (input.command === "tasklist.exe") { + if (input.command === String.raw`C:\Windows\System32\tasklist.exe`) { return Effect.succeed( processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'), ); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index db5dd3fa9e654..bbbd6bf53db92 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -845,12 +846,13 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ); const cachedPids = new Set(cached.map(([pid]) => pid)); const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS; + const tasklist = windowsSystem32Path(yield* HostProcess.Environment, "tasklist.exe"); const fetched = yield* Effect.forEach( [...pids].filter((pid) => !cachedPids.has(pid)), (pid) => processRunner .run({ - command: "tasklist.exe", + command: tasklist, args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS), maxOutputBytes: 64 * 1024, diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts index 5a391ab18ca1b..58373b5bdc0a8 100644 --- a/apps/server/src/process/SpawnWorker.ts +++ b/apps/server/src/process/SpawnWorker.ts @@ -8,6 +8,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; // Windows runs CreateProcess synchronously on the calling thread, and antivirus or a busy disk can // hold it for seconds; Linux's spawn waits for chdir and the PATH search, which a hung mount @@ -503,10 +504,14 @@ class SpawnWorkerPool { if (!killed) killPid(); done(); }; - this.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { - stdio: "ignore", - windowsHide: true, - }) + this.spawn( + windowsSystem32Path(process.env, "taskkill.exe"), + ["/pid", String(pid), "/T", "/F"], + { + stdio: "ignore", + windowsHide: true, + }, + ) .on("error", () => finish(false)) .on("exit", (code) => finish(code === 0)); } diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 20bb46a45e66e..c39c4ee4428ff 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -88,7 +88,7 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( const runner = yield* ProcessRunner.ProcessRunner; const result = yield* runner .run({ - ...legacyOwnerStartTimeCommand(state.pid, platform), + ...legacyOwnerStartTimeCommand(state.pid, platform, yield* HostProcess.Environment), timeout: Duration.seconds(2), maxOutputBytes: 16_384, }) diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 44220f2c4b148..61e52b19d63f6 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -9,6 +9,7 @@ import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -137,8 +138,10 @@ export interface ServiceUnit { readonly reload: () => Promise; } +const SCHTASKS = () => windowsSystem32Path(process.env, "schtasks.exe"); + const runSchtasks = (...args: ReadonlyArray) => - NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, { + NodeUtil.promisify(NodeChildProcess.execFile)(SCHTASKS(), args, { windowsHide: true, timeout: 30_000, }); @@ -880,7 +883,7 @@ export async function stateDirOwned(baseDir: string): Promise { if (!Number.isFinite(recordedAt)) return true; // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; - const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform); + const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform, process.env); const output = await new Promise((resolve) => NodeChildProcess.execFile( command, @@ -1654,7 +1657,7 @@ export async function main(options: LauncherOptions = {}): Promise { // lets the next repeating trigger start the service again. if (windows && options.serviceUnit !== undefined) { const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? ""); - NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], { + NodeChildProcess.spawnSync(SCHTASKS(), ["/End", "/TN", taskName], { stdio: "ignore", windowsHide: true, }); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 92600d0a326a8..a27f6b1d03447 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -918,11 +918,12 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps ProcessRunner.ProcessRunner > { const processRunner = yield* ProcessRunner.ProcessRunner; + const powershell = windowsPowerShellPath(yield* HostProcess.Environment); const command = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; const result = yield* processRunner .run({ - command: "powershell.exe", + command: powershell, args: ["-NoProfile", "-NonInteractive", "-Command", command], timeout, maxOutputBytes: 262_144, diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 75c12d8a7409b..b202bd38d7f65 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -14,6 +14,7 @@ import { import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import * as Cause from "effect/Cause"; @@ -309,7 +310,7 @@ const make = Effect.gen(function* () { processes .run({ operation: "TaskFolders.worktreeLayout", - command: onWindows ? "cmd.exe" : "sh", + command: onWindows ? windowsSystem32Path(hostEnvironment, "cmd.exe") : "sh", args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command], cwd: taskFolder.projectRoot, env: { diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 7c1d17587813e..0930fecde82d0 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -222,6 +222,15 @@ describe("agentWorkingDirectories", () => { ), ).toEqual(["/work/d"]); }); + + it("leaves network shares out of the search roots", () => { + expect( + directories( + "cd //files.example/share", + String.raw`cd '\\files.example\share'; cd C:\work\repo`, + ), + ).toEqual([String.raw`C:\work\repo`]); + }); }); // regression: #35337 a bare file name the agent cited from a subfolder of an unregistered checkout diff --git a/packages/client-runtime/src/workspaceBasenameLookup.ts b/packages/client-runtime/src/workspaceBasenameLookup.ts index ae55263fb2bd4..7d50a12304c2e 100644 --- a/packages/client-runtime/src/workspaceBasenameLookup.ts +++ b/packages/client-runtime/src/workspaceBasenameLookup.ts @@ -1,6 +1,7 @@ import { FILESYSTEM_METADATA_BATCH_LIMIT } from "@t3tools/contracts"; import { isAbsolutePath, + isNetworkPath, isWindowsAbsolutePath, resolveWorkspaceFilePath, } from "@t3tools/shared/path"; @@ -229,6 +230,8 @@ function literalDirectory(operand: string): string | null { const path = /^["']/.test(operand) ? operand.slice(1, -1) : operand; // The shell would expand these, and only it knows to what. if (!isAbsolutePath(path) || /[$`*?[\]{}"']/.test(path)) return null; + // Search roots are local directories; the server stats each one. + if (isNetworkPath(path)) return null; return path.includes("\\") && !isWindowsAbsolutePath(path) ? null : path; } diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index b08eef243fc3e..fb1cd976a9a65 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -31,6 +31,7 @@ import * as EffectAcpProtocol from "effect-acp/protocol"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { AgentScope, AgentScopeThreadId, RAISE_OOM_SCORE_LINE } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { appendAcpStderrTail, sanitizeAcpStderrExcerpt } from "./stderr.ts"; @@ -1044,7 +1045,12 @@ const terminateWindowsProcessTreeWithTaskkill = ( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const taskkill = yield* spawner.spawn( - ChildProcess.make("taskkill", ["/PID", String(pid), "/T", "/F"]), + ChildProcess.make(windowsSystem32Path(yield* HostProcess.Environment, "taskkill.exe"), [ + "/PID", + String(pid), + "/T", + "/F", + ]), ); const outputFiber = yield* Stream.decodeText(taskkill.all).pipe( Stream.mkString, diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.ts index 3cdb2058f1cf3..f51bc493535b6 100644 --- a/packages/provider-pi/src/server/rpc.ts +++ b/packages/provider-pi/src/server/rpc.ts @@ -12,6 +12,7 @@ import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { MAX_TOOL_OUTPUT_IMAGES, @@ -272,7 +273,12 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp const terminateWindowsTree = Effect.gen(function* () { if (hasExited()) return; const taskkill = yield* spawner.spawn( - ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]), + ChildProcess.make(windowsSystem32Path(yield* HostProcess.Environment, "taskkill.exe"), [ + "/PID", + String(child.pid), + "/T", + "/F", + ]), ); yield* taskkill.exitCode; }).pipe(Effect.scoped, Effect.ignore); diff --git a/packages/shared/package.json b/packages/shared/package.json index d12cd9b003982..f51761a9f8188 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -107,6 +107,10 @@ "types": "./src/shell.ts", "import": "./src/shell.ts" }, + "./windowsSystem": { + "types": "./src/windowsSystem.ts", + "import": "./src/windowsSystem.ts" + }, "./envTrampoline": { "types": "./src/envTrampoline.ts", "import": "./src/envTrampoline.ts" diff --git a/packages/shared/src/windowsSystem.ts b/packages/shared/src/windowsSystem.ts new file mode 100644 index 0000000000000..1d74ccdc5e5a3 --- /dev/null +++ b/packages/shared/src/windowsSystem.ts @@ -0,0 +1,8 @@ +// Effect-free so the standalone service launcher can use it. + +/** Windows system tools are run by absolute path, independent of PATH and the working directory. */ +export const windowsSystem32Path = (env: NodeJS.ProcessEnv, executable: string) => + `${env.SystemRoot || env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\${executable}`; + +export const windowsPowerShellPath = (env: NodeJS.ProcessEnv) => + windowsSystem32Path(env, String.raw`WindowsPowerShell\v1.0\powershell.exe`); From 08580964723e68ef71dcdd5cbda3fcf94929efac Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:20:13 -0800 Subject: [PATCH 220/288] fix: Forgejo and GitCafe merges carry the expected head commit (#41773) Co-authored-by: Claude Fable 5.2 --- ...equestDetailPanel.permissions.browser.test.tsx | 15 ++++++++++++++- .../pullRequest/PullRequestDetailPanel.tsx | 7 +++++-- .../src/server/ForgejoPullRequestProvider.ts | 3 +++ .../server/ForgejoSourceControlProvider.test.ts | 9 +++++++++ .../src/server/GitCafePullRequestProvider.test.ts | 9 +++++++-- .../src/server/GitCafePullRequestProvider.ts | 2 +- 6 files changed, 39 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx index e7a4733ae9410..c73254811aab8 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx @@ -223,9 +223,22 @@ it("keeps a merge and a review on the head the reader was shown until they load await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"])); expect(sent("action")).toEqual(["shown-head"]); + // The pin moves once the reload has been asked of the host, not at the click. + const reload = Promise.withResolvers<{ _tag: "Success"; value: undefined }>(); + command.mockImplementation((call) => + call?.input?.reference === undefined + ? Promise.resolve({ _tag: "Success", value: undefined }) + : reload.promise, + ); await screen.getByRole("button", { name: "Load new commits" }).click(); await merge(); - await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "pushed-head"])); + await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "shown-head"])); + reload.resolve({ _tag: "Success", value: undefined }); + await expect.element(screen.getByText(/still applies to/)).not.toBeInTheDocument(); + await merge(); + await vi.waitFor(() => + expect(sent("action")).toEqual(["shown-head", "shown-head", "pushed-head"]), + ); }); it("reads the first diff page once the pointer rests on the Code tab", async () => { diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 110aac26cde5c..8a7e7bb2fe96e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -1931,9 +1931,12 @@ export function PullRequestDetailPanel({
} @@ -295,13 +377,21 @@ export function PullRequestStackMenu({ term: changeRequestTermKind(terminology), }, ) - : gt( - "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", - { - count: unmerged.length, - term: changeRequestTermKind(terminology), - }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: mergeLayers.length, + term: changeRequestTermKind(terminology), + }, + ) + : gt( + "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: unmerged.length, + term: changeRequestTermKind(terminology), + }, + )} {confirmation === "merge" @@ -314,10 +404,20 @@ export function PullRequestStackMenu({ host: hostLabel, }, ) - : gt( - "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", - { base: stack.base }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + { + number: reference.number, + base: stack.base, + method: mergeMethod, + host: hostLabel, + }, + ) + : gt( + "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", + { base: stack.base }, + )} @@ -337,7 +437,11 @@ export function PullRequestStackMenu({ Cancel diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 36f57764ea37a..4d3d656f33916 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Weiteres Konto", "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", "99963c0142e17f00": "Für das neue {tracker}-Konto.", - "6d8e4ebc889bace9": "Konto hinzufügen" + "6d8e4ebc889bace9": "Konto hinzufügen", + "8a883c4fbc127b68": "Auto-Merge für den Stack wird aktiviert...", + "5fb2a26ae31e8983": "Auto-Merge für den Stack konnte nicht aktiviert werden", + "986d0dcbf4dd0098": "Auto-Merge für den Stack aktiviert", + "f3ed1f63c8a3eef2": "{host} mergt den Stack bis #{number}, sobald die Anforderungen erfüllt sind.", + "bd536a0a1754f6cb": "Auto-Merge für den Stack konnte nicht abgebrochen werden", + "bb90ac3b2f3a72d5": "Der Host hat das Abbrechen des Auto-Merge abgelehnt. Aktualisiere und versuche es erneut.", + "9c28753c777c37b7": "{count, plural, one {Auto-Merge für {count} {term, select, mr {Merge Request} cr {Änderungsanfrage} other {Pull Request}}?} other {Auto-Merge für {count} {term, select, mr {Merge Requests} cr {Änderungsanfragen} other {Pull Requests}}?}}", + "a86b49982e18784d": "#{number} und die darunterliegenden nicht gemergten Ebenen per {method} in {base} mergen, sobald jede davon die Anforderungen auf {host} erfüllt. Das kann sofort passieren.", + "b1afda5c964deee4": [ + "Auto-Merge für Stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Auto-Merge für Stack abbrechen", + "012c67c7f1a99e33": "Auto-Merge für Stack" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 22791e2badd65..da9e327abf64f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12796,5 +12796,24 @@ "99d51127f573296b": "Another account", "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", "99963c0142e17f00": "For the new {tracker} account.", - "6d8e4ebc889bace9": "Add account" + "6d8e4ebc889bace9": "Add account", + "8a883c4fbc127b68": "Enabling stack auto-merge...", + "5fb2a26ae31e8983": "Could not enable stack auto-merge", + "986d0dcbf4dd0098": "Stack auto-merge enabled", + "f3ed1f63c8a3eef2": "{host} merges the stack through #{number} once its requirements are met.", + "bd536a0a1754f6cb": "Could not cancel stack auto-merge", + "bb90ac3b2f3a72d5": "The host refused to cancel auto-merge. Refresh and try again.", + "9c28753c777c37b7": "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + "a86b49982e18784d": "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + "b1afda5c964deee4": [ + "Auto-merge stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancel stack auto-merge", + "012c67c7f1a99e33": "Auto-merge stack" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2c68ad496ac5f..ff24104e8075f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12782,5 +12782,24 @@ "99d51127f573296b": "Otra cuenta", "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", - "6d8e4ebc889bace9": "Añadir cuenta" + "6d8e4ebc889bace9": "Añadir cuenta", + "8a883c4fbc127b68": "Activando la fusión automática de la pila...", + "5fb2a26ae31e8983": "No se pudo activar la fusión automática de la pila", + "986d0dcbf4dd0098": "Fusión automática de la pila activada", + "f3ed1f63c8a3eef2": "{host} fusionará la pila hasta #{number} cuando se cumplan sus requisitos.", + "bd536a0a1754f6cb": "No se pudo cancelar la fusión automática de la pila", + "bb90ac3b2f3a72d5": "El host rechazó cancelar la fusión automática. Actualiza e inténtalo de nuevo.", + "9c28753c777c37b7": "{count, plural, one {¿Fusionar automáticamente {count} {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}?} other {¿Fusionar automáticamente {count} {term, select, mr {merge requests} cr {solicitudes de cambios} other {pull requests}}?}}", + "a86b49982e18784d": "Fusiona #{number} y sus capas sin fusionar de debajo en {base} mediante {method} cuando todas cumplan los requisitos de {host}. Puede ocurrir de inmediato.", + "b1afda5c964deee4": [ + "Fusión automática de la pila (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar la fusión automática de la pila", + "012c67c7f1a99e33": "Fusión automática de la pila" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index cb4db84726d56..64b28506bfe6a 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Autre compte", "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", "99963c0142e17f00": "Pour le nouveau compte {tracker}.", - "6d8e4ebc889bace9": "Ajouter un compte" + "6d8e4ebc889bace9": "Ajouter un compte", + "8a883c4fbc127b68": "Activation de la fusion automatique de la pile...", + "5fb2a26ae31e8983": "Impossible d’activer la fusion automatique de la pile", + "986d0dcbf4dd0098": "Fusion automatique de la pile activée", + "f3ed1f63c8a3eef2": "{host} fusionnera la pile jusqu’à #{number} dès que ses conditions seront remplies.", + "bd536a0a1754f6cb": "Impossible d’annuler la fusion automatique de la pile", + "bb90ac3b2f3a72d5": "L’hôte a refusé d’annuler la fusion automatique. Actualisez et réessayez.", + "9c28753c777c37b7": "{count, plural, one {Fusionner automatiquement {count} {term, select, mr {merge request} cr {demande de modification} other {pull request}} ?} other {Fusionner automatiquement {count} {term, select, mr {merge requests} cr {demandes de modification} other {pull requests}} ?}}", + "a86b49982e18784d": "Fusionner #{number} et ses couches non fusionnées inférieures dans {base} avec {method} dès que chacune remplit les conditions de {host}. Cela peut se produire immédiatement.", + "b1afda5c964deee4": [ + "Fusion automatique de la pile (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Annuler la fusion automatique de la pile", + "012c67c7f1a99e33": "Fusion automatique de la pile" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 01c10337742d3..f4c1b792d77e2 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12728,5 +12728,24 @@ "99d51127f573296b": "別のアカウント", "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", "99963c0142e17f00": "新しい {tracker} アカウント用です。", - "6d8e4ebc889bace9": "アカウントを追加" + "6d8e4ebc889bace9": "アカウントを追加", + "8a883c4fbc127b68": "スタックの自動マージを有効にしています...", + "5fb2a26ae31e8983": "スタックの自動マージを有効にできませんでした", + "986d0dcbf4dd0098": "スタックの自動マージを有効にしました", + "f3ed1f63c8a3eef2": "要件が満たされると、{host} が #{number} までのスタックをマージします。", + "bd536a0a1754f6cb": "スタックの自動マージをキャンセルできませんでした", + "bb90ac3b2f3a72d5": "ホストが自動マージのキャンセルを拒否しました。更新してもう一度お試しください。", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {マージリクエスト {count} 件を自動マージしますか?} cr {変更リクエスト {count} 件を自動マージしますか?} other {プルリクエスト {count} 件を自動マージしますか?}}}}", + "a86b49982e18784d": "#{number} と、その下の未マージのレイヤーがすべて {host} の要件を満たしたら、{method} で {base} にマージします。すぐにマージされる場合があります。", + "b1afda5c964deee4": [ + "スタックを自動マージ (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "スタックの自動マージをキャンセル", + "012c67c7f1a99e33": "スタックを自動マージ" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index eb4cf8b1c5273..0ef52c37295fc 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12724,5 +12724,24 @@ "99d51127f573296b": "다른 계정", "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", "99963c0142e17f00": "새 {tracker} 계정용입니다.", - "6d8e4ebc889bace9": "계정 추가" + "6d8e4ebc889bace9": "계정 추가", + "8a883c4fbc127b68": "스택 자동 병합을 켜는 중...", + "5fb2a26ae31e8983": "스택 자동 병합을 켤 수 없습니다", + "986d0dcbf4dd0098": "스택 자동 병합을 켰습니다", + "f3ed1f63c8a3eef2": "요구 사항이 충족되면 {host}에서 #{number}까지 스택을 병합합니다.", + "bd536a0a1754f6cb": "스택 자동 병합을 취소할 수 없습니다", + "bb90ac3b2f3a72d5": "호스트가 자동 병합 취소를 거부했습니다. 새로 고친 후 다시 시도하세요.", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} {count}개를 자동 병합할까요?}}", + "a86b49982e18784d": "#{number}와(과) 그 아래의 병합되지 않은 레이어가 모두 {host}의 요구 사항을 충족하면 {method}(으)로 {base}에 병합합니다. 바로 병합될 수도 있습니다.", + "b1afda5c964deee4": [ + "스택 자동 병합(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "스택 자동 병합 취소", + "012c67c7f1a99e33": "스택 자동 병합" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 06eea3c29b995..c7354ff24613d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Outra conta", "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", "99963c0142e17f00": "Para a nova conta do {tracker}.", - "6d8e4ebc889bace9": "Adicionar conta" + "6d8e4ebc889bace9": "Adicionar conta", + "8a883c4fbc127b68": "Ativando o merge automático da pilha...", + "5fb2a26ae31e8983": "Não foi possível ativar o merge automático da pilha", + "986d0dcbf4dd0098": "Merge automático da pilha ativado", + "f3ed1f63c8a3eef2": "{host} vai mesclar a pilha até o #{number} quando os requisitos forem atendidos.", + "bd536a0a1754f6cb": "Não foi possível cancelar o merge automático da pilha", + "bb90ac3b2f3a72d5": "O host recusou o cancelamento do merge automático. Atualize e tente novamente.", + "9c28753c777c37b7": "{count, plural, one {Mesclar automaticamente {count} {term, select, mr {merge request} cr {solicitação de alteração} other {pull request}}?} other {Mesclar automaticamente {count} {term, select, mr {merge requests} cr {solicitações de alteração} other {pull requests}}?}}", + "a86b49982e18784d": "Mescla o #{number} e as camadas não mescladas abaixo dele em {base} usando {method} quando todas atenderem aos requisitos de {host}. Isso pode acontecer imediatamente.", + "b1afda5c964deee4": [ + "Merge automático da pilha (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar merge automático da pilha", + "012c67c7f1a99e33": "Merge automático da pilha" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 44148970bd468..20e9a76a10fa1 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Другой аккаунт", "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", "99963c0142e17f00": "Для нового аккаунта {tracker}.", - "6d8e4ebc889bace9": "Добавить аккаунт" + "6d8e4ebc889bace9": "Добавить аккаунт", + "8a883c4fbc127b68": "Включение автослияния стека...", + "5fb2a26ae31e8983": "Не удалось включить автослияние стека", + "986d0dcbf4dd0098": "Автослияние стека включено", + "f3ed1f63c8a3eef2": "{host} сольёт стек до #{number}, когда будут выполнены требования.", + "bd536a0a1754f6cb": "Не удалось отменить автослияние стека", + "bb90ac3b2f3a72d5": "Хост отказался отменить автослияние. Обновите и повторите попытку.", + "9c28753c777c37b7": "{count, plural, one {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?} few {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} many {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} other {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?}}", + "a86b49982e18784d": "#{number} и несмёрженные слои под ним будут слиты в {base} методом {method}, когда каждый из них выполнит требования {host}. Это может произойти сразу.", + "b1afda5c964deee4": [ + "Автослияние стека (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Отменить автослияние стека", + "012c67c7f1a99e33": "Автослияние стека" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 2bb20d01df420..946abe27ad7cd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12794,5 +12794,24 @@ "99d51127f573296b": "Ett konto till", "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", "99963c0142e17f00": "För det nya {tracker}-kontot.", - "6d8e4ebc889bace9": "Lägg till konto" + "6d8e4ebc889bace9": "Lägg till konto", + "8a883c4fbc127b68": "Aktiverar automatisk merge för stacken...", + "5fb2a26ae31e8983": "Kunde inte aktivera automatisk merge för stacken", + "986d0dcbf4dd0098": "Automatisk merge för stacken aktiverad", + "f3ed1f63c8a3eef2": "{host} mergar stacken till och med #{number} när kraven är uppfyllda.", + "bd536a0a1754f6cb": "Kunde inte avbryta automatisk merge för stacken", + "bb90ac3b2f3a72d5": "Värden vägrade avbryta den automatiska mergen. Uppdatera och försök igen.", + "9c28753c777c37b7": "{count, plural, one {Merga {count} {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}} automatiskt?} other {Merga {count} {term, select, mr {merge requests} cr {ändringsbegäranden} other {pull requests}} automatiskt?}}", + "a86b49982e18784d": "Merga #{number} och dess omergade lager under in i {base} med {method} när vart och ett uppfyller kraven på {host}. Det kan ske direkt.", + "b1afda5c964deee4": [ + "Merga stacken automatiskt (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Avbryt automatisk merge för stacken", + "012c67c7f1a99e33": "Merga stacken automatiskt" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 0def42b8dda67..34b76ab61689c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12806,5 +12806,24 @@ "99d51127f573296b": "其他账号", "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", "99963c0142e17f00": "用于新的 {tracker} 账号。", - "6d8e4ebc889bace9": "添加账号" + "6d8e4ebc889bace9": "添加账号", + "8a883c4fbc127b68": "正在启用堆叠自动合并…", + "5fb2a26ae31e8983": "无法启用堆叠自动合并", + "986d0dcbf4dd0098": "已启用堆叠自动合并", + "f3ed1f63c8a3eef2": "满足要求后,{host} 会合并截至 #{number} 的堆叠。", + "bd536a0a1754f6cb": "无法取消堆叠自动合并", + "bb90ac3b2f3a72d5": "主机拒绝取消自动合并。请刷新后重试。", + "9c28753c777c37b7": "{count, plural, other {自动合并 {count} 个 {term, select, mr {merge request} cr {change request} other {pull request}}?}}", + "a86b49982e18784d": "当 #{number} 及其下方未合并的各层都满足 {host} 的要求时,使用 {method} 将它们合并到 {base}。这可能会立即发生。", + "b1afda5c964deee4": [ + "自动合并堆叠(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "取消堆叠自动合并", + "012c67c7f1a99e33": "自动合并堆叠" } diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 3318ae3cdcb58..557dbcab85d84 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -310,6 +310,8 @@ export const PullRequestCapabilities = Schema.Struct({ edit: Schema.optional(PullRequestEditCapabilities), stacks: Schema.optional(Schema.Boolean), stackActions: Schema.optional(Schema.Boolean), + /** Stack actions also arm and cancel auto-merge for a layer and the open layers below it. */ + stackAutoMerge: Schema.optional(Schema.Boolean), labels: Schema.optional(Schema.Boolean), /** The host searches the repository's users, so composers can complete `@login`. */ mentions: Schema.optional(Schema.Boolean), diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index e38255b2eb377..76b3b8cf1908b 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -2761,6 +2761,102 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); + it.effect("arms and cancels auto-merge for a stack through the pinned layer", () => + Effect.gen(function* () { + route( + [ + "stacks?pull_request=7", + [ + { + number: 3, + url: "https://api.github.com/repos/acme/web/stacks/3", + base: { ref: "main" }, + pull_requests: [ + { number: 6, head: { ref: "one", sha: "aaa" }, state: "open", draft: false }, + { number: 7, head: { ref: "two", sha: "bbb" }, state: "open", draft: false }, + ], + }, + ], + ], + ["PullRequestNodeId", { data: { repository: { pullRequest: { id: "PR_7" } } } }], + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const target = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }; + yield* cli.runPullRequestAction({ + ...target, + action: "enable-auto-merge", + mergeMethod: "squash", + stackNumber: 3, + expectedStackHeads: [ + { number: 6, headSha: "aaa" }, + { number: 7, headSha: "bbb" }, + ], + }); + yield* cli.runPullRequestAction({ ...target, action: "disable-auto-merge", stackNumber: 3 }); + expect(variablesOf("enablePullRequestAutoMerge(")).toEqual([ + { + input: { + pullRequestId: "PR_7", + mergeMethod: "SQUASH", + expectedHeadOid: "bbb", + includeStack: true, + }, + }, + ]); + expect(variablesOf("DisableStackAutoMerge")).toEqual([{ pullRequestId: "PR_7" }]); + expect(restCallsTo("merge-async")).toEqual([]); + }), + ); + + it.effect("merges a stack that is already mergeable instead of arming auto-merge", () => + Effect.gen(function* () { + route( + [ + "stacks?pull_request=7", + [ + { + number: 3, + url: "https://api.github.com/repos/acme/web/stacks/3", + base: { ref: "main" }, + pull_requests: [ + { number: 7, head: { ref: "two", sha: "bbb" }, state: "open", draft: false }, + ], + }, + ], + ], + ["PullRequestNodeId", { data: { repository: { pullRequest: { id: "PR_7" } } } }], + [ + "enablePullRequestAutoMerge(", + { + data: { enablePullRequestAutoMerge: null }, + errors: [ + { + type: "UNPROCESSABLE", + message: + "Auto-merge is not needed because all requested pull requests are already mergeable", + }, + ], + }, + ], + ["merge-async", { status: "merged", details: {} }], + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + yield* cli.runPullRequestAction({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + action: "enable-auto-merge", + mergeMethod: "squash", + stackNumber: 3, + expectedStackHeads: [{ number: 7, headSha: "bbb" }], + }); + expect(restCallsTo("merge-async")).toMatchObject([ + { method: "PUT", body: { merge_method: "squash", sha: "bbb" } }, + ]); + }), + ); + it.effect.each(["merge", "enable-auto-merge"] as const)( "removes agent credits from the proposed message for %s", (action) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 4412c5da35f37..567415248ba9d 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -2753,15 +2753,58 @@ export const make = Effect.gen(function* () { .pipe(graphql(target)); }); } - if (input.stackNumber !== undefined) - return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe( - Effect.provideService(GitHubRest.GitHubRest, api), - Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess), - Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy), - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost), - Effect.provideService(FileSystem.FileSystem, fileSystem), + if (input.stackNumber !== undefined) { + const stackNumber = input.stackNumber; + const target = { ...input, operation: "runPullRequestAction" }; + // A stack auto-merge request sits on the layer it was armed on and covers those below. + if (input.action === "disable-auto-merge") + return pullRequestNodeId(target).pipe( + Effect.flatMap((pullRequestId) => + actionSummary( + client + .DisableStackAutoMerge({ pullRequestId }) + .pipe(Effect.map((result) => result.disablePullRequestAutoMerge?.pullRequest)), + ).pipe(graphql(target)), + ), + ); + const stackAction = (action: typeof input.action) => + runGitHubStackAction({ ...input, action, stackNumber }).pipe( + Effect.provideService(GitHubRest.GitHubRest, api), + Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess), + Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost), + Effect.provideService(FileSystem.FileSystem, fileSystem), + ); + if (input.action !== "enable-auto-merge") return stackAction(input.action); + const expectedHeadOid = input.expectedStackHeads?.find( + (layer) => layer.number === input.number, + )?.headSha; + return stackAction("enable-auto-merge").pipe( + Effect.andThen(pullRequestNodeId(target)), + Effect.flatMap((pullRequestId) => + actionSummary( + client + .EnablePullRequestAutoMerge({ + input: { + pullRequestId, + mergeMethod: GRAPHQL_MERGE_METHODS[input.mergeMethod ?? "merge"] ?? "MERGE", + ...(expectedHeadOid === undefined ? {} : { expectedHeadOid }), + includeStack: true, + }, + }) + .pipe(Effect.map((result) => result.enablePullRequestAutoMerge?.pullRequest)), + ).pipe(graphql(target)), + ), + // Like `gh pr merge --auto`: a stack that can merge now merges, re-pinned to its heads. + Effect.catchIf( + (error) => + error._tag === "GitHubApiResponseError" && + (error.githubErrors ?? []).some((message) => message.includes("already mergeable")), + () => stackAction("merge"), + ), ); + } if (input.action === "revert") { return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe( Effect.flatMap((pullRequestId) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index d1f3746d38d3e..e05724a6e4d67 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -55,6 +55,7 @@ const CAPABILITIES: PullRequestCapabilities = { edit: { changeRequest: true, comment: true, maintainerEdits: true }, stacks: true, stackActions: true, + stackAutoMerge: true, labels: true, // Statuses and check runs land on the head commit itself and are read whole, so an empty list // after a push is CI that never started rather than a read that saw nothing. diff --git a/packages/source-control-github/src/server/githubStackActions.ts b/packages/source-control-github/src/server/githubStackActions.ts index fb524ae0518de..9819fe1707b60 100644 --- a/packages/source-control-github/src/server/githubStackActions.ts +++ b/packages/source-control-github/src/server/githubStackActions.ts @@ -124,7 +124,11 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* number: input.number, stackNumber: input.stackNumber, }; - if (input.action !== "merge" && input.action !== "update-branch") + if ( + input.action !== "merge" && + input.action !== "update-branch" && + input.action !== "enable-auto-merge" + ) return yield* new GitHubStackUnsupportedError({ ...identity }); const endpoint = `repos/${input.repository}`; const read = yield* api.rest({ @@ -146,9 +150,9 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 }); } const affectedLayers = - input.action === "merge" ? stack.layers.slice(0, targetIndex + 1) : stack.layers; + input.action === "update-branch" ? stack.layers : stack.layers.slice(0, targetIndex + 1); const open = affectedLayers.filter((layer) => layer.state !== "merged"); - if (input.action === "merge" && target.state !== "open") + if (input.action !== "update-branch" && target.state !== "open") return yield* new GitHubStackUnsupportedError({ ...identity }); if ( !input.expectedStackHeads || @@ -230,6 +234,8 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* } if (open.some((layer) => layer.isDraft)) return yield* new GitHubStackUnsupportedError({ ...identity }); + // Auto-merge is armed by the caller's GraphQL mutation once the layers are pinned here. + if (input.action === "enable-auto-merge") return; const decode = (raw: string) => decodeMergeResponse(raw).pipe( Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })), diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql b/packages/source-control-github/src/server/pullRequestMutations.graphql index 550b26ca4fd4f..ba8bdbd6d3fd9 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql @@ -151,6 +151,15 @@ mutation DisablePullRequestAutoMerge($pullRequestId: ID!) { } } +# Its own document: Enterprise Server rejects `includeStack` wherever it is named. +mutation DisableStackAutoMerge($pullRequestId: ID!) { + disablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, includeStack: true }) { + pullRequest { + ...PullRequestActionSummary + } + } +} + mutation UpdatePullRequestBranch( $pullRequestId: ID! $expectedHeadOid: GitObjectID! diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts index b62bf95973126..d243d3e9f541f 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts @@ -554,6 +554,32 @@ export declare namespace DisablePullRequestAutoMerge { export type Result = typeof DisablePullRequestAutoMerge.result.Type } +/** `mutation DisableStackAutoMerge` */ +export const DisableStackAutoMerge = GraphQL.mutation("DisableStackAutoMerge", { + document: { + variables: [ + { name: "pullRequestId", body: "ID!" } + ], + selections: [ + { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", " includeStack:true}){pullRequest{...PullRequestActionSummary}}"] } + ], + fragments: [ + { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] } + ] + }, + variables: { + pullRequestId: Shared.ID + }, + result: Schema.Struct({ + /** Disable auto merge on the given pull request */ + disablePullRequestAutoMerge: Schema.NullOr(DisablePullRequestAutoMergePayload) + }) +}) +export declare namespace DisableStackAutoMerge { + export type Variables = typeof DisableStackAutoMerge.variables.Type + export type Result = typeof DisableStackAutoMerge.result.Type +} + /** Autogenerated return type of UpdatePullRequestBranch. */ export const UpdatePullRequestBranchPayload = Schema.Struct({ /** The updated pull request. */ @@ -807,4 +833,4 @@ export declare namespace DeletePullRequestBranch { } /** Every operation in pullRequestMutations.graphql. */ -export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) +export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, DisableStackAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) From ceb820e24ebeb7a91790e1fe793072a4c2a5c2bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:16:59 -0800 Subject: [PATCH 251/288] fix(scripts): server benchmark keeps the rounds it finished when a later run fails (#41716) --- scripts/server-metrics.test.ts | 32 ++++++++++++++ scripts/server-metrics.ts | 81 +++++++++++++++++++++++++++------- 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index e87174969c9ed..6597e9297514b 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,3 +1,5 @@ +import { it as effectIt } from "@effect/vitest"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; @@ -19,6 +21,7 @@ import { ServerMetrics, slope, } from "./server-metrics-report.ts"; +import { runAbRounds } from "./server-metrics.ts"; const decodeMetrics = Schema.decodeSync(ServerMetrics); @@ -103,6 +106,17 @@ describe("compareMetrics", () => { expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); + it("compares the unequal run counts an ab that stopped early leaves", () => { + const steady = cpuRuns(26.1, 27.4, 25.8); + const partial = compareMetrics(steady, cpuRuns(2.2, 2.5), 10, gatedRules); + expect(partial.improved).toContain("quiet.cpuPct"); + expect(partial.table).toContain("(3 runs), after `abc` (2 runs)"); + const single = compareMetrics(steady, cpuRuns(2.2), 10, gatedRules); + expect(single.improved).toContain("quiet.cpuPct"); + expect(single.table).toContain("| quiet.cpuPct | 26.1 | 2.2 | -92% | | better |"); + expect(compareMetrics(steady, cpuRuns(), 10, gatedRules).compared).toBe(0); + }); + it("reads a file written before loop delay and GC were recorded", () => { const older = decodeMetrics({ meta, @@ -601,3 +615,21 @@ describe("activityRenewalMissed", () => { expect(activityRenewalMissed(0, sentAt, repliedAt)).toBe(missed); }); }); + +describe("runAbRounds", () => { + effectIt.effect("keeps the runs that finished when a later run fails", () => + Effect.gen(function* () { + const files: Record<0 | 1, ReadonlyArray> = { 0: [], 1: [] }; + const failure = yield* Effect.flip( + runAbRounds({ + rounds: 3, + outDir: "out", + runSide: (side) => (side === 0 ? Effect.succeed("a1") : Effect.fail("b crashed")), + save: (side, runs) => Effect.sync(() => (files[side] = [...runs])), + }), + ); + expect(failure).toBe("b crashed"); + expect(files).toEqual({ 0: ["a1"], 1: [] }); + }), + ); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index c3482c72e70ff..9fa06fcfdea5c 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -2129,8 +2129,56 @@ const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* ( ) { const fs = yield* FileSystem.FileSystem; const json = yield* encodeMetrics(metrics); - if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`); - else yield* Console.log(json); + if (Option.isNone(out)) return yield* Console.log(json); + // A sibling then a rename, so a failed write keeps the previous file whole. + const temp = `${out.value}.tmp`; + yield* fs.writeFileString(temp, `${json}\n`); + yield* fs.rename(temp, out.value); +}); + +/** + * Runs A and B alternately, saving a side after each of its runs so a failure keeps the finished + * runs. On a failure it reports how many runs of each side reached disk. + */ +export const runAbRounds = Effect.fn("serverMetrics.abRounds")(function* < + A, + S, + E, + R, + ES, + RS, +>(options: { + readonly rounds: number; + readonly outDir: string; + readonly runSide: (side: 0 | 1) => Effect.Effect; + readonly save: (side: 0 | 1, runs: ReadonlyArray) => Effect.Effect; +}) { + const runs: [A[], A[]] = [[], []]; + const persisted = [0, 0]; + const saveSide = Effect.fn("serverMetrics.abSave")(function* (side: 0 | 1) { + const count = runs[side].length; + const saved = yield* options.save(side, runs[side]); + persisted[side] = count; + return saved; + }); + const saved: [S, S] = [yield* saveSide(0), yield* saveSide(1)]; + yield* Effect.gen(function* () { + for (let round = 0; round < options.rounds; round++) { + // A B, then B A, so a drift in machine load lands on both sides. + for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { + yield* Console.error(`round ${round + 1}/${options.rounds}: ${side === 0 ? "A" : "B"}`); + runs[side].push(yield* options.runSide(side)); + saved[side] = yield* saveSide(side); + } + } + }).pipe( + Effect.onError(() => + Console.error( + `ab stopped early; ${options.outDir} keeps ${persisted[0]} A and ${persisted[1]} B runs`, + ), + ), + ); + return saved; }); /** Prints the comparison and sets exit code 1 when a metric got worse. */ @@ -2375,20 +2423,21 @@ const abCommand = Command.make( yield* withSeed(unseeded[0], input), yield* withSeed(unseeded[1], input), ] as const; - const runs: [Measured[], Measured[]] = [[], []]; - for (let round = 0; round < input.rounds; round++) { - // A B, then B A, so a drift in machine load lands on both sides. - for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { - yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`); - runs[side].push((yield* runOnce(sides[side])).measured); - } - } - const loadAfter = yield* machineLoad; - const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] }; - const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] }; - yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); - yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); - yield* report(before, after, input.threshold); + // Written up front and after every run; compare takes unequal run counts. + const saved = yield* runAbRounds({ + rounds: input.rounds, + outDir, + runSide: (side) => runOnce(sides[side]).pipe(Effect.map((run) => run.measured)), + save: Effect.fn("serverMetrics.abSaveFile")(function* (side, runs) { + const file: ServerMetrics = { + meta: { ...metas[side], loadAfter: yield* machineLoad }, + runs: [...runs], + }; + yield* writeMetrics(Option.some(path.join(outDir, side === 0 ? "a.json" : "b.json")), file); + return file; + }), + }); + yield* report(saved[0], saved[1], input.threshold); }, Effect.scoped), ).pipe( Command.withDescription( From 337e8f00d68bd0fc8ca66c1d715fbb238fd38b4c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:17:08 -0800 Subject: [PATCH 252/288] fix(server): saving a workflow no longer blocks workflow calls until running agent steps finish (#41751) --- apps/server/src/workflows/WorkflowEngine.ts | 57 ++++- .../src/workflows/WorkflowRuntime.test.ts | 74 +++++- apps/server/src/workflows/stepServices.ts | 2 + apps/server/src/workflows/workflow.ts | 5 + apps/server/src/workflows/workflowAgent.ts | 221 +++++++++++++----- 5 files changed, 294 insertions(+), 65 deletions(-) diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts index 77ff4cf0ada2e..5e6509dd33647 100644 --- a/apps/server/src/workflows/WorkflowEngine.ts +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -44,6 +44,7 @@ import { import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { settleTurn, TurnEnd, TurnWatch } from "./workflowAgent.ts"; import { type Issue, isSettled, @@ -87,6 +88,8 @@ const DELIVERY_HEADERS = [ "idempotency-key", ]; const CANCEL_WAITS = Duration.seconds(30); +const decodeTurnWatch = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnWatch)); +const encodeTurnEnd = Schema.encodeEffect(Schema.toCodecJson(TurnEnd)); // Times of day are the server's own, as they are for scheduled tasks. const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); @@ -193,6 +196,49 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( yield* send(wait, value); }); + // Agent turns being watched now, by run and wait. The fibers live in the engine's scope, so a + // reload stops them at once and the next engine picks the turns up from their open waits. + const watchingTurns = new Set(); + const seeTurn = Effect.fn("WorkflowEngine.seeTurn")(function* (wait: WorkflowStore.WaitRow) { + const id = `${wait.run_id}/${wait.name}`; + // Taken before the first yield: the wait's own step and the sweep can both ask at once. + if (watchingTurns.has(id)) return; + watchingTurns.add(id); + const watch = yield* decodeTurnWatch(WorkflowStore.jsonValue(wait.watch_json ?? "null")).pipe( + Effect.option, + ); + if (Option.isNone(watch)) { + watchingTurns.delete(id); + return; + } + yield* settleTurn(watch.value).pipe( + Effect.flatMap(encodeTurnEnd), + Effect.catch((error) => encodeTurnEnd({ lost: text(error) })), + Effect.flatMap( + Effect.fnUntraced(function* (end) { + const woke = { expired: false, value: end as Schema.Json }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + }), + ), + Effect.provideService(WorkflowAgents, agents), + Effect.provideContext(stepReferences(store, wait.run_id, watch.value.agent.step)), + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.logWarning("A workflow could not see an agent's turn through", cause).pipe( + Effect.annotateLogs({ wait: id }), + ), + ), + Effect.ensuring(Effect.sync(() => watchingTurns.delete(id))), + Effect.forkIn(scope), + ); + }); + const watchTurn = Effect.fn("WorkflowEngine.watchTurn")(function* (runId: string, name: string) { + const wait = yield* store.waitAt({ runId, wait: name }); + if (wait !== undefined) yield* seeTurn(wait); + }); + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( function* (name, input, options) { // A parent written against one version of a child must not get another one's payload. @@ -450,13 +496,17 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( const fireWatches = Effect.gen(function* () { const now = DateTime.toEpochMillis(yield* DateTime.now); for (const wait of yield* store.watches) { + const watched = WorkflowStore.jsonValue(wait.watch_json ?? "null"); + // An agent's turn is watched by a fiber of its own, started again here after a reload. + if (typeof watched === "object" && watched !== null && "agent" in watched) { + yield* seeTurn(wait); + continue; + } const id = `watch:${wait.run_id}/${wait.name}`; const last = lookedAt.get(id); if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; lookedAt.set(id, now); - const watch = WorkflowStore.jsonValue( - wait.watch_json ?? "null", - ) as unknown as PullRequestWatch; + const watch = watched as unknown as PullRequestWatch; yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( // Each look keeps where the pull request stands on the wait's own step. Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), @@ -939,6 +989,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( signalAll, start, ended, + watchTurn, cancel: (runId, reason) => cancel(runId, reason), list: Effect.fn("WorkflowEngine.list")(function* (filter) { return (yield* store.runsWhere(filter)).map((row) => ({ diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts index 344e6d871efd9..62403042de1bc 100644 --- a/apps/server/src/workflows/WorkflowRuntime.test.ts +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -3,7 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -15,7 +18,7 @@ import * as TestClock from "effect/testing/TestClock"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; -import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { type AgentResult, WorkflowAgents } from "./WorkflowAgents.ts"; import * as WorkflowEngine from "./WorkflowEngine.ts"; import * as WorkflowRuntime from "./WorkflowRuntime.ts"; import { engineTag, type WorkflowDefinition } from "./workflow.ts"; @@ -39,6 +42,7 @@ workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.Stri const setup = Effect.fn("setup")(function* ( wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, engine?: (definitions: ReadonlyArray) => Layer.Layer, + agents?: WorkflowAgents["Service"], ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -54,7 +58,11 @@ const setup = Effect.fn("setup")(function* ( (definitions: ReadonlyArray) => engine?.(definitions) ?? WorkflowEngine.layer(definitions).pipe( - Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide( + agents === undefined + ? Layer.mock(WorkflowAgents)({}) + : Layer.succeed(WorkflowAgents, agents), + ), Layer.provide(database), Layer.provide(NodeCrypto.layer), ), @@ -424,6 +432,68 @@ it.effect("a change held back by a run goes in once that run ends, with no furth }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); +it.effect( + "a reload does not wait for an agent that is still at work, and its step ends with the turn", + () => + Effect.gen(function* () { + const ended = yield* Deferred.make(); + const started = yield* Deferred.make(); + const { fileSystem, at, runtime } = yield* setup(undefined, undefined, { + start: (input) => + Effect.as(Deferred.succeed(started, undefined), { + threadId: "thread", + turnId: input.key, + }), + result: () => Deferred.await(ended), + interrupt: () => Effect.succeed("stopped" as const), + }); + yield* fileSystem.writeFileString( + at("helper.ts"), + `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value), +); +`, + ); + const ticking = (effect: Effect.Effect) => + Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second"))); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const helped = yield* ticking( + Effect.gen(function* () { + const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" }); + yield* Deferred.await(started); + yield* workflows.waitFor(run.runId, (row) => row.status === "waiting"); + return run; + }), + ); + + // The test clock stands still during the save, so an engine that waited for the agent's + // step to finish would never stop: the step is not given up on, and the turn does not end. + // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn. + const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello"))); + const saved = yield* Fiber.await(saving).pipe( + Effect.timeoutOption("10 seconds"), + TestClock.withLive, + ); + if (Option.isNone(saved)) { + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" }); + yield* ticking(Fiber.await(saving)); + assert.fail("The reload waited for the agent's turn to end."); + } + assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed); + assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting"); + + // The turn ends after the reload, and the new engine carries its result into the run. + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" }); + const done = yield* ticking( + workflows.waitFor(helped.runId, (run) => run.status === "completed"), + ); + assert.equal(done.result, "all done"); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + it.effect( "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", () => diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts index 53c6773494c3b..bdfd63b23d856 100644 --- a/apps/server/src/workflows/stepServices.ts +++ b/apps/server/src/workflows/stepServices.ts @@ -117,6 +117,8 @@ export class EngineLink extends Context.Service< readonly list: ListRuns; /** Tell the run that invoked `runId`, if one did, how it ended. */ readonly ended: (runId: string) => Effect.Effect; + /** Watch the agent turn behind an open wait of `runId` until it ends. */ + readonly watchTurn: (runId: string, wait: string) => Effect.Effect; } | undefined; /** The steps of each run that are running in this process right now. */ diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts index bad9b9f513a97..34bb7ffb20a18 100644 --- a/apps/server/src/workflows/workflow.ts +++ b/apps/server/src/workflows/workflow.ts @@ -67,6 +67,8 @@ export class RunContext extends Context.Service< readonly forStep: (name: string) => Context.Context; /** The steps running now, which a cancelled run's cleanup waits for. */ readonly inFlight: InFlight; + /** Have the engine see the agent turn behind the open wait `wait` through, and wake it. */ + readonly watchTurn: (wait: string) => Effect.Effect; } >()("t3/workflows/workflow/RunContext") {} @@ -867,6 +869,9 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo names: new Set(), forStep: (name) => forStep(store, keyValues, link, forge, runId, name), inFlight: link.inFlight, + watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) { + if (link.current !== undefined) yield* link.current.watchTurn(runId, wait); + }), }), ), ); diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts index 03956086b03c8..e53b68d571391 100644 --- a/apps/server/src/workflows/workflowAgent.ts +++ b/apps/server/src/workflows/workflowAgent.ts @@ -6,6 +6,7 @@ import { identity } from "effect/Function"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import { Activity, DurableDeferred } from "effect/workflow"; import { checkOptions } from "./options.ts"; import { stepReferences } from "./runReferences.ts"; @@ -17,6 +18,7 @@ import { type StepFailed, text, waitAs, + wakeOf, } from "./workflow.ts"; import type { IssueAddress } from "./WorkflowForge.ts"; import { @@ -26,6 +28,7 @@ import { AgentTurn, WorkflowAgents, } from "./WorkflowAgents.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; /** A thread an agent step ran in, to hand to a later step that should continue it. */ export interface AgentThread { @@ -92,6 +95,97 @@ const NEW_THREAD_OPTIONS = [ "interactionMode", ] as const; +/** What the engine needs to see one turn of an agent step through to its end. */ +export const TurnWatch = Schema.Struct({ + agent: Schema.Struct({ + step: Schema.String, + turn: AgentTurn, + startedAt: Schema.optional(Schema.Number), + timeoutMs: Schema.optional(Schema.Number), + quietMs: Schema.optional(Schema.Number), + owesOutput: Schema.Boolean, + onFailure: Schema.Literals(["pause", "return"]), + }), +}); +export type TurnWatch = typeof TurnWatch.Type; + +/** How a watched turn ended: its result, or why it could not be read, which pauses the run. */ +export const TurnEnd = Schema.Union([ + Schema.Struct({ result: AgentResult }), + Schema.Struct({ lost: Schema.String }), +]); +export type TurnEnd = typeof TurnEnd.Type; + +/** The turn's result, or its thread stopped when the step's time is up. */ +export const settleTurn = Effect.fn("workflow.agent.settle")(function* ({ + agent: watch, +}: TurnWatch): Effect.fn.Return { + const agents = yield* WorkflowAgents; + const { turn, startedAt } = watch; + const threadOf = { threadId: turn.threadId, environment: turn.environment }; + const resultOf = (quiet: number | undefined) => + agents + .result(turn, { quiet: quiet === undefined ? undefined : Duration.millis(quiet) }) + .pipe( + watch.onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + const settled = Effect.gen(function* () { + if (watch.timeoutMs === undefined || startedAt === undefined) { + return yield* resultOf(watch.quietMs); + } + const limit = Duration.millis(watch.timeoutMs); + const left = startedAt + watch.timeoutMs - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(watch.quietMs).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run, so resuming tries the stop again. A step that + // returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf, turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* watch.onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(undefined); + if (ended.ending !== "completed" || !watch.owesOutput || ended.output !== undefined) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + return yield* settled.pipe( + Effect.map((result): TurnEnd => ({ result })), + Effect.catch((error) => Effect.succeed({ lost: text(error) })), + ); +}); + +// An agent turn's wait takes no signal from outside: only the engine's watch ends it. +const NOTHING_FITS = WorkflowStore.jsonText({ not: {} }); +// A result journaled when the wait for a turn still ran inside its activity, which kept the +// engine from stopping, and every workflow call with it, until the turn ended. +const Opened = Schema.Union([AgentResult, Schema.Struct({ ending: Schema.Literal("watching") })]); +const decodeTurnEnd = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnEnd)); +const encodeWatch = Schema.encodeEffect(Schema.toCodecJson(TurnWatch)); + const attempt = Effect.fn("workflow.agent")(function* ( name: string, options: AgentOptions, @@ -121,6 +215,10 @@ const attempt = Effect.fn("workflow.agent")(function* ( const outputCodec = options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const timeoutMs = + options.timeout === undefined + ? undefined + : Duration.toMillis(Duration.fromInputUnsafe(options.timeout)); const threadOf = (turn: AgentTurn): AgentThread => ({ threadId: turn.threadId, ...(turn.environment === undefined ? {} : { environment: turn.environment }), @@ -174,61 +272,73 @@ const attempt = Effect.fn("workflow.agent")(function* ( Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), ), ); - const resultOf = (turn: AgentTurn, wait = { quiet }) => - agents - .result(turn, wait) - .pipe( - Effect.provideContext(touches), - onFailure === "pause" - ? identity - : Effect.catch((error) => - Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), - ), - ); - /** The turn's result, or its thread stopped when the step's time is up. */ - const within = Effect.fn("workflow.agent.within")(function* ( + /** + * The turn's result. The engine watches the turn outside the run and wakes the run once it + * ends, so an engine that stops while an agent works is not held up by it. + */ + const ended = Effect.fn("workflow.agent.ended")(function* ( turn: AgentTurn, startedAt: number | undefined, + round: number, + correction: number, ) { - if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); - const limit = Duration.fromInputUnsafe(options.timeout); - const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); - const result = yield* resultOf(turn).pipe( - Effect.timeoutOption(Duration.millis(Math.max(0, left))), + const watch = WorkflowStore.jsonText( + yield* encodeWatch({ + agent: { + step: name, + turn, + startedAt, + timeoutMs, + quietMs: quiet === undefined ? undefined : Duration.toMillis(quiet), + owesOutput: outputSchema !== undefined, + onFailure, + }, + }).pipe(Effect.orDie), ); - if (Option.isSome(result)) return result.value; - // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step - // that returns its failure says the turn may still be running. - const stopping = agents - .interrupt({ ...threadOf(turn), turnId: turn.turnId }) - .pipe(Effect.retry({ times: 2 })); - const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" - ? stopping - : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); - const late = `it was not done after ${Duration.format(limit)}`; - if (stop === "ended") { - // The turn ended before it could be stopped, maybe long ago, as a run that resumes late - // finds it. What it left is the answer when it is one. - const ended = yield* resultOf(turn, { quiet: undefined }); - if ( - ended.ending !== "completed" || - outputSchema === undefined || - ended.output !== undefined - ) { - return ended; - } - // Stopping the later turn it may answer from could stop someone else's. - return { - ending: "stopped" as const, - detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, - reply: "", - }; + const first = `agent/${name}/${round}/result/${correction}`; + for (let lost = 0; ; lost++) { + const at = lost === 0 ? first : `${first}/again/${lost}`; + const wake = wakeOf(at); + const token = yield* DurableDeferred.token(wake); + const opened = yield* journaled( + run, + name, + at, + Opened, + Effect.gen(function* () { + yield* run.store.runStatus(run.runId, "waiting", `agent ${name}`); + yield* run.store.waitOpened({ + runId: run.runId, + name: at, + workflow: run.workflow, + key: undefined, + token, + schemaJson: NOTHING_FITS, + requestJson: null, + watchJson: watch, + deadline: null, + }); + yield* run.watchTurn(at); + return { ending: "watching" as const }; + }), + ); + if (opened.ending !== "watching") return opened; + const woke = yield* DurableDeferred.await(wake); + const end = yield* Effect.orDie(decodeTurnEnd(woke.value)); + yield* Activity.make({ name: `${at}/close`, execute: run.store.waitClosed(run.runId, at) }); + if ("result" in end) return end.result; + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches + // it again, and the turn is watched once more. + yield* journaled( + run, + name, + `${at}/lost`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${at}/lost`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(end.lost), + ), + ); } - return { - ending: "stopped" as const, - detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, - reply: "", - }; }); const done = (round: number, produced: Schema.Json, said?: string) => journaled( @@ -263,16 +373,7 @@ const attempt = Effect.fn("workflow.agent")(function* ( let stopped = false; let died = false; for (let correction = 0; turn.failed === undefined; correction++) { - const result = yield* journaled( - run, - name, - `agent/${name}/${round}/result/${correction}`, - AgentResult, - Effect.andThen( - run.store.runStatus(run.runId, "waiting", `agent ${name}`), - within(turn, startedAt), - ), - ); + const result = yield* ended(turn, startedAt, round, correction); if (result.ending !== "completed") { stopped = result.ending === "stopped"; died = result.ending === "failed"; From 5bf6b122b5edc8b89184151ba6436a81cfb346e6 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:29:19 +0100 Subject: [PATCH 253/288] fix(web): a long pull request search no longer ends in a broken character (#41838) Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestListEmptyState.tsx | 4 +++- ...quest-search-keeps-whole-characters.e2e.ts | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx index 7edf26efc3acc..c5e26dfd6e67e 100644 --- a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx @@ -1,4 +1,5 @@ import { RefreshIcon } from "~/components/ui/refresh-icon"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { T, useGT, Var } from "gt-react"; import { PlusIcon, SearchIcon } from "lucide-react"; @@ -70,7 +71,8 @@ export function PullRequestListEmptyState({ onRefresh: () => void; }) { const gt = useGT(); - const shownQuery = query.length > 48 ? `${query.slice(0, 48)}…` : query; + const shownQuery = + query.length > 48 ? `${query.slice(0, splitsSurrogatePair(query, 48) ? 47 : 48)}…` : query; if (!hasProjects) { return ( diff --git a/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts b/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts new file mode 100644 index 0000000000000..f28695fa19bfd --- /dev/null +++ b/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts @@ -0,0 +1,21 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const KEPT = "a".repeat(47); +// The emoji's two UTF-16 units straddle unit 48, where the shown search is cut. +const QUERY = `${KEPT}😀 and the rest of the search`; + +test( + "A long pull request search that matches nothing ends without a broken character", + WEB, + async ({ t3, app, screen }) => { + await t3.project("demo"); + await t3.open(`/pull-requests?${new URLSearchParams({ q: QUERY })}`); + + const title = screen.getByText(/^Nothing matches/); + await title.waitFor({ timeout: 60_000 }); + await app.screenshot("no-matches"); + await expect(title).toHaveText(`Nothing matches “${KEPT}…”`); + }, +); From a5d86e6382bee1fbe82e0dac8c2a92f2a8adaa77 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:31:08 -0800 Subject: [PATCH 254/288] fix(web): Push on the default branch no longer commits files changed while confirming (#41844) --- .../components/GitActionsControl.logic.test.ts | 16 ++++++++++++++++ .../src/components/GitActionsControl.logic.ts | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 13b6ed8982513..87b076271807e 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -128,6 +128,22 @@ describe("when: on default ref without open PR", () => { }); }); + it("resolveQuickAction pushes without committing when the tree is clean and ahead", () => { + const withUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1 }), + false, + true, + ); + assert.deepInclude(withUpstream, { kind: "run_action", action: "push", label: "Push" }); + + const withoutUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1, hasUpstream: false }), + false, + true, + ); + assert.deepInclude(withoutUpstream, { kind: "run_action", action: "push", label: "Push" }); + }); + it("offers a feature branch only to actions that commit the changes", () => { const reason = (action: DefaultBranchConfirmableAction, hasWorkingTreeChanges: boolean) => resolveFeatureBranchUnavailableReason({ action, branchName: "main", hasWorkingTreeChanges }); diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 81ab7a51ad3db..eb13b53f95d7d 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -401,7 +401,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { @@ -439,7 +439,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { From 061717307335d95b67a8fa677ee5c437a230839d Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 20:35:20 -0600 Subject: [PATCH 255/288] fix(cli): t3 policy check expands ~ in the policy file path (#41848) Co-authored-by: Julius Marminge --- apps/server/src/cli/policy.test.ts | 21 +++++++++++++++++++++ apps/server/src/cli/policy.ts | 5 +++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index d06998ff42882..04e29808078c1 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -9,6 +9,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { Command } from "effect/cli"; +import * as TestConsole from "effect/testing/TestConsole"; import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; @@ -85,4 +86,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { ); }), ); + + it.effect("check reads a ~/ policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-check-" }); + const file = path.join(home, "policy.json"); + yield* fs.writeFileString( + file, + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })(["policy", "check", "~/policy.json"]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include((yield* TestConsole.logLines).join("\n"), `Managed by Tilde Corp (${file}`); + }).pipe(Effect.provide(Layer.fresh(TestConsole.layer))), + ); }); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index c48e2bc535a6f..e8badd9123615 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -96,14 +96,15 @@ const checkCommand = Command.make("check", { Command.withDescription("Validate a policy file before deploying it."), Command.withHandler( Effect.fn("cli.policy.check")(function* ({ file }) { + const policyFile = yield* expandHomePath(file); // Startup treats a missing file as no policy; a draft that is not there checks nothing. - if (!(yield* (yield* FileSystem.FileSystem).exists(file))) { + if (!(yield* (yield* FileSystem.FileSystem).exists(policyFile))) { return yield* new CliError.UserError({ cause: file, userMessage: `No policy file at ${file}.`, }); } - const policy = yield* ManagedPolicy.load(file); + const policy = yield* ManagedPolicy.load(policyFile); yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy))); }), ), From 57ffba5dfb0a39de4de7abbb6d69ce15ac3074d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:35:49 -0800 Subject: [PATCH 256/288] fix(ssh): a second desktop no longer stops a remote server it did not launch (#41842) --- packages/ssh/src/tunnel.test.ts | 56 +++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 54 ++++++++++++++++++++++--------- 2 files changed, 96 insertions(+), 14 deletions(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index f123820ccd191..2f7874ff08f58 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -1612,6 +1612,62 @@ server.listen(Number(flag("--port") ?? 0), "127.0.0.1", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.live( + "another desktop with the same connection details neither owns nor stops the server", + () => + Effect.gen(function* () { + const { fs, home, fakeServer, sshAsLocalShell, stateDir } = + yield* prepare("an unrelated process"); + const launch = (launcherId: string) => + SshTunnel.launchOrReuseRemoteServer( + target, + undefined, + { nodeScriptPath: fakeServer }, + launcherId, + ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, sshAsLocalShell)); + const runtimePid = fs + .readFileString(`${home}/.t3/userdata/server-runtime.json`) + .pipe(Effect.map((runtime) => Number(JSON.parse(runtime).pid))); + + assert.equal((yield* launch("a".repeat(32))).remoteServerKind, "managed"); + const serverPid = yield* runtimePid; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + process.kill(serverPid, "SIGKILL"); + } catch {} + }), + ); + + const otherDesktop = yield* launch("b".repeat(32)); + assert.equal( + yield* fs.readFileString(`${stateDir}/launcher`), + `${"a".repeat(32)}\n`, + "the second desktop recorded itself as the server's launcher", + ); + assert.equal(otherDesktop.remoteServerKind, "external"); + + const layer = Layer.mergeAll( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, sshAsLocalShell), + Layer.succeed(HttpClient.HttpClient, testHttpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ + resolveCliRunner: Effect.succeed(ARCHIVE), + resolveLauncherId: Effect.succeed("b".repeat(32)), + }), + ); + yield* Effect.flatMap(SshTunnel.SshEnvironmentManager, (manager) => + manager.disconnectEnvironment(target), + ).pipe(Effect.provide(layer)); + assert.isTrue( + yield* isRunning(serverPid), + "the second desktop's disconnect stopped the server the first desktop launched", + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.live.each(staleIds)("disconnecting does not signal %s named by the managed pid file", (kind) => Effect.gen(function* () { const { fs, holder, sshAsLocalShell, staleId, stateDir } = yield* prepare(kind); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 401af98a92335..8a50f7c45c892 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -702,7 +702,14 @@ if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then RUNNER_CHANGED=1 fi mv "$RUNNER_NEXT" "$RUNNER_FILE" -if [ -n "$LAUNCHER_ID" ]; then +# Desktops with the same connection details share this record. A server +# another desktop launched is only borrowed: it is neither replaced nor +# claimed here, and that desktop's ID stays on record. +RECORDED_LAUNCHER="$(cat "$STATE_DIR/launcher" 2>/dev/null || true)" +FOREIGN_LAUNCHER=0 +if [ -n "$LAUNCHER_ID" ] && [ -n "$RECORDED_LAUNCHER" ] && [ "$RECORDED_LAUNCHER" != "$LAUNCHER_ID" ]; then + FOREIGN_LAUNCHER=1 +elif [ -n "$LAUNCHER_ID" ]; then printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" fi pick_port() { @@ -897,6 +904,8 @@ if adopt_default_server && [ -n "$ADOPTED_PID" ] && [ -n "$LAUNCHER_ID" ]; then printf 'managed\\n' >"$MANAGED_FILE" printf 'external\\n' >"$SIBLING_DIR/managed" rm -f "$SIBLING_DIR/pid" + printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" + FOREIGN_LAUNCHER=0 RUNNER_CHANGED=1 if cmp -s "$RUNNER_FILE" "$SIBLING_DIR/run-t3.sh"; then RUNNER_CHANGED=0 @@ -917,7 +926,7 @@ if [ "$REMOTE_MANAGED" = "external" ]; then elif [ -n "$REMOTE_PORT" ] && managed_server_running "$REMOTE_PID"; then # Reconnect owns the local tunnel, not the lifetime of an already running # server. A changed runner is the update path and replaces an older server. - if [ "$RUNNER_CHANGED" -eq 1 ] && ! keeps_running_server; then + if [ "$RUNNER_CHANGED" -eq 1 ] && [ "$FOREIGN_LAUNCHER" -eq 0 ] && ! keeps_running_server; then kill "$REMOTE_PID" 2>/dev/null || true wait_for_pid_exit "$REMOTE_PID" REMOTE_PID="" @@ -935,6 +944,8 @@ elif [ -n "$REMOTE_PORT" ] && managed_server_running "$REMOTE_PID"; then elif ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then printf 'Remote T3 server is still running but did not become ready. Retry the connection; the server was left running.\\n' >&2 exit 1 + elif [ "$FOREIGN_LAUNCHER" -eq 1 ]; then + REMOTE_MANAGED="external" fi else REMOTE_PID="" @@ -1022,8 +1033,10 @@ if [ -z "$REMOTE_PORT" ]; then printf '%s\\n' "$REMOTE_PID" >"$PID_FILE" printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE" printf 'managed\\n' >"$MANAGED_FILE" - # A stop keeps the launcher file; it must not name this server's owner. - if [ -z "$LAUNCHER_ID" ]; then + # A stop keeps the launcher file; it must name this server's owner. + if [ -n "$LAUNCHER_ID" ]; then + printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" + else rm -f "$STATE_DIR/launcher" fi if ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then @@ -1082,6 +1095,13 @@ STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@" PID_FILE="$STATE_DIR/pid" PORT_FILE="$STATE_DIR/port" MANAGED_FILE="$STATE_DIR/managed" +LAUNCHER_ID="@@T3_LAUNCHER_ID@@" +RECORDED_LAUNCHER="$(cat "$STATE_DIR/launcher" 2>/dev/null || true)" +# Another desktop with the same connection details launched this server. +if [ -n "$LAUNCHER_ID" ] && [ -n "$RECORDED_LAUNCHER" ] && [ "$RECORDED_LAUNCHER" != "$LAUNCHER_ID" ]; then + printf '{"stopped":false}\\n' + exit 0 +fi REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)" REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)" @@T3_MANAGED_SERVER_RUNNING_SCRIPT@@ @@ -1200,9 +1220,14 @@ function buildRemotePairingScript(stateKey: string, input?: RemoteT3RunnerOption }); } -function buildRemoteStopScript(stateKey: string): string { +// Launcher IDs are interpolated into remote shell commands, so only hex passes. +const validLauncherId = (launcherId: string | null | undefined) => + typeof launcherId === "string" && /^[0-9a-f]{32}$/u.test(launcherId) ? launcherId : null; + +function buildRemoteStopScript(stateKey: string, launcherId: string | null): string { return applyScriptPlaceholders(REMOTE_STOP_SCRIPT, { T3_STATE_KEY: stateKey, + T3_LAUNCHER_ID: launcherId ?? "", T3_MANAGED_SERVER_RUNNING_SCRIPT: REMOTE_MANAGED_SERVER_RUNNING_SCRIPT, }); } @@ -1235,11 +1260,8 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const stateKey = yield* remoteStateKey(target); - // The launcher ID is interpolated into the remote shell command, so only hex passes. - const launchArgs = - typeof launcherId === "string" && /^[0-9a-f]{32}$/u.test(launcherId) - ? `${stateKey} ${launcherId}` - : stateKey; + const validId = validLauncherId(launcherId); + const launchArgs = validId === null ? stateKey : `${stateKey} ${validId}`; yield* Effect.logInfo("ssh.remoteServer.launch.start", { ...sshTargetLogFields(target), ...sshRunnerLogFields(runner), @@ -1348,6 +1370,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( target: DesktopSshEnvironmentTarget, input?: SshAuth.SshAuthOptions, + launcherId?: string | null, ): Effect.fn.Return< void, SshCommandError | SshInvalidTargetError, @@ -1360,7 +1383,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( }); yield* runSshCommand(target, { remoteCommandArgs: ["sh", "-s"], - stdin: buildRemoteStopScript(stateKey), + stdin: buildRemoteStopScript(stateKey, validLauncherId(launcherId)), ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1790,6 +1813,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma const tunnels = new Map(); const targetLocks = yield* KeyedLock.make(); const authSecrets = new Map(); + const resolveLauncherId = options.resolveLauncherId ?? Effect.succeed(null); // Keep one lock per target so reconnect cannot reuse a server while stop is pending. const withTargetLock = Effect.fn("ssh/tunnel.withTargetLock")(function* ( @@ -1951,8 +1975,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ...sshRunnerLogFields(input.runner), key: input.key, }); - const launcherId = - options.resolveLauncherId === undefined ? null : yield* options.resolveLauncherId; + const launcherId = yield* resolveLauncherId; const remoteLaunch = yield* runWithSshAuth({ key: input.key, target: input.resolvedTarget, @@ -2038,6 +2061,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma remotePort: tunnelEntry.remotePort, }); const authSecret = authSecrets.get(tunnelEntry.key) ?? null; + const launcherId = yield* resolveLauncherId; yield* stopRemoteServer( tunnelEntry.target, authSecret === null @@ -2050,6 +2074,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma batchMode: "no", interactiveAuth: true, }, + launcherId, ).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService), Effect.provideService(Digest.Digest, digestService), @@ -2255,10 +2280,11 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma yield* closeTunnelEntry(entry); }).pipe(Effect.uninterruptible); } + const launcherId = yield* resolveLauncherId; yield* runWithSshAuth({ key, target: resolvedTarget, - operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions), + operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions, launcherId), }); yield* Effect.logInfo("ssh.environment.disconnect.succeeded", { ...sshTargetLogFields(resolvedTarget), From e632155b3a1dcf18121cf730f393245f071fa8c9 Mon Sep 17 00:00:00 2001 From: Arman Charan Date: Tue, 24 Nov 2026 12:40:50 +1000 Subject: [PATCH 257/288] fix(claude): measure context from the last main-model pass (#41816) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 70 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 21 +++--- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ebf6500441ba7..297527393aaa1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -10601,6 +10601,76 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); + it.effect("measures Claude context from the last main-model pass in an advisor response", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-advisor-context"), + text: "Continue.", + attachments: [], + }), + ); + const usage = { + input_tokens: 4, + cache_read_input_tokens: 1087272, + cache_creation_input_tokens: 1222, + output_tokens: 711, + iterations: [ + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543529, + cache_creation_input_tokens: 214, + output_tokens: 268, + }, + { type: "advisor_message", input_tokens: 545497, output_tokens: 3144 }, + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543743, + cache_creation_input_tokens: 1008, + output_tokens: 443, + }, + ], + }; + for (const frame of [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_advisor", usage: zeroUsage }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage, + }), + usageSnapshotFrame("msg_snapshot_only", "00000000-0000-4000-8000-000000000690", { + ...zeroUsage, + iterations: [ + ...usage.iterations, + { type: "advisor_message", input_tokens: 547000, output_tokens: 25 }, + ], + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000691", result: "Done." }), + ]) + yield* Queue.offer(harness.sdkMessages, frame); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [545196, 545196]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("reports context from final stream usage when the request starts at zero", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7d16f5afba3c2..f5993b8a1824a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -315,6 +315,7 @@ function claudeMessageInputTokens(usage: { export function claudeProviderTurnTokenUsage( usage: { + readonly iterations?: SDKAssistantMessage["message"]["usage"]["iterations"] | undefined; readonly input_tokens?: number | null | undefined; readonly cache_creation_input_tokens?: number | null | undefined; readonly cache_read_input_tokens?: number | null | undefined; @@ -326,9 +327,11 @@ export function claudeProviderTurnTokenUsage( autoCompactWindow = "", requestedAt?: DateTime.Utc, ) { - const inputTokens = claudeMessageInputTokens(usage); - const outputTokens = optionalClaudeUsageTokenCount(usage.output_tokens) ?? 0; - const cachedInputTokens = optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0; + // After an advisor call, the response totals can count the same context twice. + const sample = usage.iterations?.findLast((iteration) => iteration.type === "message") ?? usage; + const inputTokens = claudeMessageInputTokens(sample); + const outputTokens = optionalClaudeUsageTokenCount(sample.output_tokens) ?? 0; + const cachedInputTokens = optionalClaudeUsageTokenCount(sample.cache_read_input_tokens) ?? 0; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); // The cache lifetime starts with the request, not when its response ends. const promptCacheExpiresAt = @@ -354,15 +357,11 @@ type ClaudeMessageUsage = Parameters[0]; // message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them. function mergeClaudeStreamUsage( current: ClaudeMessageUsage, - delta: { - readonly input_tokens?: number | null | undefined; - readonly cache_creation_input_tokens?: number | null | undefined; - readonly cache_read_input_tokens?: number | null | undefined; - readonly output_tokens?: number | null | undefined; - }, + delta: ClaudeMessageUsage, ): ClaudeMessageUsage { return { ...current, + iterations: delta.iterations ?? current.iterations, input_tokens: optionalClaudeUsageTokenCount(delta.input_tokens) ?? optionalClaudeUsageTokenCount(current.input_tokens) ?? @@ -6715,8 +6714,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.autoCompactWindow, context.streamUsage?.requestedAt, ); - if (typeof usage !== "number") { - if (claudeMessageInputTokens(usage) <= 0) return; + if ("inputTokens" in tokenUsage) { + if (tokenUsage.inputTokens <= 0) return; context.compactionTokens = undefined; } yield* emitProviderEvent({ From ededa85fe3e140f1b43a067d0586be3ea8649dae Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 23 Nov 2026 21:47:42 -0500 Subject: [PATCH 258/288] fix(server): closing an Android emulator with shutdown no longer leaves its session stuck open (#41840) Co-authored-by: Julius Marminge --- apps/server/src/device/DeviceHubOperations.ts | 40 ++++++++- apps/server/src/device/DeviceService.test.ts | 86 ++++++++++++++++++- 2 files changed, 120 insertions(+), 6 deletions(-) diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts index 3a1bcee7a8e2a..9dbc7d6ca64b4 100644 --- a/apps/server/src/device/DeviceHubOperations.ts +++ b/apps/server/src/device/DeviceHubOperations.ts @@ -14,6 +14,9 @@ import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost const BOOT_TIMEOUT = Duration.minutes(3); const SCREENSHOT_TIMEOUT = Duration.seconds(20); +// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill. +const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45); +const ADB_DEVICES_TIMEOUT = Duration.seconds(10); // Let the hub's 30 s simctl timeout report its cause first. const LIST_TIMEOUT_SECONDS = 40; // expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes. @@ -296,11 +299,26 @@ export const makeDeviceHubOperations = (options: { ? attachIosStream(device.id, "open").pipe(Effect.asVoid) : Effect.void; + // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an + // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer + // lists its serial in any state. + const emulatorExited = (serial: string) => + /^emulator-\d+$/.test(serial) + ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe( + Effect.map( + ({ code, stdout }) => + code === 0 && + !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial), + ), + Effect.orElseSucceed(() => false), + ) + : Effect.succeed(false); + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( function* (device) { - const postShutdown = (path: string, body: Record) => + const postShutdown = (path: string, body: Record, timeout?: Duration.Input) => postJson(path, body, "shutdown").pipe( - Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)), Effect.flatMap((result) => result.ok ? Effect.void @@ -329,7 +347,23 @@ export const makeDeviceHubOperations = (options: { ), ), ) - : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); + : postShutdown( + "/api/devices/shutdown", + { platform: device.platform, id: device.id }, + ANDROID_SHUTDOWN_TIMEOUT, + ).pipe( + Effect.catch((cause) => + emulatorExited(device.id).pipe( + Effect.flatMap((exited) => + exited + ? Effect.logInfo("Android emulator has exited", { + deviceId: device.id, + }) + : Effect.fail(cause), + ), + ), + ), + ); }, ); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..972a9a2b150b2 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -18,6 +18,7 @@ import { SshCommandError } from "@t3tools/ssh/errors"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -192,7 +193,14 @@ const fixture = Effect.fn("fixture")(function* ( const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; - const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; + const connection = { + online: true, + kind: "local" as "local" | "ssh", + failShutdown: false, + shutdownDelay: undefined as Duration.Input | undefined, + adbDevices: undefined as { code: number; stdout: string; stderr: string } | undefined, + }; + const shutdownRequested = yield* Deferred.make(); const http = HttpClient.make((request) => Effect.gen(function* () { requests.push(request.url); @@ -230,6 +238,8 @@ const fixture = Effect.fn("fixture")(function* ( return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody))); } if (request.url.endsWith("/shutdown")) { + yield* Deferred.succeed(shutdownRequested, undefined); + if (connection.shutdownDelay !== undefined) yield* Effect.sleep(connection.shutdownDelay); if (connection.failShutdown) return HttpClientResponse.fromWeb(request, Response.json({ ok: false })); shutDown = true; @@ -283,10 +293,19 @@ const fixture = Effect.fn("fixture")(function* ( ); }), ); - const run = (command: string) => + const run = (command: string, args: ReadonlyArray) => command === "emulator" ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }) - : Ref.get(encoderResult); + : command === "adb" && args.join(" ") === "devices" + ? Effect.sync( + () => + connection.adbDevices ?? { + code: 0, + stdout: `List of devices attached\n${booted ? "emulator-5554\tdevice\n" : ""}`, + stderr: "", + }, + ) + : Ref.get(encoderResult); const ready: DeviceHost.DeviceHostReady = { nodePath: process.execPath, hub: { origin: "http://device.test" }, @@ -426,6 +445,7 @@ const fixture = Effect.fn("fixture")(function* ( iosAvailable, listing, endDevice, + shutdownRequested, }; }); @@ -1574,6 +1594,66 @@ it.effect.each([ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); +describe("Android close with shutdown", () => { + const openEmulator = Effect.fn("openEmulator")(function* () { + const harness = yield* fixture(); + yield* harness.service.configure({ enabled: true }); + const threadId = ThreadId.make("android-close"); + const session = yield* harness.service.open({ + threadId, + deviceId: "Pixel_API_35", + platform: "android", + }); + expect(session.deviceId).toBe("emulator-5554"); + return { ...harness, threadId }; + }); + + it.effect("closes the session on a retry once the emulator has exited", () => + Effect.gen(function* () { + const { service, connection, endDevice, threadId } = yield* openEmulator(); + // The hub's `adb emu kill` fails once the serial is gone, so every attempt is rejected. + connection.failShutdown = true; + const first = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(first)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + + endDevice(); + yield* service.close({ threadId, shutdown: true }); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect.each([ + { + adb: "lists it offline", + result: { code: 0, stdout: "List of devices attached\nemulator-5554\toffline\n", stderr: "" }, + }, + { adb: "fails", result: { code: 1, stdout: "", stderr: "adb: no server" } }, + ])("keeps the session after a rejected shutdown when adb $adb", ({ result }) => + Effect.gen(function* () { + const { service, connection, threadId } = yield* openEmulator(); + connection.failShutdown = true; + connection.adbDevices = result; + const exit = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(exit)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + }), + ); + + it.effect("waits for an emulator the hub takes longer than 15 seconds to see exit", () => + Effect.gen(function* () { + const { service, connection, shutdownRequested, threadId } = yield* openEmulator(); + // The hub allows the emulator 30 seconds to leave adb after the kill. + connection.shutdownDelay = Duration.seconds(25); + const closing = yield* Effect.forkChild(service.close({ threadId, shutdown: true })); + yield* Deferred.await(shutdownRequested); + yield* TestClock.adjust(Duration.seconds(25)); + expect(Exit.isSuccess(yield* Fiber.await(closing))).toBe(true); + expect((yield* service.state).sessions).toEqual([]); + }), + ); +}); + it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( "retains hub inventory on %s when AVD enumeration fails and recovers on retry", (hostId) => From 8ef195587d53f99ac0464c706422f6ae067e4666 Mon Sep 17 00:00:00 2001 From: Afshin Jalili <153820238+AfshinJalili@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:21:39 +0330 Subject: [PATCH 259/288] fix(web): tell update-all users where to update desktop servers it can't reach (#33030) Co-authored-by: Julius Marminge --- .../sidebar/updateEverything.logic.test.ts | 31 +++++++++++++------ .../sidebar/updateEverything.logic.ts | 12 +++++-- apps/web/src/i18n/translations/de.json | 3 +- apps/web/src/i18n/translations/en.json | 3 +- apps/web/src/i18n/translations/es.json | 3 +- apps/web/src/i18n/translations/fr.json | 3 +- apps/web/src/i18n/translations/ja.json | 3 +- apps/web/src/i18n/translations/ko.json | 3 +- apps/web/src/i18n/translations/pt-BR.json | 3 +- apps/web/src/i18n/translations/ru.json | 3 +- apps/web/src/i18n/translations/sv.json | 3 +- apps/web/src/i18n/translations/zh.json | 3 +- 12 files changed, 51 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index f4b1d0053b22b..ea44f1592a956 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -45,6 +45,20 @@ function machine( }; } +// A desktop-mode server the desktop app cannot control, such as a WSL backend or an older app. +function withoutDesktopControl(base: UpdateEverythingMachine): UpdateEverythingMachine { + return { + ...base, + serverConfig: { + ...base.serverConfig!, + environment: { + ...base.serverConfig!.environment, + capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, + }, + }, + }; +} + describe("collectServerUpdateTargets", () => { it("updates remote servers that can move to the target and names every skipped one", () => { const { targets, skipped } = collectServerUpdateTargets( @@ -67,6 +81,7 @@ describe("collectServerUpdateTargets", () => { machine("current", "0.0.50", "boot-service"), machine("current-offline", "0.0.50", "boot-service", { connected: false }), machine("manual", "0.0.40", undefined), + withoutDesktopControl(machine("wsl-backend", "0.0.40", "desktop-managed")), ], "0.0.50", ); @@ -82,6 +97,7 @@ describe("collectServerUpdateTargets", () => { ["no-scope", "no permission"], ["busy", "already updating"], ["manual", "needs a manual update"], + ["wsl-backend", "update T3 Code on that machine"], ]); }); @@ -230,15 +246,9 @@ describe("collectChannelSwitchTargets", () => { host(machine("service", "0.1.2", "boot-service"), 70), // A Stable tag built a migration the latest Nightly does not have yet. host(machine("ahead", "0.1.3", "boot-service"), 73), - machine("old-desktop", "0.1.2", "desktop-managed", { - serverConfig: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!, - environment: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!.environment, - capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, - }, - }, - }), + withoutDesktopControl(machine("old-desktop", "0.1.2", "desktop-managed")), + // Already on Nightly, so it needs an update rather than a channel switch. + withoutDesktopControl(machine("behind-desktop", OLD_NIGHTLY, "desktop-managed")), machine("current", NIGHTLY, "boot-service"), // The server refuses a track its policy rules out, so the dialog skips it up front. managedHost(host(machine("no-nightly", "0.1.2", "boot-service"), 70)), @@ -254,7 +264,8 @@ describe("collectChannelSwitchTargets", () => { "ahead", `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`, ], - ["old-desktop", "needs a newer desktop app"], + ["old-desktop", "change the update track on that machine"], + ["behind-desktop", "update T3 Code on that machine"], [ "no-nightly", "Example Corp manages T3 Code updates. Only stable releases can be installed.", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index 6930549adf19b..f9bf0976a22e4 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -70,6 +70,10 @@ export interface SkippedMachine { readonly reason: string; } +// Desktop servers without the desktop control fd (older apps, WSL backends: wsl.exe cannot pass +// fds) cannot be updated from here, and their desktop app is not necessarily the stale part. +const UPDATE_ON_THAT_MACHINE = msg("update T3 Code on that machine"); + /** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run. * Desktop-managed servers use their own feed. Each server's updater checks that it can install the * release before it restarts, so no registry precheck runs here. */ @@ -115,7 +119,7 @@ export function collectServerUpdateTargets( continue; } if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { - skip(resolve(msg("needs a newer desktop app"))); + skip(resolve(UPDATE_ON_THAT_MACHINE)); continue; } const serverChannel = cliReleaseChannelOf(config.environment.serverVersion); @@ -425,7 +429,11 @@ function trackSwitchMove( if (selfUpdate === null) return { skip: resolve(msg("needs a manual update")) }; if (selfUpdate !== "desktop-managed") return { selfUpdate }; if (config.environment.capabilities.desktopAppChannelSwitch !== true) { - return { skip: resolve(msg("needs a newer desktop app")) }; + return { + skip: resolve( + sameTrack ? UPDATE_ON_THAT_MACHINE : msg("change the update track on that machine"), + ), + }; } // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it. if (!sameTrack && config.environment.platform.os === "darwin") { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4d3d656f33916..bafbe7d7cb731 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12145,7 +12145,8 @@ "f938bb483eb3d189": "startet zuletzt neu", "9bca02be2b4d612a": "nicht verbunden", "2dcc418b6a13b83c": "erfordert manuelles Update", - "5c8ebc36f84dee7a": "erfordert eine neuere Desktop-App", + "f13e08bd3614112e": "T3 Code auf diesem Rechner aktualisieren", + "3c3348c36a2695af": "Update-Kanal auf diesem Rechner ändern", "fa8faa732a2688ef": "im Kanal {channel}", "9b961309baafa09d": "keine Berechtigung", "9bafb2622c22d145": "wird bereits aktualisiert", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index da9e327abf64f..cde4bbb9458fa 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12153,7 +12153,8 @@ "f938bb483eb3d189": "restarts last", "9bca02be2b4d612a": "not connected", "2dcc418b6a13b83c": "needs a manual update", - "5c8ebc36f84dee7a": "needs a newer desktop app", + "f13e08bd3614112e": "update T3 Code on that machine", + "3c3348c36a2695af": "change the update track on that machine", "fa8faa732a2688ef": "on the {channel} channel", "9b961309baafa09d": "no permission", "9bafb2622c22d145": "already updating", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ff24104e8075f..ee4496f0bfbc5 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12138,7 +12138,8 @@ "f938bb483eb3d189": "se reinicia el último", "9bca02be2b4d612a": "sin conexión", "2dcc418b6a13b83c": "requiere una actualización manual", - "5c8ebc36f84dee7a": "requiere una app de escritorio más reciente", + "f13e08bd3614112e": "actualiza T3 Code en ese equipo", + "3c3348c36a2695af": "cambia el canal de actualizaciones en ese equipo", "fa8faa732a2688ef": "en el canal {channel}", "9b961309baafa09d": "sin permiso", "9bafb2622c22d145": "ya se está actualizando", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 64b28506bfe6a..dfb02854b6c38 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12143,7 +12143,8 @@ "f938bb483eb3d189": "redémarre en dernier", "9bca02be2b4d612a": "non connecté", "2dcc418b6a13b83c": "nécessite une mise à jour manuelle", - "5c8ebc36f84dee7a": "nécessite une version plus récente de l’app de bureau", + "f13e08bd3614112e": "mettez à jour T3 Code sur cette machine", + "3c3348c36a2695af": "changez le canal de mise à jour sur cette machine", "fa8faa732a2688ef": "sur le canal {channel}", "9b961309baafa09d": "pas d’autorisation", "9bafb2622c22d145": "déjà en cours de mise à jour", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f4c1b792d77e2..bba2c66a1adf0 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12094,7 +12094,8 @@ "f938bb483eb3d189": "最後に再起動", "9bca02be2b4d612a": "未接続", "2dcc418b6a13b83c": "手動での更新が必要", - "5c8ebc36f84dee7a": "新しいデスクトップアプリが必要", + "f13e08bd3614112e": "そのマシンで T3 Code を更新してください", + "3c3348c36a2695af": "そのマシンで更新トラックを変更してください", "fa8faa732a2688ef": "{channel} チャネル", "9b961309baafa09d": "権限なし", "9bafb2622c22d145": "すでに更新中", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 0ef52c37295fc..988724e7b1c8f 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12090,7 +12090,8 @@ "f938bb483eb3d189": "마지막에 다시 시작", "9bca02be2b4d612a": "연결되지 않음", "2dcc418b6a13b83c": "수동 업데이트 필요", - "5c8ebc36f84dee7a": "최신 데스크톱 앱 필요", + "f13e08bd3614112e": "해당 기기에서 T3 Code를 업데이트하세요", + "3c3348c36a2695af": "해당 기기에서 업데이트 트랙을 변경하세요", "fa8faa732a2688ef": "{channel} 채널", "9b961309baafa09d": "권한 없음", "9bafb2622c22d145": "이미 업데이트 중", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index c7354ff24613d..286cde4c55168 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12143,7 +12143,8 @@ "f938bb483eb3d189": "reinicia por último", "9bca02be2b4d612a": "não conectado", "2dcc418b6a13b83c": "precisa de atualização manual", - "5c8ebc36f84dee7a": "precisa de um app desktop mais novo", + "f13e08bd3614112e": "atualize o T3 Code nessa máquina", + "3c3348c36a2695af": "mude o canal de atualização nessa máquina", "fa8faa732a2688ef": "no canal {channel}", "9b961309baafa09d": "sem permissão", "9bafb2622c22d145": "já está atualizando", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 20e9a76a10fa1..4fbe93bc7f506 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12144,7 +12144,8 @@ "f938bb483eb3d189": "перезапуск последним", "9bca02be2b4d612a": "не подключено", "2dcc418b6a13b83c": "нужно обновить вручную", - "5c8ebc36f84dee7a": "нужна более новая версия десктопного приложения", + "f13e08bd3614112e": "обновите T3 Code на этом компьютере", + "3c3348c36a2695af": "смените канал обновлений на этом компьютере", "fa8faa732a2688ef": "на канале {channel}", "9b961309baafa09d": "нет прав", "9bafb2622c22d145": "уже обновляется", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 946abe27ad7cd..6759119ee8a98 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12151,7 +12151,8 @@ "f938bb483eb3d189": "startar om sist", "9bca02be2b4d612a": "inte ansluten", "2dcc418b6a13b83c": "behöver uppdateras manuellt", - "5c8ebc36f84dee7a": "behöver en nyare skrivbordsapp", + "f13e08bd3614112e": "uppdatera T3 Code på den datorn", + "3c3348c36a2695af": "byt uppdateringsspår på den datorn", "fa8faa732a2688ef": "på kanalen {channel}", "9b961309baafa09d": "ingen behörighet", "9bafb2622c22d145": "uppdateras redan", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 34b76ab61689c..3e4d7229881f3 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12169,7 +12169,8 @@ "f938bb483eb3d189": "最后重启", "9bca02be2b4d612a": "未连接", "2dcc418b6a13b83c": "需要手动更新", - "5c8ebc36f84dee7a": "需要更高版本的桌面应用", + "f13e08bd3614112e": "请在该机器上更新 T3 Code", + "3c3348c36a2695af": "请在该机器上更改更新通道", "fa8faa732a2688ef": "使用 {channel} 通道", "9b961309baafa09d": "没有权限", "9bafb2622c22d145": "正在更新", From 0d90edcf0f97b0e89a7eca608048dd83128024d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:55:46 -0800 Subject: [PATCH 260/288] fix(relay): APNs request spans and errors no longer record the request URL (#41859) Co-authored-by: Claude Fable 5.2 --- .../src/agentActivity/ApnsClient.test.ts | 100 ++++++++++++++++++ infra/relay/src/agentActivity/ApnsClient.ts | 21 +++- 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index f06c751982710..90da8ef10499c 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -4,11 +4,15 @@ import * as NodeCrypto from "node:crypto"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; import { describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as Tracer from "effect/Tracer"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import type { ApnsCredentials } from "../Config.ts"; @@ -304,4 +308,100 @@ describe("ApnsClient", () => { ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); }).pipe(Effect.provide(layer)); }); + + it.effect("keeps device tokens out of spans, for delivered and failed requests", () => { + ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); + const { privateKey } = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "prime256v1", + privateKeyEncoding: { type: "pkcs8", format: "pem" }, + publicKeyEncoding: { type: "spki", format: "pem" }, + }); + const credentials = { + teamId: "team-spans", + keyId: "key-spans", + privateKey: Redacted.make(privateKey), + bundleId: "com.t3tools.test", + environment: "sandbox", + } satisfies ApnsCredentials; + const spans: Array = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + const urls: Array = []; + let reachable = true; + const httpClient = HttpClient.make((request) => { + urls.push(request.url); + return reachable + ? Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))) + : Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request, cause: new Error("reset") }), + }), + ); + }); + const layer = ApnsClient.layer.pipe( + Layer.provide(ApnsProviderTokens.layer), + Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)), + Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)), + ); + + return Effect.gen(function* () { + const apns = yield* ApnsClient.ApnsClient; + const sendBoth = Effect.all( + [ + apns.sendLiveActivityRequest({ + credentials, + request: apns.makeLiveActivityRequest({ + event: "update", + token: "live-activity-device-token", + state, + nowEpochSeconds: 0, + nowIso: DateTime.formatIso(now), + }), + issuedAtUnixSeconds: 0, + }), + apns.sendPushNotificationRequest({ + credentials, + request: apns.makePushNotificationRequest({ + token: "push-notification-device-token", + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/threads/env/thread", + }, + }), + issuedAtUnixSeconds: 0, + }), + ], + { mode: "result" }, + ); + + yield* sendBoth; + reachable = false; + yield* sendBoth; + + expect(urls).toHaveLength(4); + expect(urls[0]).toContain("live-activity-device-token"); + expect(urls[1]).toContain("push-notification-device-token"); + const recorded = spans + .flatMap((span) => [ + span.name, + ...Array.from(span.attributes.values(), String), + ...(span.status._tag === "Ended" && Exit.isFailure(span.status.exit) + ? [Cause.pretty(span.status.exit.cause)] + : []), + ]) + .join("\n"); + expect(recorded).toContain("relay.apns.send_live_activity_request"); + expect(recorded).toContain("ApnsHttpRequestError"); + expect(recorded).not.toContain("device-token"); + ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); + }).pipe(Effect.provide(layer)); + }); }); diff --git a/infra/relay/src/agentActivity/ApnsClient.ts b/infra/relay/src/agentActivity/ApnsClient.ts index b21953c59eecc..b6311812365c7 100644 --- a/infra/relay/src/agentActivity/ApnsClient.ts +++ b/infra/relay/src/agentActivity/ApnsClient.ts @@ -6,6 +6,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Headers from "effect/http/Headers"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts"; import { MAX_SUMMARY_TEXT_LENGTH, truncateText } from "./agentActivityPayloads.ts"; @@ -236,6 +237,16 @@ function makePushNotificationRequest(input: { }; } +// The request URL ends in the device token. The client span records the URL, +// and so does an HTTP client error's message, so neither reaches telemetry. +const withoutClientSpan = Effect.provideService(HttpClient.TracerDisabledWhen, () => true); + +function causeWithoutRequestUrl(cause: unknown): unknown { + return HttpClientError.isHttpClientError(cause) + ? new Error(cause.reason._tag, { cause: cause.reason.cause }) + : cause; +} + function apnsReasonFromBody(body: string): string | undefined { if (body.trim().length === 0) { return undefined; @@ -289,6 +300,7 @@ const make = Effect.gen(function* () { }), HttpClientRequest.bodyJson(input.request.payload), Effect.flatMap(httpClient.execute), + withoutClientSpan, Effect.timeout(APNS_HTTP_STAGE_TIMEOUT), Effect.mapError( (cause) => @@ -300,7 +312,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "send", status: null, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -316,7 +328,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "read-response", status: response.status, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -351,6 +363,7 @@ const make = Effect.gen(function* () { }), HttpClientRequest.bodyJson(input.request.payload), Effect.flatMap(httpClient.execute), + withoutClientSpan, Effect.timeout(APNS_HTTP_STAGE_TIMEOUT), Effect.mapError( (cause) => @@ -362,7 +375,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "send", status: null, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -378,7 +391,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "read-response", status: response.status, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); From 4162207ddd63a2e066eb913f3e295733e1079def Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:58:19 -0800 Subject: [PATCH 261/288] fix(web): file menu opens remote files over SSH instead of on the server (#29771) --- apps/desktop/src/electron/ElectronMenu.ts | 18 ++ apps/web/src/components/chat/OpenInPicker.tsx | 154 +----------------- apps/web/src/components/editorIcons.ts | 152 +++++++++++++++++ .../src/components/files/FileBrowserPanel.tsx | 7 +- apps/web/src/contextMenuFallback.ts | 6 + apps/web/src/editorMenuIcons.tsx | 95 +++++++++++ apps/web/src/fileContextMenu.test.ts | 95 ++++++++++- apps/web/src/fileContextMenu.ts | 75 +++++++-- packages/contracts/src/ipc.ts | 4 + 9 files changed, 443 insertions(+), 163 deletions(-) create mode 100644 apps/web/src/components/editorIcons.ts create mode 100644 apps/web/src/editorMenuIcons.tsx diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index a967c75383447..48b61dbefd025 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -85,6 +85,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM disabled: sourceItem.disabled === true, ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}), ...(typeof sourceItem.checked === "boolean" ? { checked: sourceItem.checked } : {}), + ...(typeof sourceItem.iconImage === "string" ? { iconImage: sourceItem.iconImage } : {}), }; if (sourceItem.children) { @@ -114,6 +115,17 @@ const normalizePosition = ( Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })), ); +// Renderer icons are 32px PNGs; a 2x representation keeps them 16pt and sharp on Retina. +function menuIconImage(dataUrl: string): Option.Option { + try { + const image = Electron.nativeImage.createEmpty(); + image.addRepresentation({ scaleFactor: 2, dataURL: dataUrl }); + return image.isEmpty() ? Option.none() : Option.some(image); + } catch { + return Option.none(); + } +} + /** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -179,6 +191,12 @@ export const make = Effect.gen(function* () { } else { itemOption.click = () => complete(Option.some(item.id)); } + if (item.iconImage !== undefined) { + const image = menuIconImage(item.iconImage); + if (Option.isSome(image)) { + itemOption.icon = image.value; + } + } if (item.destructive && (!item.children || item.children.length === 0)) { const destructiveIcon = getDestructiveMenuIcon(); if (Option.isSome(destructiveIcon)) { diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 711f1e4cb3e63..fc125bbd79cfa 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -21,7 +21,7 @@ import { useRemoteOpenState, } from "../../remoteOpen"; import { useEnvironment } from "../../state/environments"; -import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react"; +import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react"; import { Group, GroupSeparator } from "../ui/group"; import { @@ -36,35 +36,9 @@ import { MenuTrigger, } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { - AntigravityIcon, - CursorIcon, - FileExplorerIcon, - FinderIcon, - Icon, - KiroIcon, - TraeIcon, - VisualStudioCode, - VisualStudioCodeInsiders, - VSCodium, - Zed, -} from "../Icons"; -import { - AquaIcon, - CLionIcon, - DataGripIcon, - DataSpellIcon, - GoLandIcon, - IntelliJIdeaIcon, - PhpStormIcon, - PyCharmIcon, - RiderIcon, - RubyMineIcon, - RustRoverIcon, - WebStormIcon, -} from "../JetBrainsIcons"; +import { type EditorIconOption, editorIconOptions } from "../editorIcons"; import { announce } from "~/lib/announce"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { shellEnvironment } from "~/state/shell"; import { useAtomCommand } from "~/state/use-atom-command"; import { @@ -77,131 +51,15 @@ import { import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { useComposerMenuState } from "./useComposerMenuState"; -type OpenInOption = { - label: string; - Icon: Icon; - value: EditorId; - kind: "brand" | "generic"; -}; +type OpenInOption = EditorIconOption & { label: string }; const resolveOpenInOptions = ( platform: string, availableEditors: ReadonlyArray, resolve: MessageResolver, -) => { - const baseOptions: ReadonlyArray> = [ - { - Icon: CursorIcon, - value: "cursor", - kind: "brand", - }, - { - Icon: TraeIcon, - value: "trae", - kind: "brand", - }, - { - Icon: KiroIcon, - value: "kiro", - kind: "brand", - }, - { - Icon: VisualStudioCode, - value: "vscode", - kind: "brand", - }, - { - Icon: VisualStudioCodeInsiders, - value: "vscode-insiders", - kind: "brand", - }, - { - Icon: VSCodium, - value: "vscodium", - kind: "brand", - }, - { - Icon: Zed, - value: "zed", - kind: "brand", - }, - { - Icon: AntigravityIcon, - value: "antigravity", - kind: "brand", - }, - { - Icon: IntelliJIdeaIcon, - value: "idea", - kind: "brand", - }, - { - Icon: AquaIcon, - value: "aqua", - kind: "brand", - }, - { - Icon: CLionIcon, - value: "clion", - kind: "brand", - }, - { - Icon: DataGripIcon, - value: "datagrip", - kind: "brand", - }, - { - Icon: DataSpellIcon, - value: "dataspell", - kind: "brand", - }, - { - Icon: GoLandIcon, - value: "goland", - kind: "brand", - }, - { - Icon: PhpStormIcon, - value: "phpstorm", - kind: "brand", - }, - { - Icon: PyCharmIcon, - value: "pycharm", - kind: "brand", - }, - { - Icon: RiderIcon, - value: "rider", - kind: "brand", - }, - { - Icon: RubyMineIcon, - value: "rubymine", - kind: "brand", - }, - { - Icon: RustRoverIcon, - value: "rustrover", - kind: "brand", - }, - { - Icon: WebStormIcon, - value: "webstorm", - kind: "brand", - }, - { - Icon: isMacPlatform(platform) - ? FinderIcon - : isWindowsPlatform(platform) - ? FileExplorerIcon - : FolderClosedIcon, - value: "file-manager", - kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", - }, - ]; +): ReadonlyArray => { const availableEditorSet = new Set(availableEditors); - return baseOptions + return editorIconOptions(platform) .filter((option) => availableEditorSet.has(option.value)) .map((option) => ({ ...option, diff --git a/apps/web/src/components/editorIcons.ts b/apps/web/src/components/editorIcons.ts new file mode 100644 index 0000000000000..e9183e82d8e1b --- /dev/null +++ b/apps/web/src/components/editorIcons.ts @@ -0,0 +1,152 @@ +import type { EditorId } from "@t3tools/contracts"; +import { FolderClosedIcon } from "lucide-react"; + +import { isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { + AntigravityIcon, + CursorIcon, + FileExplorerIcon, + FinderIcon, + type Icon, + KiroIcon, + TraeIcon, + VisualStudioCode, + VisualStudioCodeInsiders, + VSCodium, + Zed, +} from "./Icons"; +import { + AquaIcon, + CLionIcon, + DataGripIcon, + DataSpellIcon, + GoLandIcon, + IntelliJIdeaIcon, + PhpStormIcon, + PyCharmIcon, + RiderIcon, + RubyMineIcon, + RustRoverIcon, + WebStormIcon, +} from "./JetBrainsIcons"; + +export interface EditorIconOption { + readonly Icon: Icon; + readonly value: EditorId; + readonly kind: "brand" | "generic"; +} + +/** Editor logos in picker order. */ +export function editorIconOptions(platform: string): ReadonlyArray { + return [ + { + Icon: CursorIcon, + value: "cursor", + kind: "brand", + }, + { + Icon: TraeIcon, + value: "trae", + kind: "brand", + }, + { + Icon: KiroIcon, + value: "kiro", + kind: "brand", + }, + { + Icon: VisualStudioCode, + value: "vscode", + kind: "brand", + }, + { + Icon: VisualStudioCodeInsiders, + value: "vscode-insiders", + kind: "brand", + }, + { + Icon: VSCodium, + value: "vscodium", + kind: "brand", + }, + { + Icon: Zed, + value: "zed", + kind: "brand", + }, + { + Icon: AntigravityIcon, + value: "antigravity", + kind: "brand", + }, + { + Icon: IntelliJIdeaIcon, + value: "idea", + kind: "brand", + }, + { + Icon: AquaIcon, + value: "aqua", + kind: "brand", + }, + { + Icon: CLionIcon, + value: "clion", + kind: "brand", + }, + { + Icon: DataGripIcon, + value: "datagrip", + kind: "brand", + }, + { + Icon: DataSpellIcon, + value: "dataspell", + kind: "brand", + }, + { + Icon: GoLandIcon, + value: "goland", + kind: "brand", + }, + { + Icon: PhpStormIcon, + value: "phpstorm", + kind: "brand", + }, + { + Icon: PyCharmIcon, + value: "pycharm", + kind: "brand", + }, + { + Icon: RiderIcon, + value: "rider", + kind: "brand", + }, + { + Icon: RubyMineIcon, + value: "rubymine", + kind: "brand", + }, + { + Icon: RustRoverIcon, + value: "rustrover", + kind: "brand", + }, + { + Icon: WebStormIcon, + value: "webstorm", + kind: "brand", + }, + { + Icon: isMacPlatform(platform) + ? FinderIcon + : isWindowsPlatform(platform) + ? FileExplorerIcon + : FolderClosedIcon, + value: "file-manager", + kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", + }, + ]; +} diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 399ec73301814..4609a8bacd089 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -235,7 +235,12 @@ export default function FileBrowserPanel({ const position = pointerIsFresh ? { x: pointer.x, y: pointer.y } : { x: anchorRect.left, y: anchorRect.bottom }; - const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd }; + const fileTarget = { + environmentId, + filePath: relativePath, + workspaceRoot: cwd, + isDirectory: item.kind === "directory", + }; const fileMenuItems = fileContextMenu.buildItems(fileTarget); // The app menu owns focus; the tree's outside-click handler would dismiss it before click. context.close({ restoreFocus: !pointerIsFresh }); diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 0002e68d114a2..7754e191f4722 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -469,6 +469,12 @@ export function showContextMenuFallback( spacer.setAttribute("aria-hidden", "true"); button.appendChild(spacer); } + } else if (typeof item.iconImage === "string") { + const image = document.createElement("img"); + image.src = item.iconImage; + image.alt = ""; + image.className = "size-4.5 shrink-0 sm:size-4"; + button.appendChild(image); } else if (typeof item.icon === "string") { const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral"); if (icon) { diff --git a/apps/web/src/editorMenuIcons.tsx b/apps/web/src/editorMenuIcons.tsx new file mode 100644 index 0000000000000..adbabbcabecb6 --- /dev/null +++ b/apps/web/src/editorMenuIcons.tsx @@ -0,0 +1,95 @@ +import type { EditorId } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; + +import { editorIconOptions } from "./components/editorIcons"; +import { useTheme } from "./hooks/useTheme"; + +const ICON_PIXELS = 32; +const SVG_NS = "http://www.w3.org/2000/svg"; +const NO_ICONS: ReadonlyMap = new Map(); + +// Logos are styled by Tailwind and the theme, so render them in the document and inline the +// computed paint before rasterizing; native menus only accept bitmaps. +async function rasterizeEditorIcon(editor: EditorId): Promise { + const option = editorIconOptions(navigator.platform).find(({ value }) => value === editor); + if (option === undefined) return null; + const host = document.createElement("div"); + host.setAttribute("aria-hidden", "true"); + host.style.cssText = "position:fixed;left:-10000px;top:0;width:16px;height:16px;"; + document.body.append(host); + const root = createRoot(host); + try { + flushSync(() => + root.render( + , + ), + ); + const svg = host.querySelector("svg"); + if (svg === null) return null; + const clone = svg.cloneNode(true) as SVGSVGElement; + const sources = [svg, ...svg.querySelectorAll("*")]; + const targets = [clone, ...clone.querySelectorAll("*")]; + sources.forEach((source, index) => { + const computed = getComputedStyle(source); + const target = targets[index]; + target?.setAttribute( + "style", + `${target.getAttribute("style") ?? ""};fill:${computed.fill};stroke:${computed.stroke}`, + ); + }); + clone.removeAttribute("class"); + clone.setAttribute("xmlns", SVG_NS); + clone.setAttribute("width", String(ICON_PIXELS)); + clone.setAttribute("height", String(ICON_PIXELS)); + const image = new Image(); + image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = ICON_PIXELS; + canvas.height = ICON_PIXELS; + const context = canvas.getContext("2d"); + if (context === null) return null; + context.drawImage(image, 0, 0, ICON_PIXELS, ICON_PIXELS); + return canvas.toDataURL("image/png"); + } catch { + return null; + } finally { + root.unmount(); + host.remove(); + } +} + +// Keyed by theme and editor list; both change rarely, and each key rasterizes once. +const editorMenuIconsAtom = Atom.family((key: string) => + Atom.make((get): ReadonlyMap => { + const editors = key + .slice(key.indexOf("|") + 1) + .split(",") + .filter(Boolean) as EditorId[]; + // Render outside the reading component's render pass. + void Promise.resolve().then(async () => { + const icons = new Map(); + for (const editor of editors) { + const icon = await rasterizeEditorIcon(editor); + if (icon !== null) icons.set(editor, icon); + } + if (icons.size > 0) get.setSelf(icons); + }); + return NO_ICONS; + }).pipe(Atom.keepAlive, Atom.withLabel(`editor-menu-icons:${key}`)), +); + +/** PNG data URLs of editor logos for context menus; empty until rendered. */ +export function useEditorMenuIcons( + editors: ReadonlyArray, +): ReadonlyMap { + const { resolvedTheme } = useTheme(); + return useAtomValue(editorMenuIconsAtom(`${resolvedTheme}|${editors.join(",")}`)); +} diff --git a/apps/web/src/fileContextMenu.test.ts b/apps/web/src/fileContextMenu.test.ts index a5c74929d48ad..903c8c7bff7a4 100644 --- a/apps/web/src/fileContextMenu.test.ts +++ b/apps/web/src/fileContextMenu.test.ts @@ -1,7 +1,39 @@ import { EnvironmentId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; -import { resolveFileContextMenuAbsolutePath } from "./fileContextMenu"; +import { resolveFileContextMenuAbsolutePath, useFileContextMenu } from "./fileContextMenu"; +import type { RemoteOpenResolution } from "./remoteOpen"; + +const state = vi.hoisted(() => ({ + remoteOpen: { state: { mode: "local-exec" }, isResolved: true } as RemoteOpenResolution, + openInEditor: vi.fn(async () => ({ _tag: "Success" })), + openRemoteEditorUrl: vi.fn(async (_url: string) => true), +})); + +vi.mock("@effect/atom-react", () => ({ + useAtomValue: () => ({ + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "xdg-open", + environment: { platform: { os: "linux" } }, + }), +})); +vi.mock("gt-react", async (importOriginal) => ({ + ...(await importOriginal()), + useMessages: () => (text: string) => text, +})); +vi.mock(import("./state/session"), async (original) => ({ + ...(await original()), + useEnvironmentScope: () => true, +})); +vi.mock("./editorMenuIcons", () => ({ useEditorMenuIcons: () => new Map() })); +vi.mock("./state/use-atom-command", () => ({ useAtomCommand: () => state.openInEditor })); +vi.mock(import("./remoteOpen"), async (original) => ({ + ...(await original()), + useRemoteOpenResolution: () => state.remoteOpen, + useRemoteCapableEditors: () => ["vscode"], + openRemoteEditorUrl: state.openRemoteEditorUrl, +})); const BASE_TARGET = { environmentId: EnvironmentId.make("environment-local"), @@ -42,3 +74,62 @@ describe("resolveFileContextMenuAbsolutePath", () => { ).toBeNull(); }); }); + +describe("useFileContextMenu", () => { + it.each<[string, RemoteOpenResolution]>([ + ["remote-unavailable", { state: { mode: "remote-unavailable" }, isResolved: true }], + ["unresolved", { state: { mode: "local-exec" }, isResolved: false }], + ])("offers no open actions when remote open is %s", async (_mode, resolution) => { + state.remoteOpen = resolution; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + expect(state.openInEditor).not.toHaveBeenCalled(); + }); + + it("opens files over SSH remote links instead of on the server host", async () => { + state.remoteOpen = { + state: { mode: "remote-links", host: { kind: "ssh-alias", host: "box", username: "me" } }, + isResolved: true, + }; + state.openInEditor.mockClear(); + state.openRemoteEditorUrl.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([ + { + id: "open-with", + label: "Open with", + children: [{ id: "editor:vscode", label: "VS Code" }], + }, + ]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + await menu.activate("editor:vscode", { ...BASE_TARGET, filePath: "src", isDirectory: true }); + expect(state.openInEditor).not.toHaveBeenCalled(); + expect(state.openRemoteEditorUrl.mock.calls).toEqual([ + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src/index.ts:1:1"], + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src?windowId=_blank"], + ]); + }); + + it("opens files on the server host when remote open is local-exec", async () => { + state.remoteOpen = { state: { mode: "local-exec" }, isResolved: true }; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET).map((item) => item.id)).toEqual([ + "open", + "reveal-in-folder", + "open-with", + ]); + await menu.activate("open", BASE_TARGET); + expect(state.openInEditor).toHaveBeenCalledWith({ + environmentId: BASE_TARGET.environmentId, + input: { cwd: "/workspace/project/src/index.ts", editor: "file-manager" }, + }); + }); +}); diff --git a/apps/web/src/fileContextMenu.ts b/apps/web/src/fileContextMenu.ts index 58e17bff25367..28b1b4d2c950b 100644 --- a/apps/web/src/fileContextMenu.ts +++ b/apps/web/src/fileContextMenu.ts @@ -1,4 +1,6 @@ import { + AuthOrchestrationOperateScope, + buildRemoteOpenUrl, EDITORS, type ContextMenuItem, type EditorId, @@ -12,8 +14,15 @@ import { revealInFileExplorerLabelForKind, revealInFileExplorerLabelForOs, } from "~/components/preview/fileExplorerLabel"; +import { useEditorMenuIcons } from "./editorMenuIcons"; import { readLocalApi } from "./localApi"; +import { + openRemoteEditorUrl, + useRemoteCapableEditors, + useRemoteOpenResolution, +} from "./remoteOpen"; import { serverEnvironment } from "./state/server"; +import { useEnvironmentScope } from "./state/session"; import { shellEnvironment } from "./state/shell"; import { useAtomCommand } from "./state/use-atom-command"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; @@ -36,6 +45,7 @@ export interface FileContextMenuTarget { readonly filePath: string; readonly workspaceRoot: string | undefined; readonly repositoryRoot?: string | undefined; + readonly isDirectory?: boolean; } export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null { @@ -64,6 +74,7 @@ export interface FileContextMenuCapabilities { function buildFileContextMenuItems(input: { readonly hasAbsolutePath: boolean; readonly capabilities: FileContextMenuCapabilities; + readonly editorIcons: ReadonlyMap; readonly resolve: MessageResolver; }): readonly ContextMenuItem[] { if (!input.hasAbsolutePath) return []; @@ -87,10 +98,14 @@ function buildFileContextMenuItems(input: { items.push({ id: "open-with", label: input.resolve(msg("Open with")), - children: editorIds.map((editorId) => ({ - id: `editor:${editorId}` as FileContextMenuAction, - label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, - })), + children: editorIds.map((editorId) => { + const iconImage = input.editorIcons.get(editorId); + return { + id: `editor:${editorId}` as FileContextMenuAction, + label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, + ...(iconImage === undefined ? {} : { iconImage }), + }; + }), }); } return items; @@ -101,20 +116,40 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const resolve = useMessages(); - const availableEditors = serverConfig?.availableEditors ?? []; + const remoteOpen = useRemoteOpenResolution(environmentId); + const remoteCapableEditors = useRemoteCapableEditors(); + const mode = environmentId !== null && remoteOpen.isResolved ? remoteOpen.state.mode : null; + // Shell actions run on the server host, which is the viewer's machine only in local-exec. + const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const isLocalExec = mode === "local-exec" && canOperateHost; + const remoteHost = remoteOpen.state.mode === "remote-links" ? remoteOpen.state.host : null; + + const availableEditors = isLocalExec + ? (serverConfig?.availableEditors ?? []) + : mode === "remote-links" + ? remoteCapableEditors + : []; const capabilities: FileContextMenuCapabilities = { // WSL can reveal in Windows Explorer despite reporting Linux; use server wording. revealLabel: - environmentId !== null && + isLocalExec && serverConfig?.shellRevealInFileManager === true && serverConfig.availableEditors.includes("file-manager") ? serverConfig.shellRevealInFileManagerKind === undefined ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os, resolve) : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind, resolve) : undefined, - canOpenDefault: availableEditors.includes("file-manager"), + canOpenDefault: isLocalExec && availableEditors.includes("file-manager"), editorIds: availableEditors, }; + const editorIcons = useEditorMenuIcons(availableEditors); + + const editorFailureTitle = (editor: EditorId) => + resolve( + msg("Could not open in {editor}", { + editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, + }), + ); const activate = async ( action: FileContextMenuAction, @@ -128,8 +163,26 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { action === "open" || reveal ? ("file-manager" as const) : (action.slice("editor:".length) as EditorId); + if (action === "open" && !capabilities.canOpenDefault) return; + if (reveal && capabilities.revealLabel === undefined) return; if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return; + if (remoteHost !== null) { + const url = buildRemoteOpenUrl({ + editor, + ...remoteHost, + absolutePath, + isFile: target.isDirectory !== true, + }); + if (url !== undefined && (await openRemoteEditorUrl(url))) return; + toastManager.add({ + type: "error", + title: editorFailureTitle(editor), + description: absolutePath, + }); + return; + } + const result = await openInEditor({ environmentId, input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) }, @@ -142,11 +195,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { ? resolve(msg("Could not open file")) : reveal ? resolve(msg("Unable to reveal file")) - : resolve( - msg("Could not open in {editor}", { - editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, - }), - ), + : editorFailureTitle(editor), description: absolutePath, }); }; @@ -160,6 +209,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const items = buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }); if (items.length === 0 || api === undefined) return; @@ -173,6 +223,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }), capabilities, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 45f55bde2b2d8..d323c9a26de26 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -29,6 +29,8 @@ export interface ContextMenuItem { disabled?: boolean; header?: boolean; icon?: string; + /** PNG data URL; takes precedence over `icon`. */ + iconImage?: string; separatorBefore?: boolean; checked?: boolean; children?: readonly ContextMenuItem[]; @@ -46,6 +48,7 @@ export interface ContextMenuItemSchemaType { readonly disabled?: boolean; readonly header?: boolean; readonly icon?: string; + readonly iconImage?: string; readonly separatorBefore?: boolean; readonly checked?: boolean; readonly children?: readonly ContextMenuItemSchemaType[]; @@ -59,6 +62,7 @@ export const ContextMenuItemSchema: Schema.Codec = Sc disabled: Schema.optionalKey(Schema.Boolean), header: Schema.optionalKey(Schema.Boolean), icon: Schema.optionalKey(Schema.String), + iconImage: Schema.optionalKey(Schema.String), separatorBefore: Schema.optionalKey(Schema.Boolean), checked: Schema.optionalKey(Schema.Boolean), children: Schema.optionalKey( From 74382f25300d5cfd0f5c7ad2fd9f948139588802 Mon Sep 17 00:00:00 2001 From: Ruphy <20857801+RaphaelMitas@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:59:39 +0100 Subject: [PATCH 262/288] fix(server): a foreground Claude subagent shows the model it ran on, not its parent's (#39729) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 127 ++++++++++++------ .../Adapters/ClaudeAdapterV2.ts | 9 +- 2 files changed, 93 insertions(+), 43 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 297527393aaa1..455e95441d50e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -21837,27 +21837,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("records a forked skill's model from its transcript instead of the parent's", () => - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - subagentModel: "claude-haiku-4-5-20251001", - }); - const now = yield* DateTime.now; - const parentModel = "claude-opus-4-6"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-forked-skill-model"), - text: "/fork-probe go", - attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, - }), - ); + it.effect.each([ + { + launch: "forked skill", + text: "/fork-probe go", // A `context: fork` skill has no Agent call and streams none of its own replies: // task_started carries no tool_use_id, and only its prompt echo names the fork. - for (const frame of [ + frames: [ claudeSdkFrame({ type: "system", subtype: "task_started", @@ -21888,28 +21874,93 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000233", session_id: WAKE_NATIVE_SESSION, }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.take(harness.terminalReceipts); + ], + }, + { + launch: "foreground Agent call with no streamed reply", + text: "Ask a subagent one thing.", + frames: [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: "claude-opus-4-6", + id: "msg_unstreamed_model_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu-unstreamed-model", + name: "Agent", + input: { description: "One thing", prompt: "Check one thing." }, + }, + ], + }, + uuid: "00000000-0000-4000-8000-000000000235", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-unstreamed-model", + tool_use_id: "toolu-unstreamed-model", + description: "One thing", + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000236", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: "task-unstreamed-model", + toolUseId: "toolu-unstreamed-model", + summary: "OK", + uuid: "00000000-0000-4000-8000-000000000237", + }), + ], + }, + ])( + "records the model of a $launch from its transcript instead of the parent's", + ({ text, frames }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + subagentModel: "claude-haiku-4-5-20251001", + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-transcript-model"), + text, + attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: "claude-opus-4-6" }, + }), + ); + for (const frame of [ + ...frames, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); - const fork = harness.events - .filter((event) => event.type === "subagent.updated") - .at(-1)?.subagent; - assert.equal(fork?.status, "completed"); - assert.equal(fork?.model, "claude-haiku-4-5"); - assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + const subagent = harness.events + .filter((event) => event.type === "subagent.updated") + .at(-1)?.subagent; + assert.equal(subagent?.status, "completed"); + assert.equal(subagent?.model, "claude-haiku-4-5"); + assert.equal(subagent?.modelSelection?.model, "claude-haiku-4-5"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect.each([ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f5993b8a1824a..ab601a9d255e2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -7650,9 +7650,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // A `context: fork` skill has no Agent call and streams none of its own frames; - // only its transcript records the model, written after the fork reports its outcome. - const forkedSkillModel = Effect.fnUntraced(function* ( + // A `context: fork` skill, or a foreground subagent whose replies were never streamed, + // leaves no model on any frame; only its transcript records it, written once it finishes. + const transcriptModel = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, nativeThreadId: string, taskId: string, @@ -7660,7 +7660,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); if ( registered === undefined || - registered.runToolUseId !== null || registered.task.model !== null || registered.task.status === "running" ) { @@ -12424,7 +12423,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return next; }); for (const taskId of context.subagentsByTaskId.keys()) { - const model = yield* forkedSkillModel(context, liveQuery.nativeThreadId, taskId); + const model = yield* transcriptModel(context, liveQuery.nativeThreadId, taskId); const status = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId)?.task.status; if ( model !== undefined && From 30c5df09713d2acd10a587a0f649f507e08fc19c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:03:12 -0800 Subject: [PATCH 263/288] fix(server): a commit's diff is read only for commits the change request lists (#41863) Co-authored-by: Claude Fable 5.2 --- .../pullRequest/PullRequestService.test.ts | 63 +++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 63 ++++++++++++++----- 2 files changed, 112 insertions(+), 14 deletions(-) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 5f25633b96047..8852e5f1fe058 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -5173,6 +5173,66 @@ it.effect("authorizes cold source reads with paginated paths without fetching pa }), ); +const activityListing = (...oids: ReadonlyArray) => ({ + getChangeRequestActivity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: oids.map((oid) => ({ + oid, + messageHeadline: "Change", + committedDate: "2026-01-01T00:00:00.000Z", + })), + }), +}); + +it.effect("reads a commit's diff only for a commit the change request lists", () => + Effect.gen(function* () { + const listed = "a".repeat(40); + const read: Array = []; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing(listed, "b".repeat(40)), + getDiff: (input) => + Effect.sync(() => { + read.push(input.commit); + return { + patch: "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n+x\n", + truncated: false, + nextCursor: null, + }; + }), + getDiffFileContents: (input) => + Effect.sync(() => { + read.push(input.commit); + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const file = { changeType: "change" as const, oldPath: "a.ts", newPath: "a.ts" }; + + for (const commit of ["c".repeat(40), "abcdef", "A".repeat(41), ""]) { + const diff = yield* service.diff({ ...ref, commit }).pipe(Effect.flip); + const contents = yield* service + .diffFileContents({ ...ref, ...file, commit }) + .pipe(Effect.flip); + assert.strictEqual(diff.reason, "not-found"); + assert.strictEqual(contents.reason, "not-found"); + } + assert.deepStrictEqual(read, []); + + yield* service.diff({ ...ref, commit: "AAAAAAA" }); + yield* service.diffFileContents({ ...ref, ...file, commit: "aaaaaaa" }); + assert.deepStrictEqual(read, [listed, listed]); + }), +); + it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( "keeps cold metadata membership in its original scope through an in-flight %s", (boundary) => @@ -5192,6 +5252,7 @@ it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.die("Membership must not fetch patch hunks"), getDiffFilePaths: (input) => Effect.gen(function* () { @@ -5356,6 +5417,7 @@ it.effect.each(["commit", "credential"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.sync(() => ({ patch: @@ -5413,6 +5475,7 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref ], providers: [ fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing("a".repeat(40)), getDiff: () => Effect.gen(function* () { if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null }; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e7d1b8abae5de..f3ac5cbe0d3d0 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -3723,10 +3723,40 @@ export const make = Effect.gen(function* () { ); return { key, read }; }; - const diff: PullRequestService["Service"]["diff"] = (input) => { - const { key, read } = readDiff(input); - return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + // A host reads a commit's diff from the repository, not from the change request, so a named + // commit is forwarded only as the one oid the change request's own commit list gives for it. + const withListedCommit = ( + operation: string, + input: I, + read: (input: I) => Effect.Effect, + ): Effect.Effect => { + const wanted = input.commit?.toLowerCase(); + if (wanted === undefined) return Effect.succeed(input); + return read(input).pipe( + Effect.flatMap(({ commits }) => { + const listed = /^[0-9a-f]{7,64}$/.test(wanted) + ? commits.filter((commit) => commit.oid.toLowerCase().startsWith(wanted)) + : []; + const [commit] = listed; + return commit !== undefined && listed.length === 1 + ? Effect.succeed({ ...input, commit: commit.oid }) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: "This commit is not part of the change request.", + reason: "not-found", + }), + ); + }), + ); }; + const diff: PullRequestService["Service"]["diff"] = (input) => + withListedCommit("diff", input, activity).pipe( + Effect.flatMap((input) => { + const { key, read } = readDiff(input); + return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + }), + ); const filesViewedCache = yield* Cache.makeWith( (key: string) => { @@ -4146,18 +4176,23 @@ export const make = Effect.gen(function* () { return walk(undefined); }; // PR read access does not grant arbitrary repository reads with the project credential; restrict to changed files. + const listedActivity = credentialCached(activity); const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => - changesFile(input).pipe( - Effect.flatMap((changed) => - changed - ? readDiffFileContents(input) - : Effect.fail( - new PullRequestOperationError({ - operation: "diffFileContents", - detail: "This file is not part of the change request.", - reason: "not-found", - }), - ), + withListedCommit("diffFileContents", input, listedActivity).pipe( + Effect.flatMap((input) => + changesFile(input).pipe( + Effect.flatMap((changed) => + changed + ? readDiffFileContents(input) + : Effect.fail( + new PullRequestOperationError({ + operation: "diffFileContents", + detail: "This file is not part of the change request.", + reason: "not-found", + }), + ), + ), + ), ), ); From aab127d7fba5ca7ce185a956089b699994322166 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:04:35 -0800 Subject: [PATCH 264/288] fix(shared): repository keys for one-segment URL remotes name only the repository (#41862) Co-authored-by: Claude Fable 5.2 --- packages/shared/src/git.test.ts | 22 ++++++++++++++++++++++ packages/shared/src/git.ts | 9 ++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index e454a989fb7b6..2ea8a26379086 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -85,6 +85,28 @@ describe("normalizeGitRemoteUrl", () => { expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project"); expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project"); }); + + it("keys a one-segment URL remote by what names the repository", () => { + expect(normalizeGitRemoteUrl("https://deploy:s3cr3ttok@git.example.com/Repo.git")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("https://0123abcd@git.example.com/repo.git?key=0123abcd#x")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("ftp://deploy:s3cr3ttok@git.example.com/team/repo.git")).toBe( + "ftp://git.example.com/team/repo", + ); + expect(normalizeGitRemoteUrl("ssh://git:s3cr3ttok@git.example.com:2222/repo.git")).toBe( + "ssh://git@git.example.com:2222/repo", + ); + expect(normalizeGitRemoteUrl("ssh://git@git.example.com/repo.git")).toBe( + "ssh://git@git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("https://git.example.com/repo.git")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("/srv/git/Repo.git")).toBe("/srv/git/repo"); + }); }); describe("isBareGitConfig", () => { diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 7ef56875e34b5..c942d2976c2d1 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -198,7 +198,14 @@ export function parseGitRemoteRepository( */ export function normalizeGitRemoteUrl(value: string): string { const repository = parseGitRemoteRepository(value); - return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`; + if (repository !== null) return `${repository.host}/${repository.path}`; + // The key is shown to clients and persisted, so a URL it cannot parse keeps only what names the + // repository: no password, query or fragment, and a user only over SSH, where it is a login name. + const remote = lowerCaseRemote(value); + const url = /^([a-z][a-z0-9+.-]*):\/\/(?:([^/?#:@]*)(?::[^/?#]*)?@)?([^?#]*)/.exec(remote); + if (url === null) return remote; + const [, scheme = "", user = "", rest = ""] = url; + return lowerCaseRemote(`${scheme}://${scheme === "ssh" && user ? `${user}@` : ""}${rest}`); } function* gitConfigLines(configText: string) { From ae926f65790cea48e398adf6531bc117928d9ad5 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:04:46 +0100 Subject: [PATCH 265/288] fix(web): Cmd/Ctrl+F opens the browser find bar while a pull request is maximized (#41852) Co-authored-by: only21mil <263261067+only21mil@users.noreply.github.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../PullRequestsColumn.browser.test.tsx | 59 +++++++++++++++++++ .../pullRequest/PullRequestsColumn.tsx | 3 +- .../src/shortcuts/chatRouteCommands.test.ts | 17 ++++++ apps/web/src/shortcuts/chatRouteCommands.ts | 8 ++- 4 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx new file mode 100644 index 0000000000000..1e4de32289e69 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx @@ -0,0 +1,59 @@ +import { createRef, type RefObject } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import { PullRequestsColumn } from "./PullRequestsColumn"; + +function createColumn(maximizedAway: boolean, scrollRef: RefObject) { + return ( + {}} + searchValue="" + involvement="all" + state="open" + host={undefined} + hostMenuOptions={[]} + onInvolvement={() => {}} + onState={() => {}} + onHost={() => {}} + searchInput={} + sortMenu={null} + filtersMenu={null} + savedViewsMenu={null} + rightPanelControl={null} + titlebarControls={null} + rightPanelOpen={maximizedAway} + maximizedAway={maximizedAway} + listBody={null} + scrollRef={scrollRef} + /> + ); +} + +function dispatchFindShortcut() { + const event = new KeyboardEvent("keydown", { + key: "f", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + window.dispatchEvent(event); + return event; +} + +describe("PullRequestsColumn find shortcut", () => { + it("leaves Cmd/Ctrl+F to the browser while the detail panel is maximized", async () => { + const scrollRef = createRef(); + await using screen = await render(createColumn(false, scrollRef)); + + await screen.rerender(createColumn(true, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(false); + + await screen.rerender(createColumn(false, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(true); + await expect + .element(screen.getByRole("textbox", { name: "Search pull requests" })) + .toHaveFocus(); + }); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx index fdfe825790ba6..d4ca6d0d3b7e2 100644 --- a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx @@ -138,6 +138,7 @@ export function PullRequestsColumn({ const searchExpanded = searchOpen || searchValue.length > 0; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener focuses the visible search input on Cmd/Ctrl+F useEffect(() => { + if (maximizedAway) return; const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey)) return; @@ -151,7 +152,7 @@ export function PullRequestsColumn({ }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [condensed]); + }, [condensed, maximizedAway]); if (!condensed && searchOpen) setSearchOpen(false); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves DOM focus to the in-flow search when the topbar search it was typed in unmounts useEffect(() => { diff --git a/apps/web/src/shortcuts/chatRouteCommands.test.ts b/apps/web/src/shortcuts/chatRouteCommands.test.ts index 3979368ff9032..db332610cd923 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.test.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.test.ts @@ -105,4 +105,21 @@ describe("preview commands", () => { expect(dispatch).toHaveBeenCalledWith(action); }); + + it("preview.find leaves the key unclaimed on non-thread chat routes", () => { + using dispatch = vi.spyOn(previewActions, "dispatchPreviewAction").mockImplementation(() => {}); + using register = vi.spyOn(dispatcher, "registerCommands").mockReturnValue(() => {}); + const router = { + state: { matches: [{ routeId: "/_chat/pull-requests", params: {} }] }, + } as unknown as AnyRouter; + using stack = new DisposableStack(); + stack.defer(installChatRouteCommands(router)); + const event = { preventDefault: vi.fn(), stopPropagation: vi.fn() } as unknown as KeyboardEvent; + + const result = register.mock.calls[0]![0]["preview.find"]!(event); + + expect(result).toBe(false); + expect(event.preventDefault).not.toHaveBeenCalled(); + expect(dispatch).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index 7cca45fbd81db..90ccf9fc2023f 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -186,7 +186,13 @@ export function installChatRouteCommands(router: AnyRouter): () => void { "preview.zoomIn": zoomCommand("zoom-in"), "preview.zoomOut": zoomCommand("zoom-out"), "preview.resetZoom": zoomCommand("reset-zoom"), - "preview.find": previewCommand("find"), + // Unclaimed, the browser's own find runs when no thread handles panel find. + "preview.find": (event) => { + const environmentId = readRouteEnvironmentId(); + if (!environmentId || !canOperatePreview(environmentId)) return false; + claim(event); + dispatchPreviewAction("find"); + }, }, { when: () => From 693117121770bc1c4441e032598ebee9ae2f3ae7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:05:58 -0800 Subject: [PATCH 266/288] fix(server): snapshot and transcript reads report a deleted thread as missing (#41866) Co-authored-by: Claude Fable 5.2 --- .../orchestration-v2/ProjectionStore.test.ts | 29 +++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 5 ++++ 2 files changed, 34 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 636e69e7574b0..8de65435fda24 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -2854,6 +2854,31 @@ const recordsThreadCreated = (threadId: ThreadId) => }, }) as never; +const snapshotsReadDeletedThreadAsMissing = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:records:deleted-snapshot"); + const created: { readonly payload: object } = recordsThreadCreated(threadId); + yield* store.apply(created as never); + assert.equal((yield* store.getThreadSnapshot(threadId)).projection.thread.id, threadId); + yield* store.apply({ + id: EventId.make(`event:${threadId}:deleted`), + type: "thread.deleted", + threadId, + providerInstanceId, + occurredAt: recordsAt(1), + payload: { ...created.payload, deletedAt: recordsAt(1) }, + } as never); + + for (const read of [ + store.getThreadSnapshot(threadId), + store.getThreadSnapshotWindow(threadId, { rowLimit: 10 }), + ]) { + assert.equal((yield* Effect.flip(read))._tag, "ProjectionStoreThreadNotFoundError"); + } + // Forks of the thread still read its rows. + assert.equal((yield* store.getThreadProjection(threadId)).thread.id, threadId); +}); + const queryPlan = Effect.fn("queryPlan")(function* (statement: string | undefined) { assert.isDefined(statement); const sql = yield* SqlClient.SqlClient; @@ -3941,6 +3966,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { "SQL recovery selects unfinished runless native subagents", () => runlessNativeSubagentNeedsRecovery, ); + it.effect( + "snapshot reads report a deleted thread as missing", + () => snapshotsReadDeletedThreadAsMissing, + ); it.effect( "worktree path and title lookups skip deleted threads, and can include archived ones", () => threadWorktreePathsIncludeArchivedOnRequest, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 69848d6a44f74..b0fa371bbba33 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -7079,6 +7079,9 @@ export const layer: Layer.Layer = .withTransaction( Effect.gen(function* () { const projection = yield* getThreadProjection(threadId); + // Deletion keeps the rows for surviving forks; a client reads the thread as gone. + if (projection.thread.deletedAt !== null) + return yield* new ProjectionStoreThreadNotFoundError({ threadId }); const rows = yield* sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence FROM orchestration_events @@ -8264,6 +8267,8 @@ export const layer: Layer.Layer = : {}), ...(historyAnchor === undefined ? {} : { historyAnchor }), }); + if (projection.thread.deletedAt !== null) + return yield* new ProjectionStoreThreadNotFoundError({ threadId }); // Pending requests outlive their turn's window; clients read their prompt from the card. const retainedIds = new Set(projection.turnItems.map((item) => item.id)); const pendingCards = (yield* decodeRows( From 860da094fd1e1762113047a445522a9909a51442 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:06:17 -0800 Subject: [PATCH 267/288] fix(server): ACP Registry listing and preparation follow agent readiness and provider policy (#41867) Co-authored-by: Claude Fable 5.2 --- apps/server/src/ws.test.ts | 128 ++++++++++++++++++++++++++++++++++++- apps/server/src/ws.ts | 26 +++++++- 2 files changed, 150 insertions(+), 4 deletions(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 806a045898ddc..d12488a1b0db7 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -11,6 +11,8 @@ import { type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + AuthProvidersManageScope, + type ManagedPolicySummary, type WorkflowRun, type WorkflowStep, AuthSessionId, @@ -2378,6 +2380,7 @@ const acpSessionTags = [ WS_METHODS.serverListAcpRegistrySessions, WS_METHODS.serverImportAcpRegistrySession, WS_METHODS.serverDeleteAcpRegistrySession, + WS_METHODS.serverPrepareAcpRegistryAgent, ] as const; const acpSessionRpcs = WsRpcGroup.omit( ...[...WsRpcGroup.requests.keys()].filter( @@ -2513,7 +2516,9 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i const instance = { driverKind: acpDriver, snapshot: { - getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true, canDelete: true } }), + getSnapshot: Effect.succeed({ + nativeSessions: { canList: true, canLoad: true, canDelete: true }, + }), }, acpSessionManagement: { listSessions: () => @@ -2750,6 +2755,127 @@ const layerWorkflowRpcTest = Layer.mergeAll( Layer.mock(ServerBrowser.ServerBrowser)({}), ); +/** A client for the ACP Registry RPCs; `calls` records what reached the agent or the catalog. */ +const makeAcpRegistryClient = Effect.fn("test.makeAcpRegistryClient")(function* ( + calls: Array, + options: { + readonly nativeSessions?: { readonly canList: boolean }; + readonly managedPolicy?: ManagedPolicySummary; + }, +) { + const scopes = [AuthOrchestrationReadScope, AuthProvidersManageScope]; + const instance = { + driverKind: acpDriver, + snapshot: { getSnapshot: Effect.succeed({ nativeSessions: options.nativeSessions }) }, + } as unknown as ProviderInstance; + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ServerSettings.layerTest({}, options.managedPolicy), + Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({ + prepare: ({ agentId }) => + Effect.sync(() => calls.push(`prepare:${agentId}`)).pipe( + Effect.as({ agentId, version: "1.0.0", distribution: "npx", prepared: true } as const), + ), + }), + Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({ + project: () => Effect.succeed({ workspaceRoot: "/workspace/acp" } as never), + sessionManager: () => + Effect.succeed({ + instance, + manager: { + listSessions: () => + Effect.sync(() => calls.push("listSessions")).pipe( + Effect.as({ sessions: [], nextCursor: null }), + ), + } as unknown as NonNullable, + }), + }), + ); + return yield* RpcTest.makeClient(acpSessionRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("acp-test"), + subject: "acp-test", + method: "browser-session-cookie", + scopes, + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); + +it.effect("listing ACP sessions reaches only an agent that advertises listing", () => + Effect.gen(function* () { + const calls: Array = []; + const input = { instanceId: acpInstanceId, projectId: acpProjectId }; + + const unprobed = yield* makeAcpRegistryClient(calls, {}); + const refused = yield* unprobed[WS_METHODS.serverListAcpRegistrySessions](input).pipe( + Effect.flip, + ); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.reason : refused._tag, + "session_list_unsupported", + ); + assert.deepEqual(calls, []); + + const probed = yield* makeAcpRegistryClient(calls, { nativeSessions: { canList: true } }); + yield* probed[WS_METHODS.serverListAcpRegistrySessions](input); + assert.deepEqual(calls, ["listSessions"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + +it.effect("preparing an ACP Registry agent follows the policy's allowed providers", () => + Effect.gen(function* () { + const calls: Array = []; + const policy = (...allowedDrivers: ReadonlyArray): ManagedPolicySummary => ({ + organization: "Example Corp", + lockedSettings: [], + limits: { + providers: { + allowedDrivers: [ + ProviderDriverKind.make("codex"), + ...allowedDrivers.map((driver) => ProviderDriverKind.make(driver)), + ], + lockedInstanceFields: {}, + }, + }, + }); + + const excluded = yield* makeAcpRegistryClient(calls, { managedPolicy: policy() }); + const refused = yield* excluded[WS_METHODS.serverPrepareAcpRegistryAgent]({ + agentId: "example-agent", + }).pipe(Effect.flip); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.message : refused._tag, + "Example Corp's policy does not allow the ACP Registry provider.", + ); + assert.deepEqual(calls, []); + + const included = yield* makeAcpRegistryClient(calls, { + managedPolicy: policy("acpRegistry"), + }); + yield* included[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + const unmanaged = yield* makeAcpRegistryClient(calls, {}); + yield* unmanaged[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + assert.deepEqual(calls, ["prepare:example-agent", "prepare:example-agent"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => Effect.gen(function* () { const calls: Array = []; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b6922b9e90996..f0f746eb8041f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -36,6 +36,7 @@ import { AuthOrchestrationOperateScope, AuthProvidersManageScope, type AuthEnvironmentScope, + ProviderDriverKind, type ScheduledTaskListResult, WorkflowRequestError, AuthSessionId, @@ -198,6 +199,7 @@ import * as NpmRelease from "./cloud/npmRelease.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as ManagedProviders from "./policy/managedProviders.ts"; import * as ServerSettings from "./serverSettings.ts"; import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecrets.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; @@ -1644,6 +1646,14 @@ export const layerWsRpc = ( ) { const project = yield* acpRegistrySessions.project(input.projectId); const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); + // Only a probed agent advertises listing, so a read never installs or first-starts one. + const snapshot = yield* instance.snapshot.getSnapshot; + if (snapshot.nativeSessions?.canList !== true) { + return yield* new AcpRegistryOperationError({ + reason: "session_list_unsupported", + message: "The ACP agent does not advertise session listing.", + }); + } const listed = yield* manager.listSessions({ cwd: project.workspaceRoot, ...(input.cursor === undefined ? {} : { cursor: input.cursor }), @@ -2441,9 +2451,19 @@ export const layerWsRpc = ( [WS_METHODS.serverPrepareAcpRegistryAgent]: (input) => Effect.annotateCurrentSpan({ "acp_registry.agent_id": input.agentId }).pipe( Effect.andThen( - acpRegistryCatalog - .prepare(input) - .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), + Effect.suspend(() => { + const blocked = ManagedProviders.disallowedDriverReason( + serverSettings.managedPolicy, + ProviderDriverKind.make("acpRegistry"), + ); + return blocked === undefined + ? acpRegistryCatalog + .prepare(input) + .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)) + : Effect.fail( + new AcpRegistryOperationError({ reason: "install_failed", message: blocked }), + ); + }), ), ), [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: (input) => From b1c83e180f5ca1906df1a1a050a6ed689f88c56a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:06:33 -0800 Subject: [PATCH 268/288] fix(server): guests get failed file edits without their text (#41865) Co-authored-by: Claude Fable 5.2 --- .../src/guest/GuestShareService.test.ts | 59 ++++++++++++++++++- apps/server/src/guest/GuestShareService.ts | 32 +++++++--- 2 files changed, 79 insertions(+), 12 deletions(-) diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 363c9d84d4e2c..cb68cece707d8 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -546,6 +546,52 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("gives the guest a failed edit without the text it tried to write", () => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const failedEdit = (id: string) => + writeItem(id, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }); + const before = yield* failedEdit("item:failed-before"); + + const events = yield* guestShares.stream(session); + const during = yield* failedEdit("item:failed-during"); + const detail = (yield* guestShares.item(session, before)).item; + yield* orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("close-after-failed-edit"), + threadId, + }); + const received = Array.from(yield* Stream.runCollect(events)); + const changes = received.flatMap((event) => { + if (event.type !== "thread") return []; + if (event.item.kind === "snapshot") { + return [ + ...event.item.projection.turnItems, + ...event.item.projection.visibleTurnItems.map((row) => row.item), + ]; + } + return event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : []; + }); + const failed = changes.filter((item) => item.type === "file_change"); + assert.includeMembers( + failed.map((item) => item.id), + [before, during], + ); + for (const change of [...failed, detail]) { + assert.deepInclude(change, { status: "failed", fileName: "src/auth.ts" }); + assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr"]); + } + }).pipe(Effect.provide(layerTest)), +); + it.effect("gives a fork's guest the commands the fork shows from its source thread", () => Effect.gen(function* () { const { orchestrator, guestShares } = yield* shareThread; @@ -656,13 +702,19 @@ it.effect("pages the guest back through turns older than the stream's snapshot", }); yield* eventSink.write({ events: [ - turnItem("item:old-image", 1, { + turnItem("item:old-edit", 1, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }), + turnItem("item:old-image", 2, { type: "assistant_message", text: `![Old](${shot})`, streaming: false, }), ...Array.from({ length: 30 }, (_, index) => - turnItem(`item:ask-${index}`, index + 2, { + turnItem(`item:ask-${index}`, index + 3, { type: "user_message", text: `Ask ${index}`, createdBy: "user", @@ -694,9 +746,10 @@ it.effect("pages the guest back through turns older than the stream's snapshot", while (cursor !== null) { const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); older.push(...ids(page.items)); + for (const { item } of page.items) assert.notProperty(item, "diffStr"); cursor = page.hasMoreHistory ? page.nextCursor : null; } - assert.include(older, "item:old-image"); + assert.includeMembers(older, ["item:old-image", "item:old-edit"]); assert.deepStrictEqual(yield* guestShares.media(session, shot), { path: shot, mimeType: "image/png", diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index b5b21a7af2ae7..5ff7ae22770e2 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -52,7 +52,6 @@ import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoa import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts"; import { projectTurnItemForDetail, - projectTurnItemForWire, threadStreamEventItem, } from "../orchestration-v2/WireProjection.ts"; import * as DocumentText from "../provider/DocumentText.ts"; @@ -218,6 +217,16 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | } }; +/** A guest sees that a file changed, never the text of the change, whatever its status. */ +const withoutFileText = (item: OrchestrationV2TurnItem): OrchestrationV2TurnItem => { + if (item.type !== "file_change") return item; + const { diffStr: _diff, oldStr: _old, newStr: _new, ...shown } = item; + return shown; +}; +const rowWithoutFileText = ( + row: Row, +): Row => ({ ...row, item: withoutFileText(row.item) }); + const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const commandOutputs = yield* CommandOutputHub.CommandOutputHub; @@ -566,12 +575,16 @@ const make = Effect.gen(function* () { if (item.kind !== "event") return []; if (endsShare(item.event)) return [ended]; if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]); + const shown = + item.event.type === "turn-item.updated" + ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } } + : item; const updated = threadOf(item.event); const view = updated === null ? null : viewOf(updated); return view === null - ? [{ type: "thread", item }] + ? [{ type: "thread", item: shown }] : [ - { type: "thread", item }, + { type: "thread", item: shown }, { type: "view", view }, ]; }), @@ -585,7 +598,11 @@ const make = Effect.gen(function* () { ); const openingSnapshot = buildBoundedThreadStreamSnapshot({ snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, + projection: { + ...snapshot.projection, + turnItems: snapshot.projection.turnItems.map(withoutFileText), + visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText), + }, }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, @@ -669,10 +686,7 @@ const make = Effect.gen(function* () { const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) { const { item } = yield* threadItem(session, itemId); - return { - item: - item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item), - }; + return { item: projectTurnItemForDetail(withoutFileText(item)) }; }); const history = Effect.fn("GuestShareService.history")(function* ( @@ -687,7 +701,7 @@ const make = Effect.gen(function* () { share.id, page.items.map((row) => row.item), ); - return page; + return { ...page, items: page.items.map(rowWithoutFileText) }; }); const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( From 4508c706813f6457599f3ea260e0ae278ad9480e Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:07:52 -0500 Subject: [PATCH 269/288] fix(web): opening a thread lands at its end instead of jumping there (#41843) Co-authored-by: Julius Marminge --- .../chat/MessagesTimeline.browser.test.tsx | 45 ++++ .../src/components/chat/MessagesTimeline.tsx | 6 +- patches/@legendapp__list@3.7.3.patch | 238 +++++++++++++++++- pnpm-lock.yaml | 8 +- 4 files changed, 288 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index f0fe30716818e..a38a51feab4c7 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -815,6 +815,51 @@ describe("MessagesTimeline messages", () => { expectItemOrder(); }); + it("opens a working parent thread at its end without landing short", async () => { + setup(); + const props = baseProps(); + const parent = Array.from({ length: 30 }, (_, index) => + message( + `Parent turn ${index}:\n\n${"x ".repeat(200)}`, + { role: index % 2 === 0 ? "user" : "assistant" }, + `parent-${index}`, + ), + ); + await using screen = await renderElement( + {} }} + timelineEntries={[message("Short child reply.", { role: "assistant" }, "child-0")]} + />, + ); + expect(screen.text()).toContain("Subagent of"); + const viewport = props.listRef.current!.getScrollableNode()!; + const end = () => viewport.scrollHeight - viewport.clientHeight; + // Distance from the end as each scroll lands, against the content height at that moment. + const shortfalls: number[] = []; + viewport.addEventListener("scroll", () => + shortfalls.push(Math.round(end() - viewport.scrollTop)), + ); + + // A working parent's footer (queued turns, its subagents) is taller than the child's. + await screen.rerender( + Waiting on 4 subagents
} + isWorking + />, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain("Parent turn 29:"); + expect(end() - viewport.scrollTop).toBeLessThanOrEqual(1); + }); + + expect(shortfalls.length).toBeGreaterThan(0); + expect(shortfalls).toEqual(shortfalls.map(() => 0)); + }); + it("puts rows back in item order soon after a continuous scroll stops", async () => { setup(); const props = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 7b0a883139635..575000a55e598 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1505,10 +1505,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH : TIMELINE_MAINTAIN_SCROLL_AT_END } + // A restore owns the scroll position until it lands. Anchoring would + // move it for the previous thread's header as the list swaps threads. maintainVisibleContentPosition={ - findActive || - citationPositioning || - (restoringThreadPosition && rememberedPosition?.atEnd === false) + findActive || citationPositioning || restoringThreadPosition ? false : maintainVisibleContentPosition } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch index 2afc400b04435..a947d0b614372 100644 --- a/patches/@legendapp__list@3.7.3.patch +++ b/patches/@legendapp__list@3.7.3.patch @@ -1,5 +1,5 @@ diff --git a/react-native.js b/react-native.js -index 440b0ad..fd5d18d 100644 +index 440b0ad0d8af34e5dc4ae9b2a21a7addd2d71efb..fd5d18d8d184036d140f543285c9b5738513baa7 100644 --- a/react-native.js +++ b/react-native.js @@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { @@ -13,7 +13,7 @@ index 440b0ad..fd5d18d 100644 set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); set$( diff --git a/react-native.mjs b/react-native.mjs -index b95e1f8..e2b013a 100644 +index b95e1f86d2cd76d5dbaf1340fdc37f3f1990e9ee..e2b013a0969d512d7c9b5e6fe7d348761f286bed 100644 --- a/react-native.mjs +++ b/react-native.mjs @@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { @@ -26,3 +26,237 @@ index b95e1f8..e2b013a 100644 set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); set$( +diff --git a/react.js b/react.js +index 24cc6054d3fa59742c7f50457a18adf451128bbb..32e59a03a4da96776f2690085ff3eebb452be397 100644 +--- a/react.js ++++ b/react.js +@@ -6376,7 +6376,8 @@ function useOnLayoutSync({ + onLayoutProp, + onLayoutChange, + webLayoutResync, +- webExternalScroll = false ++ webExternalScroll = false, ++ measureNowRef + }, deps) { + const callbacks = useLatestRef({ onLayoutChange, onLayoutProp, webLayoutResync }); + const onExternalLayout = React3.useCallback( +@@ -6409,7 +6410,7 @@ function useOnLayoutSync({ + emit(toLayout(rect), true); + prevRect = rect; + } +- return createResizeObserver(element, (entry) => { ++ const disconnectResizeObserver = createResizeObserver(element, (entry) => { + var _a4, _b2, _c; + const target = entry.target instanceof HTMLElement ? entry.target : void 0; + const borderBoxSize = Array.isArray(entry.borderBoxSize) ? entry.borderBoxSize[0] : entry.borderBoxSize; +@@ -6427,7 +6428,30 @@ function useOnLayoutSync({ + emit(toLayout(rectObserved), false); + } + }); +- }, [callbacks, measureInLayoutEffect, webExternalScroll, ...deps || []]); ++ if (!measureNowRef) return disconnectResizeObserver; ++ // T3 patch: measure on demand through the observer's own baseline, so a ++ // forced read and a later observer delivery never disagree about the size. ++ const measureNow = () => { ++ const rect = element.getBoundingClientRect(); ++ if (rect.height === 0 && rect.width === 0) return; ++ const previousRect = prevRect != null ? prevRect : getContainerLayoutBaseline(element); ++ if (previousRect !== void 0 && rect.width === previousRect.width && rect.height === previousRect.height) return; ++ prevRect = rect; ++ emit(toLayout(rect), true); ++ // The browser only reports sizes that differ from its last delivery. Re-observe so a ++ // return to that size is still reported against the baseline this read just moved. ++ if (typeof ResizeObserver !== "undefined" && callbackMap.has(element)) { ++ const observer = getGlobalResizeObserver(); ++ observer.unobserve(element); ++ observer.observe(element, { box: "border-box" }); ++ } ++ }; ++ measureNowRef.current = measureNow; ++ return () => { ++ if (measureNowRef.current === measureNow) measureNowRef.current = void 0; ++ disconnectResizeObserver(); ++ }; ++ }, [callbacks, measureInLayoutEffect, measureNowRef, webExternalScroll, ...deps || []]); + return webExternalScroll ? { onLayout: onExternalLayout } : {}; + } + function toLayout(rect) { +@@ -7801,10 +7825,10 @@ function useStableRenderComponent(renderComponent, mapProps) { + [mapPropsRef, renderComponentRef] + ); + } +-var LayoutView = ({ onLayoutChange, refView, children, ...rest }) => { ++var LayoutView = ({ onLayoutChange, refView, measureRef, children, ...rest }) => { + const localRef = React3.useRef(null); + const ref = refView != null ? refView : localRef; +- useOnLayoutSync({ onLayoutChange, ref }); ++ useOnLayoutSync({ onLayoutChange, ref, measureNowRef: measureRef }); + return /* @__PURE__ */ React3__namespace.createElement("div", { ...rest, ref }, children); + }; + var subscribeScreenReader = () => () => { +@@ -7881,6 +7905,16 @@ var ListComponent = typedMemo(function ListComponent2({ + ); + const ScrollComponent = renderScrollComponent ? CustomScrollComponent : ListComponentScrollView; + const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent; ++ // T3 patch: header and footer sizes otherwise arrive from a resize observer ++ // after layout, so a scroll to the end right after a commit that changed them ++ // (a thread switch) computed its target from the previous sizes. ++ const measureHeaderRef = React3.useRef(void 0); ++ const measureFooterRef = React3.useRef(void 0); ++ ctx.state.measureHeaderAndFooter = () => { ++ var _a3, _b; ++ (_a3 = measureHeaderRef.current) == null ? void 0 : _a3.call(measureHeaderRef); ++ (_b = measureFooterRef.current) == null ? void 0 : _b.call(measureFooterRef); ++ }; + const updateFooterSize = React3.useCallback( + (size, afterSizeUpdate) => { + var _a3; +@@ -7956,7 +7990,7 @@ var ListComponent = typedMemo(function ListComponent2({ + style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style + }, + Platform.OS !== "web", +- ListHeaderComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), ++ ListHeaderComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { measureRef: measureHeaderRef, onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), + ListEmptyComponent && getComponent(ListEmptyComponent), + shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React3__namespace.createElement(AlignItemsAtEndSpacer, { horizontal }), + canRender && !ListEmptyComponent && /* @__PURE__ */ React3__namespace.createElement( +@@ -7970,7 +8004,7 @@ var ListComponent = typedMemo(function ListComponent2({ + stickyHeaderConfig + } + ), +- ListFooterComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), ++ ListFooterComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { measureRef: measureFooterRef, onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), + /* @__PURE__ */ React3__namespace.createElement(ScrollAdjust, null), + IS_DEV && ENABLE_DEVMODE + ); +@@ -8853,7 +8887,12 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) { + runScrollRequest( + pendingScroll.token, + state.pendingScrollResolve, +- () => state.props.data.length === 0 ? "unreachable" : scrollToEnd(ctx, pendingScroll.options), ++ () => { ++ var _a3; ++ if (state.props.data.length === 0) return "unreachable"; ++ (_a3 = state.measureHeaderAndFooter) == null ? void 0 : _a3.call(state); ++ return scrollToEnd(ctx, pendingScroll.options); ++ }, + () => isScrollToIndexReady(state.props.data.length - 1, true) + ); + } +diff --git a/react.mjs b/react.mjs +index 2cf1995d97cd101244b08b2b055265add859e064..af2a2817af1873ab5b5f0d8df85187521c39518a 100644 +--- a/react.mjs ++++ b/react.mjs +@@ -6355,7 +6355,8 @@ function useOnLayoutSync({ + onLayoutProp, + onLayoutChange, + webLayoutResync, +- webExternalScroll = false ++ webExternalScroll = false, ++ measureNowRef + }, deps) { + const callbacks = useLatestRef({ onLayoutChange, onLayoutProp, webLayoutResync }); + const onExternalLayout = useCallback( +@@ -6388,7 +6389,7 @@ function useOnLayoutSync({ + emit(toLayout(rect), true); + prevRect = rect; + } +- return createResizeObserver(element, (entry) => { ++ const disconnectResizeObserver = createResizeObserver(element, (entry) => { + var _a4, _b2, _c; + const target = entry.target instanceof HTMLElement ? entry.target : void 0; + const borderBoxSize = Array.isArray(entry.borderBoxSize) ? entry.borderBoxSize[0] : entry.borderBoxSize; +@@ -6406,7 +6407,30 @@ function useOnLayoutSync({ + emit(toLayout(rectObserved), false); + } + }); +- }, [callbacks, measureInLayoutEffect, webExternalScroll, ...deps || []]); ++ if (!measureNowRef) return disconnectResizeObserver; ++ // T3 patch: measure on demand through the observer's own baseline, so a ++ // forced read and a later observer delivery never disagree about the size. ++ const measureNow = () => { ++ const rect = element.getBoundingClientRect(); ++ if (rect.height === 0 && rect.width === 0) return; ++ const previousRect = prevRect != null ? prevRect : getContainerLayoutBaseline(element); ++ if (previousRect !== void 0 && rect.width === previousRect.width && rect.height === previousRect.height) return; ++ prevRect = rect; ++ emit(toLayout(rect), true); ++ // The browser only reports sizes that differ from its last delivery. Re-observe so a ++ // return to that size is still reported against the baseline this read just moved. ++ if (typeof ResizeObserver !== "undefined" && callbackMap.has(element)) { ++ const observer = getGlobalResizeObserver(); ++ observer.unobserve(element); ++ observer.observe(element, { box: "border-box" }); ++ } ++ }; ++ measureNowRef.current = measureNow; ++ return () => { ++ if (measureNowRef.current === measureNow) measureNowRef.current = void 0; ++ disconnectResizeObserver(); ++ }; ++ }, [callbacks, measureInLayoutEffect, measureNowRef, webExternalScroll, ...deps || []]); + return webExternalScroll ? { onLayout: onExternalLayout } : {}; + } + function toLayout(rect) { +@@ -7780,10 +7804,10 @@ function useStableRenderComponent(renderComponent, mapProps) { + [mapPropsRef, renderComponentRef] + ); + } +-var LayoutView = ({ onLayoutChange, refView, children, ...rest }) => { ++var LayoutView = ({ onLayoutChange, refView, measureRef, children, ...rest }) => { + const localRef = useRef(null); + const ref = refView != null ? refView : localRef; +- useOnLayoutSync({ onLayoutChange, ref }); ++ useOnLayoutSync({ onLayoutChange, ref, measureNowRef: measureRef }); + return /* @__PURE__ */ React3.createElement("div", { ...rest, ref }, children); + }; + var subscribeScreenReader = () => () => { +@@ -7860,6 +7884,16 @@ var ListComponent = typedMemo(function ListComponent2({ + ); + const ScrollComponent = renderScrollComponent ? CustomScrollComponent : ListComponentScrollView; + const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent; ++ // T3 patch: header and footer sizes otherwise arrive from a resize observer ++ // after layout, so a scroll to the end right after a commit that changed them ++ // (a thread switch) computed its target from the previous sizes. ++ const measureHeaderRef = useRef(void 0); ++ const measureFooterRef = useRef(void 0); ++ ctx.state.measureHeaderAndFooter = () => { ++ var _a3, _b; ++ (_a3 = measureHeaderRef.current) == null ? void 0 : _a3.call(measureHeaderRef); ++ (_b = measureFooterRef.current) == null ? void 0 : _b.call(measureFooterRef); ++ }; + const updateFooterSize = useCallback( + (size, afterSizeUpdate) => { + var _a3; +@@ -7935,7 +7969,7 @@ var ListComponent = typedMemo(function ListComponent2({ + style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style + }, + Platform.OS !== "web", +- ListHeaderComponent && /* @__PURE__ */ React3.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), ++ ListHeaderComponent && /* @__PURE__ */ React3.createElement(LayoutView, { measureRef: measureHeaderRef, onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), + ListEmptyComponent && getComponent(ListEmptyComponent), + shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React3.createElement(AlignItemsAtEndSpacer, { horizontal }), + canRender && !ListEmptyComponent && /* @__PURE__ */ React3.createElement( +@@ -7949,7 +7983,7 @@ var ListComponent = typedMemo(function ListComponent2({ + stickyHeaderConfig + } + ), +- ListFooterComponent && /* @__PURE__ */ React3.createElement(LayoutView, { onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), ++ ListFooterComponent && /* @__PURE__ */ React3.createElement(LayoutView, { measureRef: measureFooterRef, onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), + /* @__PURE__ */ React3.createElement(ScrollAdjust, null), + IS_DEV && ENABLE_DEVMODE + ); +@@ -8832,7 +8866,12 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) { + runScrollRequest( + pendingScroll.token, + state.pendingScrollResolve, +- () => state.props.data.length === 0 ? "unreachable" : scrollToEnd(ctx, pendingScroll.options), ++ () => { ++ var _a3; ++ if (state.props.data.length === 0) return "unreachable"; ++ (_a3 = state.measureHeaderAndFooter) == null ? void 0 : _a3.call(state); ++ return scrollToEnd(ctx, pendingScroll.options); ++ }, + () => isScrollToIndexReady(state.props.data.length - 1, true) + ); + } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 472e1d1a6c864..51da3feaaa23c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -370,7 +370,7 @@ patchedDependencies: '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 - '@legendapp/list@3.7.3': 85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4 + '@legendapp/list@3.7.3': c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d @@ -577,7 +577,7 @@ importers: version: 5.4.6 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1101,7 +1101,7 @@ importers: version: 5.3.0 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -15630,7 +15630,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': + '@legendapp/list@3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) From 14ea095b0a8e821e72b244185a7de4f49bcb6dd5 Mon Sep 17 00:00:00 2001 From: maria Date: Tue, 24 Nov 2026 00:09:14 -0300 Subject: [PATCH 270/288] feat(web): add an HTML preview width setting separate from chat width (#41663) --- apps/web/src/appInit.tsx | 3 ++ apps/web/src/components/chat/ChatCanvas.tsx | 20 +++++++- .../src/components/chat/MessagesTimeline.tsx | 3 +- .../components/chat/TimelineAssistantRows.tsx | 2 +- .../src/components/chat/canvasStore.test.ts | 1 + apps/web/src/components/chat/canvasStore.ts | 4 ++ .../components/chat/chatCanvasLayout.test.ts | 47 ++++++++++++++++++ .../src/components/chat/chatCanvasLayout.ts | 18 ++++++- .../settings/AppearanceSettingsPanel.tsx | 49 +++++++++++++++++++ .../components/settings/SettingsPanels.tsx | 4 ++ .../src/components/settings/settingsSearch.ts | 6 +++ apps/web/src/i18n/translations/de.json | 6 +++ apps/web/src/i18n/translations/en.json | 6 +++ apps/web/src/i18n/translations/es.json | 6 +++ apps/web/src/i18n/translations/fr.json | 6 +++ apps/web/src/i18n/translations/ja.json | 6 +++ apps/web/src/i18n/translations/ko.json | 6 +++ apps/web/src/i18n/translations/pt-BR.json | 6 +++ apps/web/src/i18n/translations/ru.json | 6 +++ apps/web/src/i18n/translations/sv.json | 6 +++ apps/web/src/i18n/translations/zh.json | 6 +++ apps/web/src/index.css | 17 +++++++ packages/contracts/src/settings.ts | 8 +++ 23 files changed, 237 insertions(+), 5 deletions(-) diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index cce59f08f6d12..76e7bc9e5cff1 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -90,6 +90,9 @@ function startClientAppearance(): void { if (previous?.chatWidth !== settings.chatWidth) { root.dataset.chatWidth = settings.chatWidth; } + if (previous?.htmlPreviewWidth !== settings.htmlPreviewWidth) { + root.dataset.htmlPreviewWidth = settings.htmlPreviewWidth; + } if (previous?.appearanceContrast !== settings.appearanceContrast) { applyAppearanceContrast(root, settings.appearanceContrast); } diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..c1fa62bdd5668 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -61,6 +61,7 @@ export function ChatCanvas({ }) { const elementRef = useRef(null); const widthProbeRef = useRef(null); + const htmlPreviewWidthProbeRef = useRef(null); const [timelineElement, registerTimeline] = useState(null); const measurements = useStore(store, (state) => state.measurements); const detailsCardMeasurement = useStore(store, (state) => state.detailsCardMeasurement); @@ -68,7 +69,8 @@ export function ChatCanvas({ useLayoutEffect(() => { const element = elementRef.current; const probe = widthProbeRef.current; - if (!element || !probe) return; + const htmlPreviewProbe = htmlPreviewWidthProbeRef.current; + if (!element || !probe || !htmlPreviewProbe) return; const findBar = detailsCardTopInset > 0 ? element.querySelector("[data-thread-find-bar]") : null; let disposed = false; @@ -116,6 +118,7 @@ export function ChatCanvas({ height: element.clientHeight, padding: Number.parseFloat(styles.paddingLeft), maxChatWidth: Number.parseFloat(styles.width), + maxHtmlPreviewWidth: Number.parseFloat(getComputedStyle(htmlPreviewProbe).width), minChatWidth: Number.parseFloat(styles.minWidth), composerHeight: composerOverlayElement?.getBoundingClientRect().height ?? 0, timelineGutter: timelineElement @@ -124,7 +127,7 @@ export function ChatCanvas({ }); }; measure(); - const observed: Element[] = [element, probe]; + const observed: Element[] = [element, probe, htmlPreviewProbe]; if (findBar) observed.push(findBar); if (composerOverlayElement) observed.push(composerOverlayElement); if (timelineElement) observed.push(timelineElement); @@ -158,6 +161,13 @@ export function ChatCanvas({ detailsCardPlacement: model.detailsCardPlacement, }; const { layout } = context; + const htmlPreviewLane = + layout.htmlPreview.width > layout.chat.width + ? { + "--html-preview-lane-offset": `${layout.htmlPreview.left - layout.chat.left}px`, + "--html-preview-lane-width": `${layout.htmlPreview.width}px`, + } + : null; return (
@@ -179,6 +190,11 @@ export function ChatCanvas({ aria-hidden className="pointer-events-none invisible absolute h-0 w-(--chat-content-max-width) min-w-[40rem] box-content ps-3 sm:ps-12" /> +
{children}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 575000a55e598..b809c40dfdb53 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1398,7 +1398,8 @@ const ConversationTimeline = memo(function ConversationTimeline({ >
diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index f22b1338aab91..9692bbedad62a 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -367,7 +367,7 @@ export function HtmlRenderTimelineRow({ return
{ctx.renderHtmlRender(row)}
; } return ( -
+
({ height, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 180, timelineGutter: 0, diff --git a/apps/web/src/components/chat/canvasStore.ts b/apps/web/src/components/chat/canvasStore.ts index 6b350cf95f22f..88811d1a41706 100644 --- a/apps/web/src/components/chat/canvasStore.ts +++ b/apps/web/src/components/chat/canvasStore.ts @@ -17,6 +17,7 @@ export interface ChatCanvasMeasurements { readonly height: number; readonly padding: number; readonly maxChatWidth: number; + readonly maxHtmlPreviewWidth: number; readonly minChatWidth: number; readonly composerHeight: number; readonly timelineGutter: number; @@ -36,6 +37,7 @@ const INITIAL_MEASUREMENTS: ChatCanvasMeasurements = { height: 0, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 0, timelineGutter: 0, @@ -52,6 +54,7 @@ const sameMeasurements = (a: ChatCanvasMeasurements, b: ChatCanvasMeasurements) a.height === b.height && a.padding === b.padding && a.maxChatWidth === b.maxChatWidth && + a.maxHtmlPreviewWidth === b.maxHtmlPreviewWidth && a.minChatWidth === b.minChatWidth && a.composerHeight === b.composerHeight && a.timelineGutter === b.timelineGutter && @@ -135,6 +138,7 @@ export function resolveChatCanvasModel({ preview, padding: measurements.padding, maxChatWidth: measurements.maxChatWidth, + maxHtmlPreviewWidth: measurements.maxHtmlPreviewWidth, minChatWidth: measurements.minChatWidth, composerHeight: measurements.composerHeight, detailsCard, diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.ts index 2f9e82a9e600b..53ee3f6b1ac7b 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.test.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts @@ -326,6 +326,53 @@ describe("chat canvas layout", () => { }); }); +describe("html preview lane", () => { + const wide = ( + width: number, + options: Partial[0]> = {}, + maxHtmlPreviewWidth = 1152, + ) => + resolveChatCanvasLayout({ + container: { width, height: 900 }, + preview: null, + maxChatWidth: 736, + maxHtmlPreviewWidth, + composerHeight: 180, + ...options, + }); + it("matches the chat column unless the setting allows more", () => { + const result = wide(1600, {}, 736); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("widens around a chat column that stays where it was", () => { + const result = wide(1600); + expect(result.chat).toEqual(wide(1600, {}, 736).chat); + expect(result.htmlPreview).toEqual({ left: 224, width: 1152 }); + expect(wide(1200).htmlPreview).toEqual({ left: 48, width: 1104 }); + expect(wide(1600, {}, 1600).htmlPreview).toEqual({ left: 48, width: 1504 }); + }); + it("is never narrower than the chat column", () => { + const result = wide(1600, { maxChatWidth: 1600 }, 1152); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("stops short of the details card", () => { + const detailsCard = { left: 1308, right: 1588, bottom: 400 }; + const result = wide(1600, { detailsCard }); + expect(result.chat).toEqual(wide(1600, { detailsCard }, 736).chat); + expect(result.htmlPreview).toEqual({ left: 124, width: 1152 }); + expect(wide(1600, { detailsCard }, 1600).htmlPreview).toEqual({ left: 48, width: 1228 }); + }); + it("stops short of a mini player beside the chat and matches chat under one over it", () => { + const beside = wide(1900, { preview: { ...preview, position: { x: 1500, y: 600 } } }); + expect(beside.overlapsChat).toBe(false); + expect(beside.htmlPreview.left + beside.htmlPreview.width).toBe(beside.frame!.x - 12); + expect(beside.htmlPreview.width).toBeGreaterThan(beside.chat.width); + const over = wide(1000, { preview: { ...preview, position: { x: 12, y: 700 } } }); + expect(over.overlapsChat).toBe(true); + expect(over.htmlPreview).toEqual({ left: over.chat.left, width: over.chat.width }); + }); +}); + describe("workspace card beside chat", () => { const withCard = (width: number, player: ChatCanvasPreview | null = null, maxChatWidth = 736) => resolveChatCanvasLayout({ diff --git a/apps/web/src/components/chat/chatCanvasLayout.ts b/apps/web/src/components/chat/chatCanvasLayout.ts index 77e276ee817f4..a1fc0b54b4ab1 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.ts @@ -26,6 +26,7 @@ export function resolveChatCanvasLayout({ preview, padding = 48, maxChatWidth = 768, + maxHtmlPreviewWidth = maxChatWidth, minChatWidth = 640, composerHeight = 0, detailsCard = null, @@ -35,6 +36,7 @@ export function resolveChatCanvasLayout({ preview: ChatCanvasPreview | null; padding?: number; maxChatWidth?: number; + maxHtmlPreviewWidth?: number; minChatWidth?: number; composerHeight?: number; detailsCard?: PreviewMiniPlayerObstacles["detailsCard"]; @@ -176,5 +178,19 @@ export function resolveChatCanvasLayout({ frame.x + frame.width > detailsCard.left && frame.y < detailsCard.bottom, ); - return { chat, frame, overlapsChat, overlapsDetailsCard }; + // A wider HTML preview stays centered on the chat column while that fits, and + // clear of the details card and a mini player the chat column sits beside. + const laneEnd = frame ? Math.min(laneRight, frame.x - GAP) : laneRight; + const htmlPreviewWidth = overlapsChat ? 0 : Math.min(maxHtmlPreviewWidth, laneEnd - padding); + const htmlPreview = + htmlPreviewWidth > chat.width + ? { + left: Math.max( + padding, + Math.min(chat.left + (chat.width - htmlPreviewWidth) / 2, laneEnd - htmlPreviewWidth), + ), + width: htmlPreviewWidth, + } + : { left: chat.left, width: chat.width }; + return { chat, htmlPreview, frame, overlapsChat, overlapsDetailsCard }; } diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 72fda9150a7b2..1bb96d39c9794 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -5,6 +5,7 @@ import { DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE, DEFAULT_UNIFIED_SETTINGS, type ChatWidth, + type HtmlPreviewWidth, type EffortDisplay, type EnvironmentIdentificationMode, MAX_APPEARANCE_CONTRAST, @@ -80,6 +81,12 @@ const CHAT_WIDTH_LABELS: Record = { full: msg("Full", { $context: "chat width" }), }; +const HTML_PREVIEW_WIDTH_LABELS: Record = { + chat: msg("Match chat", { $context: "HTML preview width" }), + wide: CHAT_WIDTH_LABELS.wide, + full: CHAT_WIDTH_LABELS.full, +}; + const EFFORT_DISPLAY_LABELS: Record = { label: msg("Word", { $context: "show effort as a word" }), bars: msg("Bars", { $context: "show effort as bars" }), @@ -294,6 +301,48 @@ export function AppearanceSettingsPanel() {
} /> + + updateSettings({ htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth }) + } + /> + ) : null + } + control={ +
+ +
+ } + /> void) { ? [gt("Diff colors")] : []), ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? [gt("Chat width")] : []), + ...(settings.htmlPreviewWidth !== DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth + ? [gt("HTML preview width")] + : []), ...(settings.effortDisplay !== DEFAULT_UNIFIED_SETTINGS.effortDisplay ? [gt("Effort display")] : []), @@ -709,6 +712,7 @@ export function useSettingsRestore(onRestored?: () => void) { appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, language: DEFAULT_UNIFIED_SETTINGS.language, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..fa933349eb400 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -380,6 +380,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/appearance", searchTerms: [msg("wide full width column layout messages composer monitor")], }, + { + id: "html-preview-width", + title: msg("HTML preview width"), + to: "/settings/appearance", + searchTerms: [msg("wide full width inline page render chart dashboard artifact centered")], + }, { id: "thread-details-items", title: msg("Thread details"), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index bafbe7d7cb731..493f5021da2b1 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -7560,6 +7560,11 @@ "03338c6aec8edacd": "Lege fest, wie breit Nachrichten und das Eingabefeld auf großen Bildschirmen werden können.", "92785adb251da88c": "Chatbreite auf Standard zurücksetzen", "4d457bcce0c0e272": "Chatbreite", + "7d7f65967cc821e3": "Breite der HTML-Vorschau", + "70ce0af7f78d5957": "Lässt HTML-Vorschauen in einem Chat breiter werden als die Nachrichten, die zentriert bleiben.", + "f2b119bf02ae2558": "Breite der HTML-Vorschau auf Standard zurücksetzen", + "6287212fed0deec6": "Wie Chat", + "dc8e85ea0364649c": "Wie Chat (Standard)", "81f3a196537bbee0": "Komfortabel (Standard)", "e79e5388f669495f": "Den Denkaufwand im Eingabefeld als Namen, etwa Hoch, oder als Balken anzeigen.", "7f0365c7e4e8bcbf": "Anzeige des Aufwands auf Standard zurücksetzen", @@ -11828,6 +11833,7 @@ "9cf8308531b4ff31": "transparent transparenz deckend menüs dialoge eingabefeld", "d8d6cfd630cff22d": "rot grün blau orange hinzufügungen löschungen änderungen anzahl palette farbenblind", "717e49895cfee1c7": "breit volle breite spalte layout nachrichten eingabefeld monitor", + "9d5c7430a7ff76cf": "breit volle breite inline seite rendern diagramm dashboard artefakt zentriert", "88365077fd80787b": "anpassen anzeigen ausblenden panel karte umgebung editor skripte branch pull request git änderungen server automatisierungen herkunft nutzung limits 5 stunden wöchentlich kontingent tokens kontextfenster", "d561f74efa5f3920": "reasoning aufwand denken balken grafik wort bezeichnung stufe eingabefeld", "6113c17109ee0d57": "latex tex katex gleichungen formeln markdown", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index cde4bbb9458fa..15101ae706800 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -7568,6 +7568,11 @@ "03338c6aec8edacd": "Set how wide messages and the composer can grow on large screens.", "92785adb251da88c": "Reset chat width to default", "4d457bcce0c0e272": "Chat width", + "7d7f65967cc821e3": "HTML preview width", + "70ce0af7f78d5957": "Let HTML previews in a chat grow wider than its messages, which stay centered.", + "f2b119bf02ae2558": "Reset HTML preview width to default", + "6287212fed0deec6": "Match chat", + "dc8e85ea0364649c": "Match chat (default)", "81f3a196537bbee0": "Comfortable (default)", "e79e5388f669495f": "Show reasoning effort in the composer as its name, such as High, or as bars.", "7f0365c7e4e8bcbf": "Reset effort display to default", @@ -11836,6 +11841,7 @@ "9cf8308531b4ff31": "transparent transparency solid menus dialogs composer", "d8d6cfd630cff22d": "red green blue orange additions deletions changes counts palette colorblind", "717e49895cfee1c7": "wide full width column layout messages composer monitor", + "9d5c7430a7ff76cf": "wide full width inline page render chart dashboard artifact centered", "88365077fd80787b": "customize show hide panel card environment editor scripts branch pull request git changes servers automations lineage usage limits 5 hour weekly quota tokens context window", "d561f74efa5f3920": "reasoning effort thinking bars graph word label level composer", "6113c17109ee0d57": "latex tex katex equations formulas markdown", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ee4496f0bfbc5..41ea55b0cce5e 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Define cuánto pueden crecer los mensajes y el cuadro de mensaje en pantallas grandes.", "92785adb251da88c": "Restablecer el ancho del chat al valor predeterminado", "4d457bcce0c0e272": "Ancho del chat", + "7d7f65967cc821e3": "Ancho de la vista previa HTML", + "70ce0af7f78d5957": "Permite que las vistas previas HTML de un chat sean más anchas que sus mensajes, que siguen centrados.", + "f2b119bf02ae2558": "Restablecer el ancho de la vista previa HTML al valor predeterminado", + "6287212fed0deec6": "Igual que el chat", + "dc8e85ea0364649c": "Igual que el chat (predeterminado)", "81f3a196537bbee0": "Cómodo (predeterminado)", "e79e5388f669495f": "Muestra el esfuerzo de razonamiento en el cuadro de mensaje por su nombre, como Alto, o con barras.", "7f0365c7e4e8bcbf": "Restablecer la visualización del esfuerzo al valor predeterminado", @@ -11821,6 +11826,7 @@ "9cf8308531b4ff31": "transparente transparencia sólido menús diálogos cuadro mensaje compositor", "d8d6cfd630cff22d": "rojo verde azul naranja adiciones eliminaciones cambios recuentos paleta daltonismo", "717e49895cfee1c7": "ancho ancho completo columna diseño mensajes cuadro mensaje compositor monitor", + "9d5c7430a7ff76cf": "ancho ancho completo en línea página renderizar gráfico panel artefacto centrado", "88365077fd80787b": "personalizar mostrar ocultar panel tarjeta entorno editor scripts rama pull request git cambios servidores automatizaciones linaje uso límites 5 horas semanal cuota tokens ventana de contexto", "d561f74efa5f3920": "esfuerzo de razonamiento pensamiento barras gráfico palabra etiqueta nivel cuadro mensaje compositor", "6113c17109ee0d57": "latex tex katex ecuaciones fórmulas markdown", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index dfb02854b6c38..3d27667384fdd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -7562,6 +7562,11 @@ "03338c6aec8edacd": "Définissez la largeur maximale des messages et de la zone de saisie sur les grands écrans.", "92785adb251da88c": "Réinitialiser la largeur de la discussion à la valeur par défaut", "4d457bcce0c0e272": "Largeur de la discussion", + "7d7f65967cc821e3": "Largeur des aperçus HTML", + "70ce0af7f78d5957": "Permet aux aperçus HTML d’une discussion d’être plus larges que ses messages, qui restent centrés.", + "f2b119bf02ae2558": "Réinitialiser la largeur des aperçus HTML à la valeur par défaut", + "6287212fed0deec6": "Comme la discussion", + "dc8e85ea0364649c": "Comme la discussion (par défaut)", "81f3a196537bbee0": "Confortable (par défaut)", "e79e5388f669495f": "Afficher l’effort de raisonnement dans la zone de saisie par son nom, comme Élevé, ou sous forme de barres.", "7f0365c7e4e8bcbf": "Réinitialiser l’affichage de l’effort à la valeur par défaut", @@ -11826,6 +11831,7 @@ "9cf8308531b4ff31": "transparent transparence opaque menus boîtes de dialogue zone de saisie", "d8d6cfd630cff22d": "rouge vert bleu orange ajouts suppressions modifications compteurs palette daltonien", "717e49895cfee1c7": "large pleine largeur colonne mise en page messages zone de saisie écran", + "9d5c7430a7ff76cf": "large pleine largeur intégré page rendu graphique tableau de bord artefact centré", "88365077fd80787b": "personnaliser afficher masquer panneau carte environnement éditeur scripts branche pull request modifications git serveurs automatisations lignée utilisation limites 5 heures hebdomadaire quota jetons fenêtre de contexte", "d561f74efa5f3920": "effort de raisonnement réflexion barres graphique mot libellé niveau zone de saisie", "6113c17109ee0d57": "latex tex katex équations formules markdown", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index bba2c66a1adf0..27a9f41f8b7b9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -7527,6 +7527,11 @@ "03338c6aec8edacd": "大きな画面でメッセージと入力欄を広げられる幅を設定します。", "92785adb251da88c": "チャットの幅をデフォルトにリセット", "4d457bcce0c0e272": "チャットの幅", + "7d7f65967cc821e3": "HTML プレビューの幅", + "70ce0af7f78d5957": "チャット内の HTML プレビューをメッセージより広く表示します。メッセージは中央のままです。", + "f2b119bf02ae2558": "HTML プレビューの幅をデフォルトにリセット", + "6287212fed0deec6": "チャットに合わせる", + "dc8e85ea0364649c": "チャットに合わせる (デフォルト)", "81f3a196537bbee0": "標準 (デフォルト)", "e79e5388f669495f": "入力欄での推論レベルの表示を、名前 (High など) またはバーから選択します。", "7f0365c7e4e8bcbf": "推論レベルの表示をデフォルトにリセット", @@ -11777,6 +11782,7 @@ "9cf8308531b4ff31": "透明 透過 不透明 メニュー ダイアログ 入力欄 transparency", "d8d6cfd630cff22d": "赤 緑 青 オレンジ 追加 削除 変更 件数 パレット 色覚 colorblind", "717e49895cfee1c7": "幅 全幅 列 レイアウト メッセージ 入力欄 モニター wide width", + "9d5c7430a7ff76cf": "幅 全幅 インライン ページ レンダリング グラフ ダッシュボード アーティファクト 中央 wide width", "88365077fd80787b": "カスタマイズ 表示 非表示 パネル カード 環境 エディター スクリプト ブランチ プルリクエスト Git 変更 サーバー オートメーション 系譜 使用量 上限 5 時間 週間 クォータ トークン コンテキストウィンドウ panel card", "d561f74efa5f3920": "推論レベル 思考 バー グラフ 単語 ラベル レベル 入力欄 reasoning effort", "6113c17109ee0d57": "LaTeX TeX KaTeX 数式 方程式 Markdown latex math", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 988724e7b1c8f..deb87364861ed 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -7528,6 +7528,11 @@ "03338c6aec8edacd": "큰 화면에서 메시지와 입력창이 넓어질 수 있는 폭을 설정합니다.", "92785adb251da88c": "채팅 너비 기본값으로 재설정", "4d457bcce0c0e272": "채팅 너비", + "7d7f65967cc821e3": "HTML 미리 보기 너비", + "70ce0af7f78d5957": "채팅의 HTML 미리 보기가 메시지보다 넓어질 수 있게 합니다. 메시지는 가운데에 유지됩니다.", + "f2b119bf02ae2558": "HTML 미리 보기 너비 기본값으로 재설정", + "6287212fed0deec6": "채팅에 맞춤", + "dc8e85ea0364649c": "채팅에 맞춤(기본값)", "81f3a196537bbee0": "보통(기본값)", "e79e5388f669495f": "입력창에서 추론 수준을 High 같은 이름 또는 막대로 표시합니다.", "7f0365c7e4e8bcbf": "추론 수준 표시 기본값으로 재설정", @@ -11773,6 +11778,7 @@ "9cf8308531b4ff31": "투명 투명도 불투명 메뉴 대화 상자 입력창", "d8d6cfd630cff22d": "빨간색 녹색 파란색 주황색 추가 삭제 변경 개수 팔레트 색맹", "717e49895cfee1c7": "넓게 전체 너비 열 레이아웃 메시지 입력창 모니터", + "9d5c7430a7ff76cf": "넓게 전체 너비 인라인 페이지 렌더링 차트 대시보드 아티팩트 가운데", "88365077fd80787b": "사용자 지정 표시 숨기기 패널 카드 환경 편집기 스크립트 브랜치 풀 리퀘스트 git 변경 사항 서버 자동화 계보 사용량 한도 5시간 주간 할당량 토큰 컨텍스트 창", "d561f74efa5f3920": "추론 수준 생각 막대 그래프 단어 레이블 수준 입력창", "6113c17109ee0d57": "latex tex katex 수식 공식 마크다운", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 286cde4c55168..9b3534dd3fd7d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Define até que largura as mensagens e o editor de mensagens podem crescer em telas grandes.", "92785adb251da88c": "Redefinir a largura do chat para o padrão", "4d457bcce0c0e272": "Largura do chat", + "7d7f65967cc821e3": "Largura da pré-visualização HTML", + "70ce0af7f78d5957": "Permite que as pré-visualizações HTML de um chat fiquem mais largas que as mensagens, que continuam centralizadas.", + "f2b119bf02ae2558": "Redefinir a largura da pré-visualização HTML para o padrão", + "6287212fed0deec6": "Igual ao chat", + "dc8e85ea0364649c": "Igual ao chat (padrão)", "81f3a196537bbee0": "Confortável (padrão)", "e79e5388f669495f": "Mostra o esforço de raciocínio no editor de mensagens pelo nome, como Alto, ou como barras.", "7f0365c7e4e8bcbf": "Redefinir a exibição do esforço para o padrão", @@ -11826,6 +11831,7 @@ "9cf8308531b4ff31": "transparente transparência sólido menus caixas de diálogo editor de mensagens", "d8d6cfd630cff22d": "vermelho verde azul laranja adições exclusões alterações contagens paleta daltonismo", "717e49895cfee1c7": "largo largura total coluna layout mensagens editor de mensagens monitor", + "9d5c7430a7ff76cf": "largo largura total em linha página renderizar gráfico painel artefato centralizado", "88365077fd80787b": "personalizar mostrar ocultar painel cartão ambiente editor scripts branch pull request git alterações servidores automações linhagem uso limites 5 horas semanal cota tokens janela de contexto", "d561f74efa5f3920": "esforço de raciocínio pensamento barras gráfico palavra rótulo nível editor de mensagens", "6113c17109ee0d57": "latex tex katex equações fórmulas markdown", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4fbe93bc7f506..bfc04739cb8ad 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Задайте, насколько широкими могут быть сообщения и поле ввода на больших экранах.", "92785adb251da88c": "Сбросить ширину чата к значению по умолчанию", "4d457bcce0c0e272": "Ширина чата", + "7d7f65967cc821e3": "Ширина предпросмотра HTML", + "70ce0af7f78d5957": "Позволяет предпросмотрам HTML в чате быть шире сообщений, которые остаются по центру.", + "f2b119bf02ae2558": "Сбросить ширину предпросмотра HTML к значению по умолчанию", + "6287212fed0deec6": "Как у чата", + "dc8e85ea0364649c": "Как у чата (по умолчанию)", "81f3a196537bbee0": "Удобная (по умолчанию)", "e79e5388f669495f": "Показывать усилие рассуждения в поле ввода названием, например «Высокое», или полосками.", "7f0365c7e4e8bcbf": "Сбросить отображение усилия к значению по умолчанию", @@ -11827,6 +11832,7 @@ "9cf8308531b4ff31": "прозрачный прозрачность сплошной меню диалоги поле ввода", "d8d6cfd630cff22d": "красный зелёный синий оранжевый добавления удаления изменения счётчики палитра дальтонизм", "717e49895cfee1c7": "широкий полная ширина колонка раскладка сообщения поле ввода монитор", + "9d5c7430a7ff76cf": "широкий полная ширина встроенная страница рендер график дашборд артефакт по центру", "88365077fd80787b": "настроить показать скрыть панель карточка окружение редактор скрипты ветка пул-реквест git изменения серверы автоматизации происхождение использование лимиты 5 часов неделя квота токены контекстное окно", "d561f74efa5f3920": "усилие рассуждений размышление полосы график слово метка уровень поле ввода", "6113c17109ee0d57": "latex tex katex уравнения формулы markdown", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6759119ee8a98..4de2ac04990a3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -7567,6 +7567,11 @@ "03338c6aec8edacd": "Ange hur breda meddelanden och inmatningsfältet kan bli på stora skärmar.", "92785adb251da88c": "Återställ chattbredd till standard", "4d457bcce0c0e272": "Chattbredd", + "7d7f65967cc821e3": "Bredd för HTML-förhandsvisning", + "70ce0af7f78d5957": "Låter HTML-förhandsvisningar i en chatt bli bredare än meddelandena, som förblir centrerade.", + "f2b119bf02ae2558": "Återställ bredd för HTML-förhandsvisning till standard", + "6287212fed0deec6": "Samma som chatten", + "dc8e85ea0364649c": "Samma som chatten (standard)", "81f3a196537bbee0": "Bekväm (standard)", "e79e5388f669495f": "Visa resonemangsnivån i inmatningsfältet som sitt namn, till exempel Hög, eller som staplar.", "7f0365c7e4e8bcbf": "Återställ visning av ansträngning till standard", @@ -11834,6 +11839,7 @@ "9cf8308531b4ff31": "transparent genomskinlighet solid menyer dialoger inmatningsfält", "d8d6cfd630cff22d": "röd grön blå orange tillägg borttagningar ändringar antal palett färgblind", "717e49895cfee1c7": "bred full bredd kolumn layout meddelanden inmatningsfält skärm", + "9d5c7430a7ff76cf": "bred full bredd inbäddad sida rendera diagram instrumentpanel artefakt centrerad", "88365077fd80787b": "anpassa visa dölj panel kort miljö redigerare skript gren pull request git ändringar servrar automatiseringar härkomst användning gränser 5 timmar vecka kvot token kontextfönster", "d561f74efa5f3920": "resonemang ansträngning tänkande staplar diagram ord etikett nivå inmatningsfält", "6113c17109ee0d57": "latex tex katex ekvationer formler markdown", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 3e4d7229881f3..7689205ddb802 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -7576,6 +7576,11 @@ "03338c6aec8edacd": "设置大屏幕上消息和输入框的最大宽度。", "92785adb251da88c": "重置聊天宽度为默认值", "4d457bcce0c0e272": "聊天宽度", + "7d7f65967cc821e3": "HTML 预览宽度", + "70ce0af7f78d5957": "让聊天中的 HTML 预览比消息更宽,消息仍保持居中。", + "f2b119bf02ae2558": "重置 HTML 预览宽度为默认值", + "6287212fed0deec6": "与聊天一致", + "dc8e85ea0364649c": "与聊天一致(默认)", "81f3a196537bbee0": "适中(默认)", "e79e5388f669495f": "在输入框中用名称(如 High)或条形显示推理强度。", "7f0365c7e4e8bcbf": "重置推理强度显示为默认值", @@ -11851,6 +11856,7 @@ "9cf8308531b4ff31": "透明 透明度 实色 菜单 对话框 输入框", "d8d6cfd630cff22d": "红 绿 蓝 橙 新增 删除 更改 计数 调色板 色盲", "717e49895cfee1c7": "宽 全宽 列 布局 消息 输入框 显示器", + "9d5c7430a7ff76cf": "宽 全宽 内嵌 页面 渲染 图表 仪表板 工件 居中", "88365077fd80787b": "自定义 显示 隐藏 面板 卡片 环境 编辑器 脚本 分支 PR git 更改 服务器 自动化 谱系 用量 限制 5 小时 每周 配额 token 上下文窗口", "d561f74efa5f3920": "推理强度 思考 条形 图表 文字 标签 级别 输入框", "6113c17109ee0d57": "latex tex katex 方程 公式 markdown", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 272c0269d9e28..4441b65f8143f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -129,6 +129,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --workspace-titlebar-control-gap: 0.75rem; --workspace-titlebar-scroll-fade-height: 1.5rem; --chat-content-max-width: 46rem; + --html-preview-max-width: var(--chat-content-max-width); --thread-details-panel-width: 17.5rem; /* The prompt on phones: iOS zooms into any input under 16px on focus. */ --font-size-prompt-touch: max(var(--font-size-prompt, 1rem), 16px); @@ -982,6 +983,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil max-width: var(--chat-content-max-width); } + /* ChatCanvas sets these only while HTML previews run wider than the chat column. */ + .html-preview-lane { + width: var(--html-preview-lane-width, auto); + margin-inline-start: var(--html-preview-lane-offset, 0px); + } + .messages-timeline-row-frame { padding-inline: 0; } @@ -2366,6 +2373,16 @@ code { --chat-content-max-width: 100%; } +/* HTML preview width setting. ChatCanvas measures this and never lays a + preview out narrower than the chat column. */ +:root[data-html-preview-width="wide"] { + --html-preview-max-width: 72rem; +} + +:root[data-html-preview-width="full"] { + --html-preview-max-width: 100%; +} + :root[data-diff-color-scheme="blue-orange"] { --diff-addition: light-dark(var(--color-blue-600), var(--color-blue-400)); --diff-deletion: light-dark(var(--color-orange-600), var(--color-orange-400)); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e7887f88f0369..5b6ce48c88833 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -352,6 +352,10 @@ export const DiffColorScheme = Schema.Literals(["red-green", "blue-orange"]); export const ChatWidth = Schema.Literals(["comfortable", "wide", "full"]); export type ChatWidth = typeof ChatWidth.Type; +/** How wide inline HTML previews grow: "chat" keeps them in the chat column. */ +export const HtmlPreviewWidth = Schema.Literals(["chat", "wide", "full"]); +export type HtmlPreviewWidth = typeof HtmlPreviewWidth.Type; + /** How the composer shows reasoning effort: the level's name, or rising bars. */ export const EffortDisplay = Schema.Literals(["label", "bars"]); export type EffortDisplay = typeof EffortDisplay.Type; @@ -418,6 +422,9 @@ export const ClientSettingsSchema = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed("red-green" as const)), ), chatWidth: ChatWidth.pipe(Schema.withDecodingDefault(Effect.succeed("comfortable" as const))), + htmlPreviewWidth: HtmlPreviewWidth.pipe( + Schema.withDecodingDefault(Effect.succeed("chat" as const)), + ), effortDisplay: EffortDisplay.pipe(Schema.withDecodingDefault(Effect.succeed("label" as const))), loadBalancingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), loadBalancingWeights: LoadBalancingWeights.pipe(Schema.withDecodingDefault(Effect.succeed({}))), @@ -2075,6 +2082,7 @@ export const ClientSettingsPatch = Schema.Struct({ inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean), diffColorScheme: Schema.optionalKey(DiffColorScheme), chatWidth: Schema.optionalKey(ChatWidth), + htmlPreviewWidth: Schema.optionalKey(HtmlPreviewWidth), effortDisplay: Schema.optionalKey(EffortDisplay), loadBalancingEnabled: Schema.optionalKey(Schema.Boolean), loadBalancingWeights: Schema.optionalKey(LoadBalancingWeights), From 6f8282c2c8a463487f883b7154a6066a883b8a7a Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:10:10 -0600 Subject: [PATCH 271/288] fix(web): an IME Escape no longer blurs the file editor (#41837) Co-authored-by: Julius Marminge --- .../fileEditorDismissal.browser.test.tsx | 57 +++++++++++++++++++ .../components/files/fileEditorDismissal.ts | 3 +- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx index 38c8e53156ecc..730ebb2d7cc5c 100644 --- a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx +++ b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx @@ -64,6 +64,63 @@ describe("installFileEditorDismissal", () => { expect(window.getSelection()?.toString()).toBe("Assistant reply"); }); + it("leaves the editor focused when Escape belongs to an IME composition", async () => { + let editor: Editor<"file" | "file-diff", undefined, undefined> | undefined; + const createEditor: EditorFactory = (...args) => + (editor = new Editor(...args)); + await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] }); + await using screen = await render( +
+ + + +
, + ); + const shadowRoot = screen.container.querySelector("diffs-container")?.shadowRoot; + const content = shadowRoot?.querySelector("[data-content]"); + expect(content).toBeTruthy(); + content!.focus(); + const range = { start: { line: 0, character: 6 }, end: { line: 0, character: 12 } }; + editor!.setSelections([{ ...range, direction: "forward" }]); + const onDismiss = vi.fn(); + const onAppKeyDown = vi.fn(); + window.addEventListener("keydown", onAppKeyDown); + using _appKeyDown = { + [Symbol.dispose]: () => window.removeEventListener("keydown", onAppKeyDown), + }; + using _dismissal = { + [Symbol.dispose]: installFileEditorDismissal({ + root: screen.getByTestId("file-surface").element() as HTMLElement, + editor: editor!, + isBlocked: () => false, + onDismiss, + }), + }; + const pressEscape = (init: KeyboardEventInit) => { + const event = new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + composed: true, + cancelable: true, + ...init, + }); + content!.dispatchEvent(event); + return event; + }; + + expect(pressEscape({ isComposing: true, keyCode: 27 }).defaultPrevented).toBe(false); + expect(pressEscape({ keyCode: 229 }).defaultPrevented).toBe(false); + + expect(onDismiss).not.toHaveBeenCalled(); + expect(onAppKeyDown).not.toHaveBeenCalled(); + expect(editor!.getViewState().selections).toMatchObject([range]); + expect(shadowRoot!.activeElement).toBe(content); + + expect(pressEscape({ keyCode: 27 }).defaultPrevented).toBe(true); + expect(onDismiss).toHaveBeenCalledOnce(); + expect(shadowRoot!.activeElement).toBeNull(); + }); + it("lets clicks beside the open search panel reach the file's code", async () => { let editor: Editor<"file" | "file-diff", undefined, undefined> | undefined; const createEditor: EditorFactory = (...args) => diff --git a/apps/web/src/components/files/fileEditorDismissal.ts b/apps/web/src/components/files/fileEditorDismissal.ts index 1291cfe9aeea0..9441893d15e91 100644 --- a/apps/web/src/components/files/fileEditorDismissal.ts +++ b/apps/web/src/components/files/fileEditorDismissal.ts @@ -39,8 +39,9 @@ export function installFileEditorDismissal({ }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || isBlocked() || !isFileEditorFocused(root)) return; - event.preventDefault(); event.stopImmediatePropagation(); + if (event.isComposing || event.keyCode === 229) return; + event.preventDefault(); dismissFileEditorInteraction({ root, editor, onDismiss }); }; From 82af3cf2c364f549bfe1f11c756796c60dd83d80 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:15:03 -0800 Subject: [PATCH 272/288] fix(server): a thread resume replays a deleted thread from its deletion (#41874) Co-authored-by: Claude Fable 5.2 --- apps/server/src/ws.test.ts | 55 ++++++++++++++++++++++++++++++++++++++ apps/server/src/ws.ts | 6 ++++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index d12488a1b0db7..2838be2a228a3 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2168,6 +2168,61 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("thread resume replays a deleted thread's deletion and nothing recorded before it", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const now = "2026-10-13T00:00:00.000Z"; + const threadId = ThreadId.make("thread:deleted-resume"); + const insert = (version: number, type: string, payload: object) => sql` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + ${`deleted-resume:${version}`}, 'thread', ${threadId}, ${version}, ${type}, + ${now}, 'server', ${JSON.stringify(payload)}, '{}', 2 + ) + `; + const detached = { providerSessionId: "session:deleted-resume", detachedAt: now }; + yield* insert(0, "provider-session.detached", detached); + yield* insert(1, "provider-session.detached", detached); + yield* insert(2, "thread.deleted", { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: "project:deleted-resume", + title: "Deleted", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "default" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: now, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }); + + const items = yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: 0 }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + assert.deepEqual( + Array.from(items).map((item) => item.kind === "event" && item.event.type), + ["thread.deleted"], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + // A prune pass can delete replayed rows after the boundary check; the read must not be trusted. it.effect.each(["thread", "shell"] as const)( "%s resume loads a snapshot when pruning advances during the replay read", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index f0f746eb8041f..583b1919aa5e0 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1132,7 +1132,11 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ) { return yield* snapshotThenLive(); } - const replay = coalesceLiveUpdatedEvents(replayed); + // A deleted thread reads as gone: its replay starts at the deletion. + const deletion = replayed.findLastIndex((item) => item.event.type === "thread.deleted"); + const replay = coalesceLiveUpdatedEvents( + deletion === -1 ? replayed : replayed.slice(deletion), + ); const plan = decideThreadResume({ afterSequence: input.afterSequence, highWater, From 036751b6f5556fcf221ef9483bec6ba358af22c8 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:15:33 -0600 Subject: [PATCH 273/288] fix(web): Esc in project icon search clears it without closing the dialog (#41856) Co-authored-by: Julius Marminge --- .../ProjectIconPickerDialog.browser.test.tsx | 50 +++++++++++++++++++ .../settings/ProjectIconPickerDialog.tsx | 15 +++++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx new file mode 100644 index 0000000000000..a45214f545ca6 --- /dev/null +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx @@ -0,0 +1,50 @@ +import { page, userEvent } from "vite-plus/test/browser"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog"; + +import "~/index.css"; + +it("Escape in the icon search clears it without closing the dialog", async () => { + const onOpenChange = vi.fn(); + await using _screen = await render( + {}} + />, + ); + const search = page.getByRole("searchbox", { name: "Search Lucide icons" }); + await expect.element(search).toHaveAttribute("type", "text"); + await userEvent.fill(search, "rocket"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(search).toHaveValue("rocket"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close the dialog. + await act(() => { + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + expect(onOpenChange).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onOpenChange.mock.calls.map(([open]) => open)).toEqual([false]); +}); diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx index 44942c2ce0c47..258f975a31905 100644 --- a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx @@ -171,12 +171,25 @@ function ProjectIconPickerBody({ {mode === "lucide" ? ( <> + {/* Native search inputs clear on Escape even during IME composition. */} setQuery(event.currentTarget.value)} + onKeyDown={(event) => { + if ( + event.key !== "Escape" || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) + return; + if (!query && !event.repeat) return; + event.stopPropagation(); + setQuery(""); + }} />
From 637cd28599b0364630f10745321f7ce78d03bc28 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:16:10 -0800 Subject: [PATCH 274/288] fix(client-runtime): Remove is no longer offered on a route the environment cannot lose (#41845) --- .../settings/EnvironmentRoutesSection.tsx | 6 ++---- .../EnvironmentRoutesList.browser.test.tsx | 20 +++++++++++++++++++ .../settings/EnvironmentRoutesList.tsx | 3 ++- .../client-runtime/src/connection/routes.ts | 14 +++++++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx index 8e5cf5f500856..86641489f35cd 100644 --- a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx +++ b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx @@ -3,6 +3,7 @@ import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useAtomValue } from "@effect/atom-react"; import { + canRemoveRoute, type ConnectionRoute, type ConnectionRouteKind, connectionRouteAddress, @@ -225,10 +226,7 @@ export function EnvironmentRoutesSection({ if (!cancelled) move(index, dropIndex(index, translation)); }} onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)} - // A learned route would be learned again, so it is only reordered. - onRemove={ - routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined - } + onRemove={canRemoveRoute(routes, route) ? () => confirmRemove(route) : undefined} /> ); })} diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx index 39b9cac03ede1..17689eb8581fb 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx @@ -3,6 +3,7 @@ import { BearerConnectionTarget, type ConnectionCatalogEntry, type ConnectionRoute, + mergeLearnedRoutes, } from "@t3tools/client-runtime/connection"; import { EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; @@ -91,3 +92,22 @@ it("shows a route added after a reorder was saved, once another route is removed .element(screen.getByRole("button", { name: "Remove desk.example.com route" })) .toBeVisible(); }); + +it("does not offer to remove the only route a found-automatically route depends on", async () => { + const paired: ConnectionCatalogEntry = { + target: LAN.target, + profile: LAN.profile, + alternateRoutes: [], + enabled: true, + }; + const learned = mergeLearnedRoutes({ + entry: paired, + activeRoute: LAN, + reported: [{ httpBaseUrl: "https://desk.tail1234.ts.net/", kind: "tailnet" }], + allowInsecure: true, + })!; + await using screen = await render(routesList(learned)); + await expect.element(screen.getByText(/found automatically/)).toBeVisible(); + + expect(screen.getByRole("button", { name: "Remove LAN route" }).elements()).toHaveLength(0); +}); diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.tsx index f559f85ce80f7..f4b9a1593b9d8 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.tsx @@ -17,6 +17,7 @@ import { } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { + canRemoveRoute, type ConnectionRoute, connectionRouteAddress, connectionRouteId, @@ -121,7 +122,7 @@ export function EnvironmentRoutesList({ position={index + 1} inUse={connectionRouteId(route.target) === activeRouteId} refused={environment.refusedRouteIds.includes(connectionRouteId(route.target))} - removable={routes.length > 1 && !isLearned(route)} + removable={canRemoveRoute(routes, route)} onRemove={() => void confirmRemove(route)} /> ))} diff --git a/packages/client-runtime/src/connection/routes.ts b/packages/client-runtime/src/connection/routes.ts index 1ae8df56fc109..0a2c38445b1b6 100644 --- a/packages/client-runtime/src/connection/routes.ts +++ b/packages/client-runtime/src/connection/routes.ts @@ -477,6 +477,20 @@ export function routesAfterRemoving( }); } +/** + * A route is offered for removal only when removing it leaves a route behind. + * A learned route would be learned again, and the last route a learned route + * borrows from would take the whole environment with it. + */ +export function canRemoveRoute( + routes: ReadonlyArray, + route: ConnectionRoute, +): boolean { + return ( + !isLearned(route) && routesAfterRemoving(routes, connectionRouteId(route.target)).length > 0 + ); +} + /** * A dragged route order shows until the saved routes catch up with it. It is * stale, and returns null, once the saved order matches it or the saved routes From 7913360b2e61bb04086229c4ec283e512c8d7a9e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:17:25 -0800 Subject: [PATCH 275/288] fix(server): saving a voice key reference needs provider management (#41876) Co-authored-by: Claude Fable 5.2 --- .../features/settings/CloudVoiceSection.tsx | 3 +++ apps/server/src/speech/http.test.ts | 20 ++++++++++++++++--- apps/server/src/speech/http.ts | 10 ++++++++++ .../settings/CloudVoiceConfiguration.tsx | 3 +++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index 3e782d2457fa3..1e32e2585e072 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -8,6 +8,7 @@ import { secretRequestReference, } from "@t3tools/client-runtime/secret-request"; import { + AuthProvidersManageScope, AuthSettingsWriteScope, CLOUD_SPEECH_LABELS, CLOUD_SPEECH_PROVIDER_NAMES, @@ -188,6 +189,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const keys = useAtomValue(cloudVoiceKeysAtom(id)); const reload = useAtomRefresh(cloudVoiceKeysAtom(id)); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [editing, setEditing] = useState<{ provider: CloudSpeechProvider; enable: boolean; @@ -199,6 +201,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 8bbf2d81bc065..c6d5405cfa82c 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -7,6 +7,7 @@ import { expect, vi } from "vite-plus/test"; import { AuthSessionId, AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, type AuthEnvironmentScope, CloudSpeechError, @@ -37,17 +38,18 @@ import { speechHttpApiLayer } from "./http.ts"; const decodeSessionId = Schema.decodeUnknownSync(AuthSessionId); -const principal = (...scopes: AuthEnvironmentScope[]) => +const principalWith = (scopes: ReadonlySet) => Layer.succeed(EnvironmentAuthenticatedAuth, (effect) => effect.pipe( Effect.provideService(EnvironmentAuthenticatedPrincipal, { sessionId: decodeSessionId("voice-test"), subject: "test", method: "bearer-access-token", - scopes: new Set(scopes), + scopes, }), ), ); +const principal = (...scopes: AuthEnvironmentScope[]) => principalWith(new Set(scopes)); const dependencies = Layer.mergeAll( Layer.mock(CloudSpeech.CloudSpeech)({}), @@ -145,6 +147,10 @@ effectIt.effect( Effect.gen(function* () { let stored = false; const reference = { provider: "work", reference: "op://Work/Voice/key" }; + const scopes = new Set([ + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + ]); const save = vi.fn(); const transcribe = vi.fn(); const cloud = Layer.mock(CloudSpeech.CloudSpeech)({ @@ -182,7 +188,7 @@ effectIt.effect( const { handler, dispose } = HttpRouter.toWebHandler( HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( Layer.provide(speechHttpApiLayer), - Layer.provide(principal(AuthOrchestrationOperateScope, AuthSettingsWriteScope)), + Layer.provide(principalWith(scopes)), Layer.provide( Layer.mock(SpeechService.SpeechService)({ models: () => Effect.succeed({ models: [linkedModel] }), @@ -220,6 +226,14 @@ effectIt.effect( headers: { "content-type": "application/json" }, body: JSON.stringify({ key }), }); + // A reference needs the scope that saving it through settings would. + const refused = yield* setReference(reference); + expect(refused.status).toBe(403); + expect(yield* Effect.promise(() => refused.json())).toMatchObject({ + requiredPermission: AuthProvidersManageScope, + }); + expect(save).toHaveBeenCalledTimes(1); + scopes.add(AuthProvidersManageScope); expect((yield* setReference(reference)).status).toBe(204); expect(save).toHaveBeenLastCalledWith("xai", reference); expect((yield* setReference(reference.reference)).status).toBe(400); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 09c3d4dc23faa..f73640044be89 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -8,6 +8,7 @@ import { EnvironmentHttpApi, type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, + requiredScopesForServerSettingsPatch, SPEECH_MAX_OPTIONS_BYTES, TextGenerationError, } from "@t3tools/contracts"; @@ -15,6 +16,7 @@ import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -102,6 +104,14 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "setCloudKey", Effect.fn("environment.voice.setCloudKey")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); + // The key is a setting, so saving it needs what the same settings patch would. + const { key } = args.payload; + const value = key === null || Redacted.isRedacted(key) ? "" : key; + for (const scope of requiredScopesForServerSettingsPatch({ + cloudSpeechCredentials: { [args.params.provider]: value }, + })) { + yield* requireEnvironmentScope(scope); + } yield* cloud .setKey(args.params.provider, args.payload.key) .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 0a992f4f93b61..3d41537abf182 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -13,6 +13,7 @@ import { } from "@t3tools/client-runtime/voice-input"; import { AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, CloudSpeechApiKey, CloudSpeechModelId, @@ -176,6 +177,7 @@ export function CloudVoiceConfiguration({ const prepared = Option.getOrNull(usePreparedConnection(id)); const canUse = useEnvironmentScope(id, AuthOrchestrationOperateScope); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [presence, refresh] = useCloudRead(canUse ? prepared : null, getCloudSpeechKeys); const [models, refreshModels] = useCloudRead( routed && canUse ? prepared : null, @@ -194,6 +196,7 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) From d36fb7d263ac2267496b21f21e1cdf081d396549 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:19:28 -0800 Subject: [PATCH 276/288] fix(web): Open in file manager waits for a file preview to load, then shows the file in its folder (#41877) Co-authored-by: Claude Fable 5.2 --- .../chat/OpenInPicker.browser.test.tsx | 33 +++++++++++++++++-- .../chat/OpenInPicker.logic.test.ts | 15 ++++++++- .../src/components/chat/OpenInPicker.logic.ts | 15 +++++++++ apps/web/src/components/chat/OpenInPicker.tsx | 24 +++++++++----- .../src/components/files/FilePreviewPanel.tsx | 15 +++++---- 5 files changed, 84 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index cc246a1f9967c..51d06370dd838 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -66,6 +66,7 @@ vi.mock(import("../../remoteOpen"), async (importOriginal) => ({ })); import { OpenInPicker } from "./OpenInPicker"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { registerOpenFavoriteEditorCommand, useOpenFavoriteEditorShortcut, @@ -98,7 +99,7 @@ async function setup() { async function renderPicker( availableEditors: readonly EditorId[] = editors, panel = false, - { openInCwd = "/work/project", revealFileManager = false } = {}, + { openInCwd = "/work/project", fileManagerAction = "open" as FileManagerAction } = {}, ) { await act(async () => { for (const listener of state.listeners) listener(); @@ -108,7 +109,7 @@ async function setup() { keybindings={DEFAULT_RESOLVED_KEYBINDINGS} availableEditors={availableEditors} openInCwd={openInCwd} - revealFileManager={revealFileManager} + fileManagerAction={fileManagerAction} displayMode={panel ? "panel" : "toolbar"} compact={!panel} /> @@ -189,6 +190,34 @@ describe("host editor access", () => { }); }); +describe("file manager", () => { + it("waits for the path's type, then shows a file in its folder", async () => { + await using fixture = await setup(); + const { renderPicker, primaryButton, click, pressOpenFavorite } = fixture; + state.allowed.add(selected); + const openInCwd = "/work/project/notes.md"; + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "unavailable" }); + + expect(primaryButton().disabled).toBe(true); + await click(primaryButton()); + expect((await pressOpenFavorite()).defaultPrevented).toBe(false); + expect(state.run).not.toHaveBeenCalled(); + + // A failed open is not announced, so no timer outlives the test. + state.run.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No file manager")))); + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "reveal" }); + await click(primaryButton()); + expect(state.run.mock.calls).toEqual([ + [ + { + environmentId: selected, + input: { cwd: openInCwd, editor: "file-manager", reveal: true }, + }, + ], + ]); + }); +}); + describe("remote editor links", () => { it("opens the link from the fallback when the picker is not mounted", async () => { await using fixture = await setup(); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.test.ts b/apps/web/src/components/chat/OpenInPicker.logic.test.ts index 10595e2f8cdbe..3b5536c78f396 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.test.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.test.ts @@ -1,7 +1,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { shouldShowOpenInPicker } from "./OpenInPicker.logic"; +import { fileManagerActionForPath, shouldShowOpenInPicker } from "./OpenInPicker.logic"; describe("shouldShowOpenInPicker", () => { it("shows both local environments when the primary has a separate WSL home", () => { @@ -24,3 +24,16 @@ describe("shouldShowOpenInPicker", () => { } }); }); + +describe("fileManagerActionForPath", () => { + it("opens only folders and shows a file once its read settled on a server that can", () => { + for (const [isFolder, isSettled, canReveal, action] of [ + [true, false, false, "open"], + [false, false, true, "unavailable"], + [false, true, false, "unavailable"], + [false, true, true, "reveal"], + ] as const) { + expect(fileManagerActionForPath({ isFolder, isSettled, canReveal })).toBe(action); + } + }); +}); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.ts b/apps/web/src/components/chat/OpenInPicker.logic.ts index 5978a5986030a..8e49592e05866 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.ts @@ -18,3 +18,18 @@ export function shouldShowOpenInPicker(input: { } return input.remoteOpenMode !== "local-exec"; } + +export type FileManagerAction = "open" | "reveal" | "unavailable"; + +/** + * The file manager opens folders and shows files in their folder. A path whose read has not + * settled may be either, and a file needs the server's reveal support, so both wait. + */ +export function fileManagerActionForPath(input: { + readonly isFolder: boolean; + readonly isSettled: boolean; + readonly canReveal: boolean; +}): FileManagerAction { + if (input.isFolder) return "open"; + return input.isSettled && input.canReveal ? "reveal" : "unavailable"; +} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index fc125bbd79cfa..a4b7322aa5dda 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -10,6 +10,7 @@ import { T, useGT, useMessages, Var } from "gt-react"; import { memo, use, useRef } from "react"; import { BackgroundThreadContext } from "./backgroundThread"; import { shortcutLabelForCommand } from "../../keybindings"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut"; import { usePreferredEditor } from "../../editorPreferences"; import { editorLabelForPlatform } from "../../editorLabels"; @@ -81,7 +82,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact = false, enableShortcut = true, displayMode = "toolbar", - revealFileManager = false, + fileManagerAction = "open", }: { environmentId: EnvironmentId; keybindings: ResolvedKeybindingsConfig; @@ -92,7 +93,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact?: boolean; enableShortcut?: boolean; displayMode?: "toolbar" | "panel"; - revealFileManager?: boolean; + fileManagerAction?: FileManagerAction; }) { const gt = useGT(); const messages = useMessages(); @@ -111,11 +112,13 @@ export const OpenInPicker = memo(function OpenInPicker({ // Remote editors run on the viewing machine; only desktop can probe that PATH. const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors; const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors); + const isEditorUnavailable = (editor: EditorId | null) => + editor === "file-manager" && fileManagerAction === "unavailable"; const openInEditor = async (editorId: EditorId | null): Promise => { if (!openInCwd) return false; const editor = editorId ?? preferredEditor; - if (!editor) return false; + if (!editor || isEditorUnavailable(editor)) return false; if (remote.mode === "remote-unavailable") return false; if (remote.mode === "remote-links") { const url = buildRemoteOpenUrl({ @@ -139,7 +142,7 @@ export const OpenInPicker = memo(function OpenInPicker({ input: { cwd: openInCwd, editor, - ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}), + ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}), }, }); setPreferredEditor(editor); @@ -187,7 +190,11 @@ export const OpenInPicker = memo(function OpenInPicker({ {options.map(({ label, Icon, value, kind }) => ( { if (presentation === "menu") { @@ -223,8 +230,7 @@ export const OpenInPicker = memo(function OpenInPicker({ {primaryOption && ( openInEditor(preferredEditor)} > @@ -261,7 +267,9 @@ export const OpenInPicker = memo(function OpenInPicker({ variant={isPanel ? "ghost" : "outline"} part="primary" panel={isPanel} - disabled={!preferredEditor || !openInCwd || !canOpenEditor} + disabled={ + !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor) + } {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})} onClick={() => { if (!preferredEditor) return; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 2ef4d67095e55..8a59d79db24d6 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -64,6 +64,7 @@ import { import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { OpenInPicker } from "~/components/chat/OpenInPicker"; +import { fileManagerActionForPath } from "~/components/chat/OpenInPicker.logic"; import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer"; import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions"; import { useRemoteOpenState } from "~/remoteOpen"; @@ -1311,12 +1312,12 @@ export default function FilePreviewPanel({ attachment === undefined && (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null)); const hostFolderPath = isFolder && isHostFile ? relativePath : null; - // A chat-linked folder reads as a file until its read settles, and revealing a - // folder selects it in its parent instead of opening it, so reveal waits. - const revealsInFileManager = - !isFolder && - (file.data !== null || file.error !== null) && - serverConfig?.shellRevealInFileManager === true; + // A chat-linked folder reads as a file until its read settles, and a trail only implies a folder. + const fileManagerAction = fileManagerActionForPath({ + isFolder: relativePath === null || file.isNotFile, + isSettled: file.data !== null || file.error !== null, + canReveal: serverConfig?.shellRevealInFileManager === true, + }); // Everything preview-related keys off previewPath; a folder has no preview. const previewPath = isFolder ? null : relativePath; const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); @@ -1613,7 +1614,7 @@ export default function FilePreviewPanel({ openInCwd={absolutePath} openInCwdIsFile={file.isFile} compact - revealFileManager={revealsInFileManager} + fileManagerAction={fileManagerAction} /> ) : null} {canToggleRendered && renderedMode ? ( From f981b42dc490aed87c2c91ddd88b5d497eb811fd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:20:51 -0800 Subject: [PATCH 277/288] fix(mobile): the default-branch confirmation describes the live checkout (#41880) Co-authored-by: Claude Fable 5.2 --- .../pull-requests/PullRequestRouteScreen.tsx | 4 +- .../pull-requests/usePullRequestDiff.test.tsx | 20 ++- .../pull-requests/usePullRequestDiff.ts | 14 ++ .../features/threads/ThreadGitControls.tsx | 2 - .../threads/git/GitConfirmSheet.test.tsx | 124 ++++++++++++++++++ .../features/threads/git/GitConfirmSheet.tsx | 66 +++++----- .../features/threads/git/GitOverviewSheet.tsx | 4 - apps/mobile/vite.config.ts | 1 + 8 files changed, 192 insertions(+), 43 deletions(-) create mode 100644 apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 488ca226d64c9..c0a644321a66f 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -116,6 +116,7 @@ import { usePullRequestVerticalControls, } from "./PullRequestControls"; import { + pullRequestParams, pullRequestTarget as requestTarget, usePullRequestDiff, usePullRequestDiffEntry, @@ -408,7 +409,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps pullRequestParams(route.params), [route.params]); usePullRequestEnvironmentFallback(params); const connected = usePullRequestConnected(params.environmentId); const [chosenSection, setSection] = useState<"overview" | "activity" | "guide">(() => { diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx index 7d4244a5c04a5..282a18ca2443b 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx @@ -10,7 +10,11 @@ import { expect, it, vi } from "vite-plus/test"; const mocks = vi.hoisted(() => ({ diff: vi.fn() })); vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } })); -import { usePullRequestDiff, usePullRequestDiffEntry } from "./usePullRequestDiff"; +import { + pullRequestParams, + usePullRequestDiff, + usePullRequestDiffEntry, +} from "./usePullRequestDiff"; import * as reviewModel from "../review/reviewModel"; import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter"; @@ -290,3 +294,17 @@ it("holds further pages back until a pull to refresh has reread page one", async expect(screen.current.patch).toContain("+pushed"); expect(screen.current.canLoadMore).toBe(true); }); + +it("keeps only the pull request a route names", () => { + const pullRequest = { + environmentId: "environment", + projectId: "project", + repository: "owner/repo", + number: 1, + host: "git.example.com", + navigationUrl: "https://git.example.com/owner/repo/pull/1#discussion_r1", + navigationId: 2, + }; + const routeParams = { ...pullRequest, commit: "abc1234", path: "src/index.ts" }; + expect(pullRequestParams(routeParams)).toEqual(pullRequest); +}); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts index 5cf121b7f5660..85527e491c93a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts @@ -34,6 +34,20 @@ export type PullRequestParams = { export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string }; +/** The pull request a route names, without whatever else arrived on that route. */ +export function pullRequestParams(params: PullRequestParams): PullRequestParams { + return { + environmentId: params.environmentId, + projectId: params.projectId, + repository: params.repository, + number: params.number, + ...(params.host === undefined ? {} : { host: params.host }), + ...(params.navigationUrl === undefined ? {} : { navigationUrl: params.navigationUrl }), + ...(params.navigationId === undefined ? {} : { navigationId: params.navigationId }), + ...(params.initialSummary === undefined ? {} : { initialSummary: params.initialSummary }), + }; +} + export function pullRequestTarget(params: PullRequestParams) { return { environmentId: EnvironmentId.make(params.environmentId), diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 5e67fb0181ad5..1a36d6b350e4a 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -237,8 +237,6 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) { environmentId: String(environmentId), threadId: String(threadId), confirmAction: confirmableAction, - branchName, - includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"), }); return; } diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx new file mode 100644 index 0000000000000..90b9580fd48bc --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx @@ -0,0 +1,124 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +type ActionProps = { label: string; disabled?: boolean; onPress: () => void }; +type IntroProps = { title: string; description: string }; +const state = vi.hoisted(() => ({ + refName: null as string | null, + intro: null as IntroProps | null, + actions: [] as ActionProps[], + ran: [] as object[], +})); + +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ goBack: () => {} }), +})); +vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../../components/ui/SheetIntro", () => ({ + SheetIntro: (props: IntroProps) => { + state.intro = props; + return null; + }, +})); +vi.mock("../../../state/query", () => ({ + useEnvironmentQuery: () => ({ + data: state.refName === null ? undefined : { refName: state.refName }, + }), +})); +vi.mock("../../../state/use-thread-selection", () => ({ + useThreadSelection: () => ({ + selectedThread: { environmentId: "environment" }, + selectedThreadProject: null, + }), +})); +vi.mock("../../../state/use-selected-thread-worktree", () => ({ + useSelectedThreadWorktree: () => ({ selectedThreadCwd: "/repo" }), +})); +vi.mock("../../../state/use-selected-thread-git-state", () => ({ + useSelectedThreadGitState: () => ({ selectedThreadBranches: [] }), +})); +vi.mock("../../../state/use-selected-thread-git-actions", () => ({ + useSelectedThreadGitActions: () => ({ + canWriteSourceControl: true, + canCreateFeatureBranch: true, + onRunSelectedThreadGitAction: (input: object) => { + state.ran.push(input); + return Promise.resolve(null); + }, + }), +})); +vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } })); +vi.mock("../thread-inspector-navigation", () => ({ useReturnToThread: () => () => {} })); +vi.mock("./gitSheetComponents", () => ({ + SheetActionButton: (props: ActionProps) => { + state.actions.push(props); + return null; + }, +})); + +import { GitConfirmSheet } from "./GitConfirmSheet"; + +function setup(refName: string | null, params: Record) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + state.refName = refName; + state.intro = null; + state.actions = []; + state.ran = []; + const root = createRoot(document.createElement("div")); + act(() => { + root.render( + , + ); + }); + // Each render registers Continue first, then the feature branch button. + const [continueButton, featureBranchButton] = state.actions.slice(-2); + return { + continueButton: continueButton!, + featureBranchButton: featureBranchButton!, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("describes the action it runs on the branch that is checked out", async () => { + using screen = setup("main", { + confirmAction: "commit_push", + branchName: "docs", + includesCommit: "false", + commitMessage: "from the route", + filePaths: "a.ts,b.ts", + }); + expect(state.intro).toMatchObject({ + title: "Commit & push to default branch?", + description: expect.stringContaining('commit and push changes on "main"'), + }); + expect(screen.continueButton.label).toBe("Commit & push to main"); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([ + { action: "commit_push" }, + { action: "commit_push", featureBranch: true }, + ]); +}); + +it.each([ + ["an action it does not confirm", "main", "commit"], + ["no checked out branch", null, "push"], +])("runs nothing for %s", async (_case, refName, confirmAction) => { + using screen = setup(refName, { confirmAction }); + expect(screen.continueButton.disabled).toBe(true); + expect(screen.featureBranchButton.disabled).toBe(true); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([]); +}); diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 1da0ec450a572..32a6fcbe22c2a 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -1,4 +1,7 @@ -import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/state/vcs"; +import { + resolveDefaultBranchActionDialogCopy, + type DefaultBranchConfirmableAction, +} from "@t3tools/client-runtime/state/vcs"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; @@ -13,6 +16,7 @@ import { FitSheet } from "../../../components/ui/FitSheet"; import { SheetIntro } from "../../../components/ui/SheetIntro"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../../state/query"; import { @@ -28,13 +32,16 @@ type GitConfirmSheetProps = StaticScreenProps< readonly environmentId: string; readonly threadId: string; readonly confirmAction?: string; - readonly branchName?: string; - readonly includesCommit?: string; - readonly commitMessage?: string; - readonly filePaths?: string; } & GitRepositoryRouteParams >; +const CONFIRMABLE_ACTIONS: ReadonlyArray = [ + "push", + "create_pr", + "commit_push", + "commit_push_pr", +]; + export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); @@ -45,37 +52,35 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gitActions = useSelectedThreadGitActions(repository); const { canWriteSourceControl, canCreateFeatureBranch } = gitActions; const { selectedThread, selectedThreadProject } = useThreadSelection(); - // The overview that opened this sheet already holds the repository's status subscription. - const repositoryStatus = useEnvironmentQuery( - repository !== undefined && selectedThread !== null + const threadWorktree = useSelectedThreadWorktree(); + const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd; + // The Git controls that opened this sheet already hold the checkout's status subscription. + const gitStatus = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ environmentId: selectedThread.environmentId, - input: { cwd: repository.cwd }, + input: { cwd: selectedThreadCwd }, }) : null, ); const terminology = sourceControlClients.get( repository === undefined ? selectedThreadProject?.repositoryIdentity?.provider - : repositoryStatus.data?.sourceControlProvider?.kind, + : gitStatus.data?.sourceControlProvider?.kind, ).changeRequest; const params = props.route.params; - const confirmAction = params.confirmAction as - | "push" - | "create_pr" - | "commit_push" - | "commit_push_pr" - | undefined; - const branchName = params.branchName ?? ""; - const includesCommit = params.includesCommit === "true"; + // The route only names the action; what the sheet says about it comes from the checkout. + const confirmAction = CONFIRMABLE_ACTIONS.find((action) => action === params.confirmAction); + const branchName = gitStatus.data?.refName ?? null; + const includesCommit = confirmAction === "commit_push" || confirmAction === "commit_push_pr"; const environmentId = params.environmentId ?? ""; const threadId = params.threadId ?? ""; const copy = useMemo( () => - confirmAction + confirmAction && branchName ? resolveDefaultBranchActionDialogCopy( { action: confirmAction, @@ -90,26 +95,17 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { ); const continuePendingAction = async () => { - if (!canWriteSourceControl || !confirmAction) return; + if (!canWriteSourceControl || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction }); }; const movePendingActionToFeatureBranch = useCallback(async () => { - if (!canCreateFeatureBranch || !confirmAction) return; + if (!canCreateFeatureBranch || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); if (includesCommit) { - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - featureBranch: true, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, featureBranch: true }); return; } @@ -129,10 +125,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { }, [ canCreateFeatureBranch, confirmAction, + copy, gitActions, gitState.selectedThreadBranches, includesCommit, - params, returnToThread, environmentId, threadId, @@ -153,13 +149,13 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { void continuePendingAction()} /> void movePendingActionToFeatureBranch()} /> diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 0ab21904489e1..4c7225f5cbb4d 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -247,10 +247,6 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { threadId: String(threadId), ...repositoryParams, confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), }), ); return; diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 436cea63f4f28..584ac4ae67968 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -8,6 +8,7 @@ const reactTests = [ "src/features/threads/ThreadGuestShareSheet.test.tsx", "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", + "src/features/threads/git/GitConfirmSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/threads/NewTaskRouteScreen.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", From cc2e4c1704a952df7cebc78d80a4c97a108cffa1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:29:52 -0800 Subject: [PATCH 278/288] fix(server): revoking all other sessions also ends sign-ins still in progress (#41884) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/EnvironmentAuth.test.ts | 44 ++++ apps/server/src/auth/EnvironmentAuth.ts | 210 ++++++++++++------- apps/server/src/auth/McpOAuth.test.ts | 38 ++++ apps/server/src/auth/McpOAuth.ts | 21 +- 4 files changed, 226 insertions(+), 87 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 6eceb824a8cba..352ca586783d2 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -17,6 +17,7 @@ import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as PairingGrantStore from "./PairingGrantStore.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; @@ -916,6 +917,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( ), ); + it.effect("issues no session to an exchange that revoking all others overtook", () => + Effect.gen(function* () { + const pairingLinks = yield* PairingGrantStore.PairingGrantStore; + let afterSpend: Effect.Effect = Effect.void; + const serverAuth = yield* EnvironmentAuth.make.pipe( + Effect.provideService(PairingGrantStore.PairingGrantStore, { + ...pairingLinks, + consume: (credential, input) => + pairingLinks.consume(credential, input).pipe(Effect.tap(() => afterSpend)), + }), + Effect.provide( + Layer.merge( + ManagedPolicy.layerTest(), + ServerSecretStore.layer.pipe(Layer.provideMerge(layerServerConfig())), + ), + ), + ); + const owner = yield* serverAuth.issueSession(); + const succeeded = { onFailure: () => false, onSuccess: () => true }; + const exchanges = [ + (credential: string) => + serverAuth + .createBrowserSession(credential, requestMetadata) + .pipe(Effect.match(succeeded)), + (credential: string) => + serverAuth + .exchangeBootstrapCredentialForAccessToken(credential, undefined, requestMetadata) + .pipe(Effect.match(succeeded)), + ]; + for (const exchange of exchanges) { + const pairing = yield* serverAuth.issuePairingCredential(); + afterSpend = serverAuth.revokeOtherClientSessions(owner.sessionId).pipe(Effect.orDie); + const exchanged = yield* exchange(pairing.credential); + afterSpend = Effect.void; + + expect(exchanged).toBe(false); + expect((yield* serverAuth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + } + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("accepts cookie sessions on socket upgrades only from the app's own origins", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 977840617d04c..46e207dcf8ead 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -35,6 +35,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -639,18 +640,25 @@ export class EnvironmentAuth extends Context.Service< readonly revokeMcpClientToken: ( token: string, ) => Effect.Effect; + /** How many times "revoke all others" has run since this server started. */ + readonly otherSessionRevocationCount: Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; readonly peerLink: boolean; readonly client: AuthClientMetadata; + /** + * `otherSessionRevocationCount` read before the sign-in was approved. The session is + * refused when "revoke all others" has run since. + */ + readonly approvedAtRevocationCount?: number; }) => Effect.Effect< { readonly sessionId: AuthSessionId; readonly token: string; readonly expiresAt: DateTime.DateTime; }, - ServerAuthInternalError + ServerAuthInvalidCredentialError | ServerAuthInternalError >; /** * Spends a code covering all granted scopes and returns the level it approves. A level-bound @@ -940,6 +948,28 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.getSessionState"), ); + // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints + // at once would open two requests with one code, and a revoke landing between an exchange + // spending its credential and trusting the key would be undone by that exchange. + const connectTrustLock = yield* Semaphore.make(1); + + // Counts "revoke all others" runs. An exchange or sign-in approval that began before a run + // issues its session here, under the lock the run holds, so it cannot leave a session behind. + const otherSessionRevocations = yield* Ref.make(0); + const issueUnlessOthersRevokedSince = (since: number, issue: Effect.Effect) => + Ref.get(otherSessionRevocations).pipe( + Effect.flatMap((count): Effect.Effect => + count === since + ? issue + : Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "All other sessions were revoked before this one was issued.", + }), + ), + ), + connectTrustLock.withPermits(1), + ); + const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn( "EnvironmentAuth.createBrowserSession", )(function* (credential, requestMetadata, previousSessionToken) { @@ -967,6 +997,7 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.createBrowserSession"), ); } + const revocationsAtStart = yield* Ref.get(otherSessionRevocations); const previousSession = previousSessionToken === undefined ? undefined @@ -977,20 +1008,23 @@ export const make = Effect.gen(function* () { const grant = yield* bootstrapCredentials .consume(credential) .pipe(Effect.mapError(toBootstrapExchangeError)); - const session = yield* sessions - .issue({ - method: "browser-session-cookie", - subject: grant.subject, - scopes: grant.scopes, - ...(previousSession?.method === "browser-session-cookie" - ? { replaceSessionId: previousSession.sessionId } - : {}), - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))); + const session = yield* issueUnlessOthersRevokedSince( + revocationsAtStart, + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + scopes: grant.scopes, + ...(previousSession?.method === "browser-session-cookie" + ? { replaceSessionId: previousSession.sessionId } + : {}), + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))), + ); return { response: { authenticated: true, @@ -1062,11 +1096,6 @@ export const make = Effect.gen(function* () { ); }; - // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints - // at once would open two requests with one code, and a revoke landing between an exchange - // spending its credential and trusting the key would be undone by that exchange. - const connectTrustLock = yield* Semaphore.make(1); - const toAccessTokenResult = (session: SessionStore.IssuedSession) => DateTime.now.pipe( Effect.map( @@ -1106,63 +1135,71 @@ export const make = Effect.gen(function* () { const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] = (credential, requestedScopes, requestMetadata, input) => { - return resolveBootstrapGrant(credential, { - ...input, - requestMetadata, - ...(requestedScopes !== undefined ? { requestedScopes } : {}), - }).pipe( - // Every T3 Connect key that gets in is remembered, so turning approval on later - // keeps the devices already in use and lists them for review. - Effect.tap((grant) => - grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint - ? bootstrapCredentials - .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) - .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) - : Effect.void, - ), - Effect.flatMap((grant) => - Effect.gen(function* () { - const grantedScopes = - requestedScopes === undefined - ? grant.scopes - : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); - if (grantedScopes.length === 0) { - return yield* new ServerAuthScopeNotGrantedError({}); - } - // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep - // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. - const renewable = - input?.proofKeyThumbprint !== undefined && - grant.method === "one-time-token" && - grant.subject === PAIRING_LINK_SUBJECT; - return yield* sessions - .issue({ - method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", - subject: grant.subject, - scopes: grantedScopes, - ...(input?.proofKeyThumbprint - ? { - proofKeyThumbprint: input.proofKeyThumbprint, - ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), - } - : {}), - ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), - replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe( - Effect.mapError( - (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), - ), - ); - }), - ), - Effect.flatMap(toAccessTokenResult), - (exchange) => - input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + const exchangeSince = (revocationsAtStart: number) => + resolveBootstrapGrant(credential, { + ...input, + requestMetadata, + ...(requestedScopes !== undefined ? { requestedScopes } : {}), + }).pipe( + // Every T3 Connect key that gets in is remembered, so turning approval on later + // keeps the devices already in use and lists them for review. + Effect.tap((grant) => + grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint + ? bootstrapCredentials + .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) + : Effect.void, + ), + Effect.flatMap((grant) => + Effect.gen(function* () { + const grantedScopes = + requestedScopes === undefined + ? grant.scopes + : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); + if (grantedScopes.length === 0) { + return yield* new ServerAuthScopeNotGrantedError({}); + } + // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep + // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. + const renewable = + input?.proofKeyThumbprint !== undefined && + grant.method === "one-time-token" && + grant.subject === PAIRING_LINK_SUBJECT; + const issue = sessions + .issue({ + method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", + subject: grant.subject, + scopes: grantedScopes, + ...(input?.proofKeyThumbprint + ? { + proofKeyThumbprint: input.proofKeyThumbprint, + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), + } + : {}), + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), + replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), + ), + ); + // A proof-key exchange holds the lock from before it spends its credential. + return yield* input?.proofKeyThumbprint + ? issue + : issueUnlessOthersRevokedSince(revocationsAtStart, issue); + }), + ), + Effect.flatMap(toAccessTokenResult), + (exchange) => + input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + ); + return Ref.get(otherSessionRevocations).pipe( + Effect.flatMap(exchangeSince), Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"), ); }; @@ -1486,7 +1523,12 @@ export const make = Effect.gen(function* () { .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey)) .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))); return yield* revokeOtherSessionsExcept(currentSessionId); - }).pipe(connectTrustLock.withPermits(1)); + }).pipe( + // Counted last, after unspent links and session rows are gone, so whatever reads the + // new count can no longer use either. + Effect.ensuring(Ref.update(otherSessionRevocations, (count) => count + 1)), + connectTrustLock.withPermits(1), + ); }); const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) => @@ -1659,8 +1701,8 @@ export const make = Effect.gen(function* () { return yield* revokeSession(session.value.sessionId); }); - const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => - sessions + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => { + const issue = sessions .issue({ subject: MCP_CLIENT_SUBJECT, method: "bearer-access-token", @@ -1677,8 +1719,13 @@ export const make = Effect.gen(function* () { expiresAt: issued.expiresAt, })), Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), - Effect.withSpan("EnvironmentAuth.issueMcpClientSession"), ); + return ( + input.approvedAtRevocationCount === undefined + ? issue + : issueUnlessOthersRevokedSince(input.approvedAtRevocationCount, issue) + ).pipe(Effect.withSpan("EnvironmentAuth.issueMcpClientSession")); + }; const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = ( code, @@ -1742,6 +1789,7 @@ export const make = Effect.gen(function* () { issueStartupPairingUrl, authenticateMcpClient, revokeMcpClientToken, + otherSessionRevocationCount: Ref.get(otherSessionRevocations), issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index c21b707bad889..ea321bcf0241c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -538,6 +538,44 @@ it.live("signs in Gemini, which registers six user-bound redirect URIs for one c ), ); +it.live("issues no session for a sign-in approved before all other sessions were revoked", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const params = authorizeParams(clientId); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: (yield* auth.issuePairingCredential()).credential, + }); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const owner = yield* auth.issueSession(); + yield* auth.revokeOtherClientSessions(owner.sessionId); + + const response = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ); + expect(response.status).toBe(400); + expect(yield* json(response)).toEqual({ + error: "invalid_grant", + error_description: "The authorization code is invalid or expired.", + }); + expect((yield* auth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + }), + ), +); + it.live("rejects a wrong PKCE verifier and spends the code", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index e63c600ae1b2d..7c6cdc677cc3c 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -197,6 +197,7 @@ interface PendingCode { readonly codeChallenge: string; readonly resource: string; readonly access: AuthMcpClientAccess; + readonly approvedAtRevocationCount: number; readonly expiresAtMs: number; } @@ -445,6 +446,7 @@ const make = Effect.gen(function* () { const mintCode = Effect.fn("McpOAuth.mintCode")(function* ( authorization: AuthorizationRequest, access: AuthMcpClientAccess, + approvedAtRevocationCount: number, ) { const now = yield* Clock.currentTimeMillis; const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url"); @@ -458,6 +460,7 @@ const make = Effect.gen(function* () { codeChallenge: authorization.codeChallenge, resource: authorization.resource, access, + approvedAtRevocationCount, expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS, }); return next; @@ -467,6 +470,9 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; + // Read before the approver is checked: "revoke all others" then ends this sign-in whether + // it lands before the check or after the code is handed out. + const approvedAtRevocationCount = yield* environmentAuth.otherSessionRevocationCount; let access = decision.access; if (decision._tag === "pairing-code") { // An approval code is for one app's sign-in, never for linking another environment. @@ -502,7 +508,7 @@ const make = Effect.gen(function* () { }); } } - const code = yield* mintCode(input.authorization, access); + const code = yield* mintCode(input.authorization, access, approvedAtRevocationCount); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, access, @@ -567,14 +573,17 @@ const make = Effect.gen(function* () { access: pending.access, peerLink: pending.peerLink, client: deriveAuthClientMetadata({ request }), + approvedAtRevocationCount: pending.approvedAtRevocationCount, }) .pipe( Effect.catch((cause) => - Effect.logError("Could not issue an MCP client session.", { cause }).pipe( - Effect.andThen( - Effect.fail(fail("invalid_grant", "The session could not be issued.")), - ), - ), + cause._tag === "ServerAuthInvalidCredentialError" + ? Effect.fail(fail("invalid_grant", "The authorization code is invalid or expired.")) + : Effect.logError("Could not issue an MCP client session.", { cause }).pipe( + Effect.andThen( + Effect.fail(fail("invalid_grant", "The session could not be issued.")), + ), + ), ), ); return { From 8dc01892ad452038cd856e7d2447715ce23f286c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:31:37 -0800 Subject: [PATCH 279/288] fix(server): answering a secret request with a reference needs provider management (#41886) Co-authored-by: Claude Fable 5.2 --- .../features/threads/SecretRequestCard.tsx | 19 +++--- apps/server/src/auth/RpcAuthorization.test.ts | 61 +++++++++++++++++++ apps/server/src/auth/RpcAuthorization.ts | 10 +++ .../src/components/chat/SecretRequestCard.tsx | 14 +++-- docs/internals/04_environment-auth.md | 4 ++ docs/user/secrets.md | 3 +- 6 files changed, 98 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index e52fae8ce659f..24b0a1aa81d67 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -16,10 +16,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { useGT, useMessages } from "gt-react-native"; @@ -31,6 +32,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/ import { SecretTextInput } from "../../components/ui/SecretTextInput"; import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { Button } from "../../components/ui/Button"; @@ -91,10 +93,13 @@ function PendingSecretRequestForm(props: { const inputs = secretRequestInputs(item, m); const multiple = item.fields !== undefined; const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(props.environmentId, AuthProvidersManageScope); // A reference answers one value, so a card with fields is always typed. - const sources = multiple - ? NO_SOURCES - : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); + const sources = + multiple || !canUseReferences + ? NO_SOURCES + : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); const [sourceId, setSourceId] = useState(null); const source = sources.find((candidate) => candidate.id === sourceId) ?? null; const [values, setValues] = useState>>({}); diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 15ddfb90b08a5..1aa2a5b182ffa 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -657,6 +657,67 @@ describe("settings mutation authorization", () => { ); }); +it.effect("answering a secret request with a reference needs provider management", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.secretsAnswerRequest + > => tag !== WS_METHODS.secretsAnswerRequest, + ), + ); + const handled: string[] = []; + const handler = group.toLayerHandler(WS_METHODS.secretsAnswerRequest, ({ answer }) => + Effect.sync(() => { + handled.push(answer.type); + }), + ); + const clientWith = (...scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handler, RpcAuthorization.layer(scopes))), + ); + const request = { threadId: ThreadId.make("thread"), turnItemId: TurnItemId.make("item") }; + const reference = { + type: "reference" as const, + reference: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }; + + const operate = yield* clientWith(AuthOrchestrationOperateScope); + expect( + yield* operate[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); + expect(handled).toEqual([]); + // Typed values stay with the scope that runs the thread, whatever the fields are called. + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", secret: "typed-value" }, + }); + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", values: { provider: "personal", reference: "typed-value" } }, + }); + expect(handled).toEqual(["save", "save"]); + + const manage = yield* clientWith(AuthOrchestrationOperateScope, AuthProvidersManageScope); + yield* manage[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }); + expect(handled).toEqual(["save", "save", "reference"]); + const manageOnly = yield* clientWith(AuthProvidersManageScope); + expect( + yield* manageOnly[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + }), +); + it.effect("requires task permission before attaching a prepared worktree to a thread", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index b276fafb2723a..f6dda3ad4d8f8 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -11,6 +11,7 @@ import { requiredScopesForServerSettingsPatch, requiredScopesForProjectMutation, ProjectMutation, + SecretRequestAnswerInput, AuthSettingsWriteScope, AuthProvidersManageScope, AuthEnvironmentMaintainScope, @@ -283,6 +284,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => { const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput); +const decodeSecretRequestAnswer = Schema.decodeUnknownSync(SecretRequestAnswerInput); /** * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show; @@ -338,6 +340,14 @@ const requiredScopesForRpcCall = ( ) { return [AuthSettingsWriteScope, AuthProvidersManageScope]; } + // A reference answer has the server read a secret the caller names, as a saved reference does. + // Typed values can use any field names, so the answer's type decides, not its shape. + if ( + method === WS_METHODS.secretsAnswerRequest && + decodeSecretRequestAnswer(payload).answer.type === "reference" + ) { + return [AuthOrchestrationOperateScope, AuthProvidersManageScope]; + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index 25c1fe59d5e6b..49dff6b6a1c16 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -18,10 +18,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; @@ -38,6 +39,7 @@ import { import { useId, useRef, useState, type FormEvent } from "react"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -80,7 +82,9 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return hasFeatureFlag(config, "secretProviders") + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(environmentId, AuthProvidersManageScope); + return canUseReferences && hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 8b80c65860d60..1b22ab16e4d6d 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -29,6 +29,10 @@ model. over authenticated HTTP so long-lived tokens never appear in socket URLs. DPoP RPC tickets stay proof-key bound at upgrade. A successful handshake grants no extra authority: every RPC declares and checks its required scope in [`RpcAuthorization.ts`](../../apps/server/src/auth/RpcAuthorization.ts). +- **Secret references need `providers:manage`.** A request that names a secret for the server to + read needs `providers:manage` on top of its method's scope, whether the reference is saved in + settings or used once, as in a secret request answered with a reference. Typed values need only + the method's scope. Clients hide the secret provider picker from sessions without it. - **Backward-compatible scope evolution.** Token exchange intersects requested scopes with the pairing grant, dropping retired/unknown names and failing before consuming a link if none remain. Stored grants are never expanded when scopes split. Auth responses preserve legacy `scopes` diff --git a/docs/user/secrets.md b/docs/user/secrets.md index e7e899f197aeb..4f2a4b0de138c 100644 --- a/docs/user/secrets.md +++ b/docs/user/secrets.md @@ -55,7 +55,8 @@ you to paste it into the chat. Type or paste the value and select **Save securel **Decline**. You can answer from web, desktop, or mobile. If the environment has a secret provider, the card also lets you pick it and enter a reference -instead of the value. T3 Code reads the secret once, when you answer. If 1Password is locked, the +instead of the value. Answering with a reference needs permission to manage providers, as saving a +reference in Settings does; a session without it sees only the value field. T3 Code reads the secret once, when you answer. If 1Password is locked, the card says so and the request stays open: unlock it and try again, or enter the value. The value never appears in the conversation. Most requests keep it from the agent too: T3 Code From f133ec7cac2903596454421ba29673930ad430e0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:33:10 -0800 Subject: [PATCH 280/288] perf(scripts): the soak drives forge polling and thread churn, and names what grew (#41831) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 3 +- scripts/server-metrics-forge.ts | 614 +++++++++++++++++++ scripts/server-metrics-report.ts | 267 +++++++- scripts/server-metrics.test.ts | 83 +++ scripts/server-metrics.ts | 244 ++++++-- 5 files changed, 1160 insertions(+), 51 deletions(-) create mode 100644 scripts/server-metrics-forge.ts diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 863ccc0c7b697..1319174766471 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -36,7 +36,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud - Always compare refs with `ab ` on the same machine rather than comparing isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to - spot rising heap slopes (leaks). + spot rising heap slopes (leaks). A leak only shows in code the soak drives, so give a new + subsystem with long-lived state a part in its workload. - Steer server work by `working`: many worktree threads editing files at once with one client subscribed to all of them. Turns per minute that stay flat as threads are added mean the server, not the agents, is the bottleneck. diff --git a/scripts/server-metrics-forge.ts b/scripts/server-metrics-forge.ts new file mode 100644 index 0000000000000..1422bc25f6436 --- /dev/null +++ b/scripts/server-metrics-forge.ts @@ -0,0 +1,614 @@ +// A fake GitHub Enterprise host for the server-metrics soak: the GitHub API the server polls for a +// web client, and a git remote it fetches from, both over HTTPS on loopback. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http2 server; the proxy is raw. +import * as NodeHttp from "node:http"; +import * as NodeHttp2 from "node:http2"; +import * as NodeNet from "node:net"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { + PullRequestListInput, + PullRequestListResult, + PullRequestRef, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Duration from "effect/Duration"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; + +import { run, ScenarioError } from "./scenarios/shell.ts"; + +const OWNER = "bench"; +const REPO = "project"; +const TOKEN = "ghp_bench_fake"; +/** + * The host the project's origin names. It carries no port because pull request listings key a + * GitHub host without one, so the server reaches it on 443 through a proxy that tunnels it here. + */ +const HOST = "bench.test"; + +export interface ForgeRequest { + readonly at: number; + readonly method: string; + readonly path: string; + /** The GraphQL operation name, for GraphQL requests. */ + readonly operation: string | undefined; + readonly status: number; +} + +const GraphQlRequest = Schema.Struct({ + query: Schema.optional(Schema.String), + operationName: Schema.optional(Schema.NullOr(Schema.String)), + variables: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))), +}); +const decodeGraphQl = Schema.decodeUnknownEffect(Schema.fromJsonString(GraphQlRequest)); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +/** FNV-1a, enough to tell bodies apart. */ +const hash = (text: string) => { + let value = 0x811c9dc5; + for (let index = 0; index < text.length; index++) { + value = Math.imul(value ^ text.charCodeAt(index), 0x01000193) >>> 0; + } + return value.toString(16); +}; + +interface Failure { + readonly message: string; +} + +interface FakePullRequest { + readonly number: number; + readonly head: string; + oid: string; +} + +/** Serves the fake host until the scope closes. */ +export const serveFakeGitHub = Effect.fn("serverMetrics.serveFakeGitHub")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-forge-" }); + const keyFile = path.join(dir, "key.pem"); + const certFile = path.join(dir, "cert.pem"); + yield* run("openssl", [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-days", + "2", + "-subj", + `/CN=${HOST}`, + "-addext", + `subjectAltName=DNS:${HOST}`, + "-keyout", + keyFile, + "-out", + certFile, + ]); + const bare = path.join(dir, `${REPO}.git`); + yield* run("git", ["init", "-q", "--bare", bare]); + const requests: ForgeRequest[] = []; + const host = HOST; + const pullRequests: Array = [ + { number: 1, head: "bench/feature", oid: "0".repeat(40) }, + ...[2, 3, 4, 5].map((number) => ({ + number, + head: `bench/other-${number}`, + oid: "0".repeat(40), + })), + ]; + + const actor = { __typename: "User", id: "U_bench", login: OWNER, name: "Bench", avatarUrl: "" }; + /** Every field any of the polled reads selects; decoders ignore the ones a read did not ask for. */ + const pullRequestNode = (pr: FakePullRequest, now: number) => { + const minute = Math.floor(now / 60_000); + const at = (offsetMinutes: number) => + DateTime.formatIso(DateTime.makeUnsafe((minute - offsetMinutes) * 60_000)); + // The branch PR's CI reruns every other minute, so checks and their rollup keep changing. + const running = pr.number === 1 && minute % 2 === 0; + return { + __typename: "PullRequest", + id: `PR_bench_${pr.number}`, + number: pr.number, + title: `Bench change ${pr.number}`, + url: `https://${host}/${OWNER}/${REPO}/pull/${pr.number}`, + body: "A pull request the soak polls.", + baseRefName: "main", + headRefName: pr.head, + headRefOid: pr.oid, + state: "OPEN", + isDraft: false, + mergeable: "MERGEABLE", + mergeStateStatus: running ? "BLOCKED" : "CLEAN", + reviewDecision: null, + additions: 1, + deletions: 0, + changedFiles: 1, + createdAt: at(600 + pr.number), + updatedAt: at(0), + mergedAt: null, + mergeCommit: null, + mergedBy: null, + closedAt: null, + isCrossRepository: false, + maintainerCanModify: false, + headRepository: { name: REPO, nameWithOwner: `${OWNER}/${REPO}`, viewerPermission: "ADMIN" }, + headRepositoryOwner: { __typename: "User", login: OWNER }, + headRef: { id: `REF_bench_${pr.number}` }, + repository: { nameWithOwner: `${OWNER}/${REPO}` }, + author: actor, + autoMergeRequest: null, + viewerCanUpdate: true, + viewerDidAuthor: true, + viewerCanUpdateBranch: false, + baseRef: { compare: { behindBy: 0 } }, + reviewRequests: { nodes: [] }, + latestReviews: { nodes: [] }, + labels: { nodes: [] }, + commits: { + nodes: [ + { + commit: { + statusCheckRollup: { + state: running ? "PENDING" : "SUCCESS", + contexts: { + nodes: [ + { + __typename: "CheckRun", + name: "test", + status: running ? "IN_PROGRESS" : "COMPLETED", + conclusion: running ? null : "SUCCESS", + startedAt: at(1), + completedAt: running ? null : at(0), + detailsUrl: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + checkSuite: { + workflowRun: { + event: "pull_request", + runNumber: minute, + workflow: { id: "W_bench", name: "CI" }, + }, + }, + }, + { + __typename: "StatusContext", + context: "lint", + state: "SUCCESS", + targetUrl: null, + createdAt: at(5), + description: "Lint passed", + }, + ], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, + }, + ], + }, + }; + }; + const repositorySettings = { + mergeCommitAllowed: true, + squashMergeAllowed: true, + rebaseMergeAllowed: true, + autoMergeAllowed: false, + viewerPermission: "ADMIN", + }; + const page = (nodes: ReadonlyArray) => ({ + pageInfo: { hasNextPage: false, endCursor: null }, + nodes, + }); + + /** The `data` of a GraphQL answer, each aliased slice (`_0_repository`) answered on its own. */ + const answer = ( + operation: string, + variables: Readonly>, + now: number, + ): Record | undefined => { + const prefixes = new Set( + Object.keys(variables).map((name) => /^(_\d+_)?/.exec(name)?.[1] ?? ""), + ); + if (prefixes.size === 0) prefixes.add(""); + const data: Record = {}; + for (const prefix of prefixes) { + const variable = (name: string) => variables[`${prefix}${name}`]; + const byNumber = pullRequests.find((pr) => pr.number === variable("number")); + const single = byNumber === undefined ? null : pullRequestNode(byNumber, now); + const all = pullRequests.map((pr) => pullRequestNode(pr, now)); + switch (operation) { + case "PullRequestsByHead": + case "PullRequestHeads": + data[`${prefix}repository`] = { + pullRequests: page(all.filter((pr) => pr.headRefName === variable("head"))), + }; + break; + case "PullRequestList": + data[`${prefix}repository`] = { pullRequests: page(all) }; + break; + case "PullRequestSearch": + data[`${prefix}search`] = page(all); + break; + case "PullRequestByNumber": + case "PullRequestSummary": + case "PullRequestStats": + case "PullRequestCheckContexts": + data[`${prefix}repository`] = { pullRequest: single }; + break; + case "PullRequestCore": + data[`${prefix}repository`] = { ...repositorySettings, pullRequest: single }; + break; + case "RoutingIdentityViewer": + data[`${prefix}viewer`] = { databaseId: 1, login: OWNER }; + break; + case "ActorAvatars": { + const ids = variable("ids"); + data[`${prefix}nodes`] = (Array.isArray(ids) ? ids : []).map(() => actor); + break; + } + default: + return undefined; + } + } + return data; + }; + + /** REST answers by path under /api/v3; the body moves each minute where real polling sees change. */ + const restAnswer = (path: string, now: number): unknown => { + const minute = Math.floor(now / 60_000); + const repository = `repos/${OWNER}/${REPO}`; + if (path === "user") + return { login: OWNER, id: 1, name: "Bench", avatar_url: "", type: "User" }; + if (path === repository) { + return { + id: 1, + node_id: "R_bench", + name: REPO, + full_name: `${OWNER}/${REPO}`, + private: false, + default_branch: "main", + html_url: `https://${host}/${OWNER}/${REPO}`, + owner: { login: OWNER, id: 1, type: "User" }, + permissions: { admin: true, maintain: true, push: true, triage: true, pull: true }, + }; + } + if (path === `${repository}/actions/runs`) { + return { + total_count: minute % 2 === 0 ? 1 : 0, + workflow_runs: + minute % 2 === 0 + ? [ + { + id: minute, + name: "CI", + html_url: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + status: "in_progress", + }, + ] + : [], + }; + } + return undefined; + }; + + const serveGit = Effect.fn("serverMetrics.fakeGitHub.git")(function* (relative: string) { + if (relative.split("/").includes("..")) return HttpServerResponse.empty({ status: 404 }); + const file = path.join(bare, relative); + const body = yield* fs.readFile(file).pipe(Effect.option); + return body._tag === "Some" + ? HttpServerResponse.uint8Array(body.value, { contentType: "application/octet-stream" }) + : HttpServerResponse.empty({ status: 404 }); + }); + + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = new URL(request.url, "https://127.0.0.1"); + const gitPrefix = `/${OWNER}/${REPO}.git/`; + let operation: string | undefined; + let response: HttpServerResponse.HttpServerResponse; + if (url.pathname.startsWith(gitPrefix)) { + // Dumb HTTP: a static info/refs makes git fall back to reading the bare repository's files. + response = yield* serveGit(url.pathname.slice(gitPrefix.length)); + } else if (url.pathname === "/api/graphql") { + const raw = yield* request.text; + const body = yield* decodeGraphQl(raw).pipe( + Effect.orElseSucceed((): typeof GraphQlRequest.Type => ({})), + ); + operation = + body.operationName ?? + /\b(?:query|mutation)\s+(\w+)/.exec(body.query ?? "")?.[1] ?? + "anonymous"; + const data = answer(operation, body.variables ?? {}, yield* Clock.currentTimeMillis); + response = + data === undefined + ? HttpServerResponse.jsonUnsafe({ message: "Not Found" }, { status: 404 }) + : HttpServerResponse.jsonUnsafe({ data }); + } else { + const body = url.pathname.startsWith("/api/v3/") + ? restAnswer(url.pathname.slice("/api/v3/".length), yield* Clock.currentTimeMillis) + : undefined; + if (body === undefined) { + response = HttpServerResponse.jsonUnsafe( + { message: "Not Found", documentation_url: "https://docs.github.com/rest" }, + { status: 404 }, + ); + } else { + // A weak validator of the body, so an unchanged answer revalidates as a 304. + const text = encodeJson(body); + const etag = `W/"${text.length.toString(16)}-${hash(text)}"`; + response = + request.headers["if-none-match"] === etag + ? HttpServerResponse.empty({ status: 304, headers: { etag } }) + : HttpServerResponse.text(text, { + contentType: "application/json", + headers: { etag }, + }); + } + } + requests.push({ + at: yield* Clock.currentTimeMillis, + method: request.method, + path: url.pathname + url.search, + operation, + status: response.status, + }); + return response; + }).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500 }))); + + const key = yield* fs.readFileString(keyFile); + const cert = yield* fs.readFileString(certFile); + const context = yield* Layer.build( + NodeHttpServer.layer(() => NodeHttp2.createSecureServer({ key, cert, allowHTTP1: true }), { + port: 0, + host: "127.0.0.1", + }), + ); + const port = yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + return address._tag === "UnixPathAddress" ? 0 : address.port; + }).pipe(Effect.provide(context)); + // Tunnels only the fake host, so nothing the server sends through it reaches the internet. + const tunnels = new Set(); + const proxy = NodeHttp.createServer((_request, response) => { + response.writeHead(405).end(); + }); + proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => { + if (request.url !== `${HOST}:443`) { + client.end("HTTP/1.1 403 Forbidden\r\n\r\n"); + return; + } + const upstream = NodeNet.connect(port, "127.0.0.1", () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.pipe(client); + client.pipe(upstream); + }); + for (const socket of [client, upstream]) { + tunnels.add(socket); + socket.on("close", () => tunnels.delete(socket)); + socket.on("error", () => { + client.destroy(); + upstream.destroy(); + }); + } + }); + const proxyPort = yield* Effect.acquireRelease( + Effect.callback((resume) => { + proxy.once("error", (error) => + resume( + Effect.fail(new ScenarioError({ message: `the fake GitHub proxy: ${error.message}` })), + ), + ); + proxy.listen(0, "127.0.0.1", () => { + const address = proxy.address(); + resume(Effect.succeed(typeof address === "object" && address !== null ? address.port : 0)); + }); + }), + () => + Effect.callback((resume) => { + for (const socket of tunnels) socket.destroy(); + proxy.closeAllConnections(); + proxy.close(() => resume(Effect.void)); + }), + ); + const proxyUrl = `http://127.0.0.1:${proxyPort}`; + + /** Publishes the project to the fake remote and checks out a branch with an open PR. */ + const setupProject = Effect.fn("serverMetrics.fakeGitHub.setupProject")(function* ( + project: string, + ) { + const git = (args: ReadonlyArray) => run("git", args, { cwd: project }); + yield* git(["switch", "-q", "-c", "bench/feature"]); + yield* fs.writeFileString(path.join(project, "FEATURE.md"), "# feature\n"); + yield* git(["add", "."]); + yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit", + "-qm", + "feature", + ]); + yield* git(["push", "-q", bare, "main", "bench/feature"]); + yield* run("git", ["--git-dir", bare, "update-server-info"]); + yield* git(["remote", "add", "origin", `https://${host}/${OWNER}/${REPO}.git`]); + yield* git(["config", "http.sslCAInfo", certFile]); + yield* git(["config", "http.proxy", proxyUrl]); + // A developer's NO_PROXY could send this past the proxy, which is the only route to the host. + const hostEnvironment = yield* HostProcess.Environment; + yield* run("git", ["fetch", "-q", "origin"], { + cwd: project, + env: { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined, + ), + ), + NO_PROXY: "", + no_proxy: "", + GIT_SSL_CAINFO: certFile, + }, + }); + yield* git(["branch", "-q", "--set-upstream-to", "origin/bench/feature"]); + const [feature, main] = (yield* git(["rev-parse", "HEAD", "main"])).stdout.trim().split("\n"); + for (const pr of pullRequests) pr.oid = (pr.number === 1 ? feature : main) ?? pr.oid; + setupRequests = requests.length; + publishedMain = main; + }); + + let pushes = 0; + /** Lands a commit on the remote's main, so the server's next fetch transfers something. */ + const advanceRemote = Effect.gen(function* () { + const git = (args: ReadonlyArray) => run("git", ["--git-dir", bare, ...args]); + const commit = (yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit-tree", + "main^{tree}", + "-p", + "main", + "-m", + `upstream ${++pushes}`, + ])).stdout.trim(); + yield* git(["update-ref", "refs/heads/main", commit]); + yield* git(["update-server-info"]); + }); + + /** Requests the project setup made before the server started, which `verify` leaves out. */ + let setupRequests = 0; + let publishedMain: string | undefined; + let fetchedPush = false; + let completedPolls = 0; + const failures: Array = []; + /** + * What a web client with the pull requests sidebar and the branch's PR open asks for: the list, + * then the branch PR's summary and checks, every 30 s until interrupted. Failures are kept, not + * thrown, so one bad answer does not end the soak. + */ + const pollLikeWebClient = Effect.fn("serverMetrics.fakeGitHub.poll")(function* (rpc: { + readonly list: (input: PullRequestListInput) => Effect.Effect; + readonly summary: (input: PullRequestRef) => Effect.Effect; + readonly checks: (input: PullRequestRef) => Effect.Effect; + }) { + const record = (what: string) => (error: Failure) => + Effect.sync(() => { + failures.push(`${what}: ${error.message}`); + }); + while (true) { + const listed = yield* rpc + .list({ state: "open" }) + .pipe(Effect.tapError(record("pullRequests.list")), Effect.option); + const entry = + listed._tag === "Some" + ? listed.value.entries.find((row) => row.headBranch === "bench/feature") + : undefined; + if (listed._tag === "Some" && entry === undefined) { + failures.push(`pullRequests.list: no branch PR in ${listed.value.entries.length} rows`); + } + if (entry !== undefined) { + const ref = { + projectId: entry.projectId, + host: entry.host, + repository: entry.repository, + number: entry.number, + }; + const completed = yield* Effect.all([rpc.summary(ref), rpc.checks(ref)]).pipe( + Effect.as(true), + Effect.catch((error) => + record("pullRequests.summary/checks")(error).pipe(Effect.as(false)), + ), + ); + if (completed) completedPolls++; + } + yield* Effect.sleep(Duration.seconds(30)); + } + }); + + return { + host, + /** The server's view of the host: the fake token and CA, and none of the developer's logins. */ + env: { + GH_HOST: host, + GH_ENTERPRISE_TOKEN: TOKEN, + GITHUB_ENTERPRISE_TOKEN: "", + GH_TOKEN: "", + GITHUB_TOKEN: "", + // An empty gh config, so a gh the server runs has no login for any host. + GH_CONFIG_DIR: path.join(dir, "gh"), + NODE_EXTRA_CA_CERTS: certFile, + // Overrides a developer's own GIT_SSL_CAINFO, which would win over the repository's setting. + GIT_SSL_CAINFO: certFile, + NODE_USE_ENV_PROXY: "1", + HTTPS_PROXY: proxyUrl, + https_proxy: proxyUrl, + // The fake Anthropic API and the server's own loopback listeners stay direct. + NO_PROXY: "127.0.0.1,localhost,::1", + no_proxy: "127.0.0.1,localhost,::1", + }, + setupProject, + advanceRemote, + /** Records whether the project's origin/main moved past setup, i.e. the server fetched a push. */ + checkFetched: (project: string) => + run("git", ["rev-parse", "refs/remotes/origin/main"], { cwd: project }).pipe( + Effect.map(({ stdout }) => { + fetchedPush = stdout.trim() !== publishedMain; + }), + ), + requests: requests as ReadonlyArray, + pollLikeWebClient, + /** + * Prints what the server asked for, and fails unless it polled pull requests and checks and + * fetched from the remote. Poller failures are reported, not fatal: a long soak can see one. + */ + verify: Effect.gen(function* () { + const counts = new Map(); + for (const request of requests.slice(setupRequests)) { + const key = + request.operation ?? + (request.path.startsWith(`/${OWNER}/${REPO}.git/`) + ? request.status !== 200 + ? undefined + : request.path.startsWith(`/${OWNER}/${REPO}.git/info/refs`) + ? "git fetch" + : undefined + : `${request.method} ${request.path.replace(/\?.*/, "")} ${request.status}`); + if (key !== undefined) counts.set(key, (counts.get(key) ?? 0) + 1); + } + const listed = [...counts].map(([key, count]) => `${key} ×${count}`).join(", "); + yield* Console.error(`fake GitHub served ${requests.length} requests: ${listed}`); + if (failures.length > 0) { + yield* Console.error( + `fake GitHub: ${failures.length} client polls failed, first: ${failures[0]}`, + ); + } + const missing = [ + "PullRequestsByHead", + "PullRequestSearch", + "PullRequestCore", + "git fetch", + ].filter((key) => !counts.has(key)); + if (pushes > 0 && !fetchedPush) missing.push("a fetch that brought in a pushed commit"); + if (completedPolls === 0) missing.push("one full client poll (list, summary, checks)"); + if (missing.length > 0) { + return yield* new ScenarioError({ + message: `the soak never reached the fake GitHub for ${missing.join(", ")}`, + }); + } + }), + }; +}); + +export type FakeGitHub = Effect.Success>; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index b06e08a590af0..bab911ab9124f 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -37,6 +37,8 @@ const Soak = Schema.Struct({ minutes: Schema.Number, heapMBPerHour: Schema.Number, rssMBPerHour: Schema.Number, + /** Processes below the server, so agent or git children that outlive their thread show. */ + childProcessesPerHour: Schema.optional(Schema.Number), }); const MachineState = Schema.Struct({ @@ -161,6 +163,14 @@ export const HeapGrowth = Schema.Struct({ MB: Schema.Number, }); +/** An object whose retained size grew at every soak snapshot, and how it is reached. */ +export const RetainerGrowth = Schema.Struct({ + path: Schema.String, + MB: Schema.Number, + retainedMB: Schema.Number, +}); +export type RetainerGrowth = typeof RetainerGrowth.Type; + export const ServerMetrics = Schema.Struct({ meta: Schema.Record( Schema.String, @@ -170,6 +180,7 @@ export const ServerMetrics = Schema.Struct({ /** Top CPU self time (ms) and allocated MB by function, from the last run. */ profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), + soakRetainerGrowth: Schema.optional(Schema.Array(RetainerGrowth)), }); export type ServerMetrics = typeof ServerMetrics.Type; @@ -703,19 +714,24 @@ export function summarizeProfiles( return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; } +const TypeNames = Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])); export const HeapSnapshot = Schema.Struct({ snapshot: Schema.Struct({ meta: Schema.Struct({ node_fields: Schema.Array(Schema.String), - node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + node_types: TypeNames, + edge_fields: Schema.Array(Schema.String), + edge_types: TypeNames, }), }), nodes: Schema.Array(Schema.Number), + edges: Schema.Array(Schema.Number), strings: Schema.Array(Schema.String), }); +type HeapSnapshot = typeof HeapSnapshot.Type; /** Self size by constructor from a V8 heap snapshot. */ -export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { +export function heapByConstructor(snapshot: HeapSnapshot) { const fields = snapshot.snapshot.meta.node_fields; const typeNames = snapshot.snapshot.meta.node_types[0]; const types = Array.isArray(typeNames) ? typeNames : []; @@ -757,6 +773,253 @@ export function heapGrowth( .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); } +interface Retainer { + readonly retained: number; + /** The id of the node that dominates this one, none for the root. */ + readonly dominator: number | undefined; + /** Empty below `pathBytes`: such a node is only kept to compare sizes across snapshots. */ + readonly path: string; +} + +const TEXT_NODES = new Set(["string", "concatenated string", "sliced string", "regexp", "number"]); +const IDENTIFIER = /^[A-Za-z_$#][\w$]{0,48}$/; + +/** + * Retained size by node id for every node retaining at least `minBytes`, and for those retaining + * `pathBytes` the shortest strong path from the root to it. Node ids are stable within one process, so snapshots of one + * server line up. Paths name only code: string contents and non-identifier keys are left out. + */ +export function heapRetainers(snapshot: HeapSnapshot, minBytes = 16_000, pathBytes = 256_000) { + const { meta } = snapshot.snapshot; + const nodeFields = meta.node_fields.length; + const edgeFields = meta.edge_fields.length; + const list = (names: typeof meta.node_types) => { + const first = names[0]; + return Array.isArray(first) ? first : []; + }; + const nodeTypes = list(meta.node_types); + const edgeTypes = list(meta.edge_types); + const [typeAt, nameAt, idAt, sizeAt, edgeCountAt] = [ + "type", + "name", + "id", + "self_size", + "edge_count", + ].map((field) => meta.node_fields.indexOf(field)) as [number, number, number, number, number]; + const [edgeTypeAt, edgeNameAt, toAt] = ["type", "name_or_index", "to_node"].map((field) => + meta.edge_fields.indexOf(field), + ) as [number, number, number]; + const { nodes, edges, strings } = snapshot; + const count = nodes.length / nodeFields; + const firstEdge = new Uint32Array(count + 1); + for (let node = 0, offset = 0; node < count; node++) { + firstEdge[node] = offset; + offset += nodes[node * nodeFields + edgeCountAt]! * edgeFields; + firstEdge[node + 1] = offset; + } + const weak = edgeTypes.indexOf("weak"); + const shortcut = edgeTypes.indexOf("shortcut"); + const strong = (edge: number) => + edges[edge + edgeTypeAt] !== weak && edges[edge + edgeTypeAt] !== shortcut; + const target = (edge: number) => edges[edge + toAt]! / nodeFields; + + // Postorder from the root, then dominators by Cooper, Harvey and Kennedy's iteration. + const postorder = new Int32Array(count).fill(-1); + const order = new Int32Array(count); + const stack = new Int32Array(count); + const cursor = new Uint32Array(count); + const seen = new Uint8Array(count); + let depth = 0; + let visited = 0; + stack[depth++] = 0; + seen[0] = 1; + cursor[0] = firstEdge[0]!; + while (depth > 0) { + const node = stack[depth - 1]!; + if (cursor[node]! < firstEdge[node + 1]!) { + const edge = cursor[node]!; + cursor[node] = edge + edgeFields; + const next = target(edge); + if (strong(edge) && !seen[next]) { + seen[next] = 1; + cursor[next] = firstEdge[next]!; + stack[depth++] = next; + } + } else { + depth--; + postorder[node] = visited; + order[visited++] = node; + } + } + const predecessorStart = new Uint32Array(count + 1); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessorStart[target(edge) + 1]!++; + } + } + for (let node = 0; node < count; node++) predecessorStart[node + 1]! += predecessorStart[node]!; + const predecessors = new Int32Array(predecessorStart[count]!); + const fill = predecessorStart.slice(0, count); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessors[fill[target(edge)]!++] = node; + } + } + const dominator = new Int32Array(count).fill(-1); + dominator[0] = 0; + const intersect = (left: number, right: number) => { + while (left !== right) { + while (postorder[left]! < postorder[right]!) left = dominator[left]!; + while (postorder[right]! < postorder[left]!) right = dominator[right]!; + } + return left; + }; + for (let changed = true; changed;) { + changed = false; + for (let index = visited - 2; index >= 0; index--) { + const node = order[index]!; + let found = -1; + for (let at = predecessorStart[node]!; at < predecessorStart[node + 1]!; at++) { + const predecessor = predecessors[at]!; + if (dominator[predecessor] === -1) continue; + found = found === -1 ? predecessor : intersect(predecessor, found); + } + if (found !== -1 && dominator[node] !== found) { + dominator[node] = found; + changed = true; + } + } + } + const retained = new Float64Array(count); + for (let node = 0; node < count; node++) retained[node] = nodes[node * nodeFields + sizeAt]!; + for (let index = 0; index < visited - 1; index++) { + const node = order[index]!; + retained[dominator[node]!]! += retained[node]!; + } + + const parent = new Int32Array(count).fill(-1); + const parentEdge = new Int32Array(count).fill(-1); + const queue = new Int32Array(count); + let head = 0; + let tail = 0; + queue[tail++] = 0; + parent[0] = 0; + while (head < tail) { + const node = queue[head++]!; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + const next = target(edge); + if (!strong(edge) || parent[next] !== -1) continue; + parent[next] = node; + parentEdge[next] = edge; + queue[tail++] = next; + } + } + const nodeType = (node: number) => nodeTypes[nodes[node * nodeFields + typeAt]!] ?? "?"; + const label = (node: number) => { + const type = nodeType(node); + if (TEXT_NODES.has(type)) return `(${type})`; + const name = strings[nodes[node * nodeFields + nameAt]!] ?? ""; + const shown = name.length > 60 || /["'`\n\\]|:\/\/|(^|\s)\/[\w.]/.test(name) ? "?" : name; + if (type === "object") return shown; + if (type === "closure") return `${shown || "(anonymous)"}()`; + return `(${type}${shown ? ` ${shown}` : ""})`; + }; + const edgeName = (edge: number) => { + const type = edgeTypes[edges[edge + edgeTypeAt]!]; + const value = edges[edge + edgeNameAt]!; + if (type === "element" || type === "hidden") return `[${value}]`; + const name = strings[value] ?? ""; + return IDENTIFIER.test(name) ? name : ""; + }; + const pathTo = (node: number) => { + const steps: string[] = []; + for (let at = node; at !== 0 && steps.length < 40; at = parent[at]!) { + if (parent[at] === -1) return "(unreachable)"; + const from = parent[at]!; + steps.push( + from === 0 || nodeType(from) === "synthetic" + ? edgeName(parentEdge[at]!) + : `${label(from)}.${edgeName(parentEdge[at]!)}`, + ); + if (nodeType(from) === "synthetic") break; + } + const shown = steps.reverse(); + return [...(shown.length > 6 ? ["…", ...shown.slice(-6)] : shown), label(node)].join(" → "); + }; + const result = new Map(); + for (let node = 0; node < count; node++) { + if (!seen[node] || retained[node]! < minBytes) continue; + result.set(nodes[node * nodeFields + idAt]!, { + retained: retained[node]!, + dominator: node === 0 ? undefined : nodes[dominator[node]! * nodeFields + idAt]!, + path: + retained[node]! < pathBytes + ? "" + : nodeType(node) === "synthetic" + ? label(node) + : pathTo(node), + }); + } + return result; +} + +/** + * The objects whose retained size grew from each snapshot to the next, at least `minBytes` in all. + * An object is left out when a reported object it dominates holds at least 80% of its growth: of + * a chain that grew by about the same amount, only the deepest is kept, the container holding the + * growth. Nested objects whose growth differs are each reported. + */ +export function retainerGrowth( + snapshots: ReadonlyArray>, + minBytes = 1_000_000, +) { + const last = snapshots.at(-1); + if (last === undefined || snapshots.length < 2) return []; + const growth = new Map(); + for (const [id, { retained, path }] of last) { + if (path === "" || path.startsWith("(synthetic")) continue; + const sizes = [ + ...snapshots.slice(0, -1).map((snapshot) => snapshot.get(id)?.retained ?? 0), + retained, + ]; + const grewEachTime = sizes.every((size, index) => index === 0 || size > sizes[index - 1]!); + const grown = retained - sizes[0]!; + if (grewEachTime && grown >= minBytes) growth.set(id, grown); + } + const ancestors = (id: number) => { + const found: number[] = []; + for (let at = last.get(id)?.dominator; at !== undefined && found.length < 500;) { + found.push(at); + at = last.get(at)?.dominator; + } + return found; + }; + // Deepest first, so every descendant is decided before its ancestors: a row is left out + // only when a reported descendant holds at least 80% of its growth. + const heldBelow = new Map(); + const kept: Array<[number, number]> = []; + const depth = new Map([...growth.keys()].map((id) => [id, ancestors(id).length])); + const order = [...growth].toSorted((a, b) => depth.get(b[0])! - depth.get(a[0])!); + for (const [id, grown] of order) { + if ((heldBelow.get(id) ?? 0) >= grown * 0.8) continue; + kept.push([id, grown]); + for (const ancestor of ancestors(id)) { + heldBelow.set(ancestor, Math.max(heldBelow.get(ancestor) ?? 0, grown)); + } + } + const rows: RetainerGrowth[] = kept + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([id, grown]) => ({ + path: last.get(id)!.path, + MB: round(grown / 1e6, 2), + retainedMB: round(last.get(id)!.retained / 1e6, 2), + })); + return rows; +} + const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String)); const spellings: ReadonlyArray<(path: string) => string> = [ (path) => path, diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 6597e9297514b..9baf6a86369a2 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -9,6 +9,7 @@ import { activityRenewalMissed, describeFailure, heapGrowth, + heapRetainers, loadWarnings, nextActivityReport, noiseReport, @@ -16,6 +17,7 @@ import { parsePsCpuTime, profileMismatch, parseRunSelection, + retainerGrowth, pathRewrites, pathSpellings, ServerMetrics, @@ -467,6 +469,87 @@ describe("heapGrowth", () => { }); }); +describe("heapRetainers", () => { + it("sums what each object alone keeps alive and names only code on the way to it", () => { + // root → Holder.cache → Map → [0] array → [0] string; Holder also points at the string weakly. + const node = (type: number, name: number, id: number, size: number, edges: number) => [ + type, + name, + id, + size, + edges, + ]; + const retainers = heapRetainers( + { + snapshot: { + meta: { + node_fields: ["type", "name", "id", "self_size", "edge_count"], + node_types: [["synthetic", "object", "array", "string"]], + edge_fields: ["type", "name_or_index", "to_node"], + edge_types: [["property", "element", "weak", "hidden"]], + }, + }, + nodes: [ + ...node(0, 4, 1, 0, 1), + ...node(1, 1, 3, 100, 2), + ...node(1, 2, 5, 50, 1), + ...node(2, 0, 7, 1_000, 1), + ...node(3, 5, 9, 500, 0), + ], + edges: [0, 6, 5, 0, 3, 10, 2, 0, 20, 3, 0, 15, 1, 0, 20], + strings: ["", "Holder", "Map", "cache", "(GC roots)", "a secret", "holder"], + }, + 0, + 0, + ); + expect(retainers.get(5)).toEqual({ + retained: 1_550, + dominator: 3, + path: "holder → Holder.cache → Map", + }); + expect(retainers.get(3)?.retained).toBe(1_650); + expect(retainers.get(9)?.path).toBe("holder → Holder.cache → Map.[0] → (array).[0] → (string)"); + }); +}); + +describe("retainerGrowth", () => { + const at = (sizes: Record) => + new Map( + Object.entries(sizes).map(([id, retained]) => [ + Number(id), + { retained, dominator: Number(id) === 3 ? undefined : 3, path: `node ${id}` }, + ]), + ); + it("reports the deepest object holding the growth, and only growth at every snapshot", () => { + const growth = retainerGrowth([ + at({ 3: 1_000_000, 5: 900_000, 7: 2_000_000 }), + at({ 3: 3_000_000, 5: 2_900_000, 7: 4_000_000 }), + at({ 3: 5_000_000, 5: 4_900_000, 7: 3_500_000 }), + ]); + expect(growth).toEqual([{ path: "node 5", MB: 4, retainedMB: 4.9 }]); + }); + it("keeps an ancestor its reported descendant does not account for", () => { + // A chain 1 → 2 → 3 growing by 7, 6 and 5 MB, and 4 under 1 growing by 2 MB. + const chain = (scale: number) => + new Map( + [ + [1, 7, undefined], + [2, 6, 1], + [3, 5, 2], + [4, 2, 1], + ].map(([id, mb, dominator]) => [ + id!, + { retained: (10 + mb! * scale) * 1e6, dominator, path: `node ${id}` }, + ]), + ); + expect(retainerGrowth([chain(0), chain(0.5), chain(1)]).map(({ path }) => path)).toEqual([ + "node 1", + "node 3", + "node 4", + ]); + }); +}); + describe("slope", () => { it("fits the cost per thread", () => { const points: Array = [ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 9fa06fcfdea5c..6f553bcea38c1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -57,6 +57,7 @@ import * as Scope from "effect/Scope"; import * as Socket from "effect/socket/Socket"; import { run } from "./scenarios/shell.ts"; +import { serveFakeGitHub, type FakeGitHub } from "./server-metrics-forge.ts"; import { compareMetrics, CpuProfile, @@ -65,6 +66,9 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + heapRetainers, + retainerGrowth, + type RetainerGrowth, competingBetween, loadWarnings, noiseReport, @@ -135,6 +139,9 @@ const RECONNECT_CLIENTS = 3; const RECONNECT_THREADS = 10; /** Clients that drop and reconnect at once in the opt-in storm, each holding one thread. */ const STORM_CLIENTS = 20; +/** Threads the soak keeps open; every few turns the oldest is replaced. */ +const SOAK_THREADS = 10; +const SOAK_CHURN_TURNS = 4; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; const LoopStats = Schema.Struct({ @@ -523,7 +530,8 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); const json = chunks.join(""); chunks.length = 0; - return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + const snapshot = yield* decodeJson(HeapSnapshot)(json); + return { byConstructor: heapByConstructor(snapshot), retainers: heapRetainers(snapshot) }; }), }; }); @@ -582,7 +590,8 @@ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: n } } else if (platform === "darwin") { const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); - for (const line of Option.getOrElse(table, () => "").split("\n")) { + if (Option.isNone(table)) return yield* new MetricsError({ message: "ps listed no processes" }); + for (const line of table.value.split("\n")) { const [child, parent] = line.trim().split(/\s+/).map(Number); if (child && parent) add(child, parent); } @@ -611,6 +620,8 @@ interface Environment { interface ServerOptions { /** A base dir `migrate-dev-db` prepared; the server starts on a copy of its database. */ readonly seed?: string; + /** A fake GitHub host the project's origin points at. */ + readonly forge?: FakeGitHub; } /** Transcript text: paths there are words in a conversation, which the server never acts on. */ @@ -834,12 +845,14 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( yield* fs.makeDirectory(project); yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); for (const args of [ - ["init", "-q", "-b", "main"], + // Loose refs on purpose: the soak writes them as files, which a reftable store would ignore. + ["-c", "init.defaultRefFormat=files", "init", "-q", "-b", "main"], ["add", "."], ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], ]) { yield* run("git", args, { cwd: project }); } + if (options.forge !== undefined) yield* options.forge.setupProject(project); const baseDir = path.join(directory, "base"); // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); @@ -872,6 +885,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", OTEL_SDK_DISABLED: "true", T3CODE_DEV_SEED: "0", + ...options.forge?.env, }; const port = yield* freePort; const started = yield* nowMs; @@ -1025,6 +1039,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( return { readyMs, + pid, startedAt: started, origin: `http://127.0.0.1:${port}`, /** The seeded projects' clones; none without a seed. */ @@ -1247,6 +1262,8 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( threadId: string, item: OrchestrationV2ThreadStreamItem, ) => Effect.Effect = () => Effect.void, + /** How long the server may go silent before the client drops the connection or a report fails. */ + pingTimeout?: Duration.Input, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1265,7 +1282,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(ticketBody); const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( + RpcClient.layerProtocolSocket(pingTimeout === undefined ? {} : { pingTimeout }).pipe( Layer.provide( Socket.layerWebSocket( `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, @@ -1279,6 +1296,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( // client costs, so the first such loss is kept for `healthy` to report. const lost = yield* Ref.make(undefined); const ready = Effect.fn("serverMetrics.subscription")(function* ( + name: string, stream: Stream.Stream, isReady: (item: A) => boolean, onItem: (item: A) => Effect.Effect = () => Effect.void, @@ -1294,8 +1312,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), ), ), - Effect.andThen(lose("a subscription ended")), - Effect.catchCause(() => lose("a subscription failed")), + Effect.andThen(lose(`the ${name} subscription ended`)), + Effect.catchCause((cause) => + lose(`the ${name} subscription failed: ${describeFailure(Cause.squash(cause))}`), + ), Effect.forkScoped, ); return Deferred.await(synchronized); @@ -1317,7 +1337,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }).pipe( // A server that keeps the socket open but never answers would otherwise hang the scenario. Effect.timeoutOrElse({ - duration: Duration.seconds(15), + duration: pingTimeout ?? Duration.seconds(15), orElse: () => new MetricsError({ message: "an activity report got no answer" }), }), ); @@ -1346,6 +1366,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const synchronized = (item: { readonly kind: string }) => item.kind === "synchronized"; const waits = [ yield* ready( + "shell", client["orchestration.subscribeShell"]({ requestCompletionMarker: true, omitIdleSubagents: true, @@ -1353,9 +1374,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), synchronized, ), - yield* ready(client.subscribeVcsStatus({ cwd: server.project }), () => true), + yield* ready("VCS status", client.subscribeVcsStatus({ cwd: server.project }), () => true), ...(yield* Effect.forEach(threadIds, (threadId) => ready( + `thread ${threadId}`, client["orchestration.subscribeThread"]({ threadId: ThreadId.make(threadId), requestCompletionMarker: true, @@ -1390,6 +1412,14 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( creationSource: "web", dispatchMode: { type: "start_immediately" }, }), + rpc: client, + /** Archives or deletes a thread the way the sidebar does. */ + retire: (type: "thread.archive" | "thread.delete", threadId: string, commandId: string) => + client["orchestration.dispatchCommand"]({ + type, + commandId: CommandId.make(commandId), + threadId: ThreadId.make(threadId), + }), /** Fails if any of this client's subscriptions or reports was lost since it attached. */ healthy: Effect.flatMap(Ref.get(lost), (message) => message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), @@ -1640,6 +1670,7 @@ interface RunOptions { /** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; + const platform = yield* HostProcess.Platform; const path = yield* Path.Path; const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); @@ -1658,6 +1689,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; const profiles: Record = {}; let soakHeapGrowth: ReturnType | undefined; + let soakRetainerGrowth: ReadonlyArray | undefined; const withServer = ( name: string, body: (server: Server) => Effect.Effect, @@ -1916,50 +1948,165 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption ); } if (options.soakMinutes > 0) { - yield* withServer("soak", (server) => - Effect.gen(function* () { - const threads = yield* openThreads(server, 0, 10); - yield* Effect.sleep(Duration.seconds(60)); - // The snapshot inflates RSS once, so the slopes start after it. - const before = yield* server.snapshot; - const samples: Array<{ hours: number; window: Window }> = []; - const start = yield* nowMs; - const elapsed = Effect.map(nowMs, (now) => now - start); - const takeSample = Effect.gen(function* () { - samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); - }); - let nextSample = 0; - for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { - if ((yield* elapsed) >= nextSample) { - yield* takeSample; - nextSample += 120_000; + const forge = yield* serveFakeGitHub(); + yield* withServer( + "soak", + (server) => + Effect.gen(function* () { + let threads = yield* openThreads(server, 0, SOAK_THREADS); + // A busy repository under a web client: thousands of loose remote-tracking refs, more + // arriving every turn as fetches and agent branches add them, so caches keyed by ref + // state churn the way they do on a real checkout. + const head = (yield* run("git", ["rev-parse", "HEAD"], { cwd: server.project })).stdout; + // Under a remote with no config, so no fetch (or a host's fetch.prune) can delete them. + const remotes = path.join(server.project, ".git", "refs", "remotes", "mirror"); + yield* fs.makeDirectory(remotes, { recursive: true }); + yield* Effect.forEach( + Array.from({ length: 3_000 }, (_, index) => index), + (index) => fs.writeFileString(path.join(remotes, `bench-${index}`), head), + { concurrency: 64, discard: true }, + ); + // A reftable store (GIT_DEFAULT_REF_FORMAT can still pick one) ignores refs written as files. + const listed = yield* run( + "git", + ["for-each-ref", "--count=3000", "refs/remotes/mirror/"], + { + cwd: server.project, + }, + ); + if (listed.stdout.trim().split("\n").length < 3_000) { + return yield* new MetricsError({ message: "git does not see the soak's loose refs" }); } - // Round robin, so two soaks send the same turns to the same threads. - const threadId = threads[turn % threads.length]; - if (threadId === undefined) - return yield* new MetricsError({ message: "no soak threads" }); - const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); - if (sent.exitCode !== 0) { - return yield* new MetricsError({ - message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, - }); + const token = yield* server.issueToken; + // The client gets a scope of its own so each churn cycle can drop it and reconnect. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + // Each client also polls pull requests the way the sidebar and an open PR do. + const connect = Effect.fn("serverMetrics.soakClient")(function* ( + threadIds: ReadonlyArray, + ) { + // A heap snapshot pauses the server for longer than the default 5 s ping timeout. + const client = yield* attachClient( + server, + token, + threadIds, + undefined, + Duration.minutes(2), + ); + yield* forge + .pollLikeWebClient({ + list: client.rpc["pullRequests.list"], + summary: client.rpc["pullRequests.summary"], + checks: client.rpc["pullRequests.checks"], + }) + .pipe(Effect.forkScoped); + return client; + }); + let scope = yield* clientScope; + let client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* Effect.sleep(Duration.seconds(60)); + // The first snapshot inflates RSS once, so the slopes start after it. + const snapshots = [yield* server.snapshot]; + const samples: Array<{ + hours: number; + window: Window; + rssMB: number; + processes: number | null; + }> = []; + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); + let snapshotRssMB = 0; + const takeSample = Effect.gen(function* () { + const hours = (yield* elapsed) / 3_600_000; + const window = yield* server.measure(5); + // Windows lists no descendants, which is not the same as having none. + const processes = + platform === "win32" + ? null + : yield* descendantsOf(server.pid).pipe( + Effect.map((found) => found.length), + // Unknown, not zero: a failed probe leaves the process slope out. + Effect.orElseSucceed(() => null), + ); + samples.push({ hours, window, rssMB: window.rssMB - snapshotRssMB, processes }); + yield* Console.error( + `soak ${round(hours * 60)} min: heap ${window.heapAfterGcMB} MB, RSS ${window.rssMB} MB${processes === null ? "" : `, ${processes} child processes`}`, + ); + }); + let nextSample = 0; + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if (snapshots.length === 1 && (yield* elapsed) >= options.soakMinutes * 30_000) { + // RSS the snapshot itself added stays off the slope: later samples drop the step. + const before = (yield* sample(server.pid)).rss; + snapshots.push(yield* server.snapshot); + snapshotRssMB = Math.max(0, ((yield* sample(server.pid)).rss - before) / 1e6); + } + if ((yield* elapsed) >= nextSample) { + yield* takeSample; + nextSample += 120_000; + } + // Users come and go: a new thread replaces the oldest, which is archived and deleted, + // and the client reconnects, so state kept per thread or per connection must be freed. + if (turn > 0 && turn % SOAK_CHURN_TURNS === 0) { + yield* client.healthy; + const [fresh] = yield* openThreads(server, SOAK_THREADS + turn, 1); + const [oldest, ...rest] = threads; + if (fresh === undefined || oldest === undefined) + return yield* new MetricsError({ message: "no soak thread to churn" }); + threads = [...rest, fresh]; + const retiring = client; + yield* Scope.close(scope, Exit.void); + // A loss while the replacement thread started still counts against the run. + yield* retiring.healthy.pipe( + Effect.mapError( + (error) => new MetricsError({ message: `the retired client: ${error.message}` }), + ), + ); + scope = yield* clientScope; + client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* forge.advanceRemote; + yield* client.retire("thread.archive", oldest, `bench-archive-${turn}`); + yield* client.retire("thread.delete", oldest, `bench-delete-${turn}`); + } + // Round robin, so two soaks send the same turns to the same threads. + const threadId = threads[turn % threads.length]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + yield* fs.writeFileString(path.join(remotes, `soak-${turn}`), head); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + yield* Effect.sleep( + Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed))), + ); } - yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); - } - yield* takeSample; - const perHour = (pick: (window: Window) => number) => - round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); - measured.soak = { - minutes: options.soakMinutes, - heapMBPerHour: perHour((window) => window.heapAfterGcMB), - rssMBPerHour: perHour((window) => window.rssMB), - }; - soakHeapGrowth = heapGrowth(before, yield* server.snapshot); - }), + yield* takeSample; + yield* client.healthy; + yield* forge.checkFetched(server.project); + const perHour = (pick: (sample: (typeof samples)[number]) => number) => + round(slope(samples.map((sample) => [sample.hours, pick(sample)]))); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: perHour(({ window }) => window.heapAfterGcMB), + rssMBPerHour: perHour(({ rssMB }) => rssMB), + ...(samples.some(({ processes }) => processes === null) + ? {} + : { childProcessesPerHour: perHour(({ processes }) => processes ?? 0) }), + }; + snapshots.push(yield* server.snapshot); + soakHeapGrowth = heapGrowth(snapshots[0]!.byConstructor, snapshots.at(-1)!.byConstructor); + soakRetainerGrowth = retainerGrowth(snapshots.map((snapshot) => snapshot.retainers)); + }), + { forge }, ); + yield* forge.verify; } measured.machine = yield* machine; - return { measured: measured as Measured, profiles, soakHeapGrowth }; + return { measured: measured as Measured, profiles, soakHeapGrowth, soakRetainerGrowth }; }, Effect.scoped); const machineLoad = Effect.gen(function* () { @@ -2277,7 +2424,7 @@ const runFlags = { soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( - "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + "Minutes of soak: 10 threads under one web client, a short turn every 30 s in a project with 3,000 loose remote refs that gains one per turn. From minute 2, every 2 minutes a new thread replaces the oldest (archived, then deleted), the client reconnects and a fake GitHub remote gains a commit; the client polls that host's pull requests and checks. Reports heap, RSS and child-process slopes per hour, the constructors that grew, and the objects whose retained size grew at each of three snapshots with the path that holds them. Needs openssl on PATH and Node 24.5 or later. Runs alone unless --only names more.", ), Flag.withDefault(0), ), @@ -2381,6 +2528,7 @@ const runCommand = Command.make( runs, ...(last ? { profiles: last.profiles } : {}), ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + ...(last?.soakRetainerGrowth ? { soakRetainerGrowth: last.soakRetainerGrowth } : {}), }); }, Effect.scoped), ).pipe( From 8d9b39edc540fe61dba927681287e58b3db42afc Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:40:14 +0100 Subject: [PATCH 281/288] fix(mobile): long branch names in the Git menu no longer show a broken character (#41861) Co-authored-by: Julius Marminge --- .../threads/ThreadGitControls.logic.test.ts | 9 ++++++ .../threads/ThreadGitControls.logic.ts | 17 +++++++++++ .../features/threads/ThreadGitControls.tsx | 15 +--------- ...-menu-branch-keeps-whole-characters.e2e.ts | 28 +++++++++++++++++++ 4 files changed, 55 insertions(+), 14 deletions(-) create mode 100644 apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts create mode 100644 apps/mobile/src/features/threads/ThreadGitControls.logic.ts create mode 100644 scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts new file mode 100644 index 0000000000000..1538540949880 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vite-plus/test"; + +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; + +it("keeps emoji whole at both cuts of a long branch name", () => { + expect(compactMenuBranchLabel("feature/abc😀-long-branch-name-😀-for-menus")).toBe( + "feature/abc…-for-menus", + ); +}); diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts new file mode 100644 index 0000000000000..a3441835b5951 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts @@ -0,0 +1,17 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +function truncateMiddle(value: string, maxLength: number): string { + if (value.length <= maxLength) { + return value; + } + + const headLength = Math.ceil((maxLength - 1) / 2); + const tailStart = value.length - Math.floor((maxLength - 1) / 2); + const headEnd = splitsSurrogatePair(value, headLength) ? headLength - 1 : headLength; + const tailFrom = splitsSurrogatePair(value, tailStart) ? tailStart + 1 : tailStart; + return `${value.slice(0, headEnd)}…${value.slice(tailFrom)}`; +} + +export function compactMenuBranchLabel(branch: string): string { + return truncateMiddle(branch, 24); +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 1a36d6b350e4a..9e7ab388ccee4 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -30,20 +30,7 @@ import { type TerminalMenuSession, } from "../terminal/terminalMenu"; import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy"; - -function truncateMiddle(value: string, maxLength: number): string { - if (value.length <= maxLength) { - return value; - } - - const headLength = Math.ceil((maxLength - 1) / 2); - const tailLength = Math.floor((maxLength - 1) / 2); - return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`; -} - -function compactMenuBranchLabel(branch: string): string { - return truncateMiddle(branch, 24); -} +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string { if (!gitStatus) { diff --git a/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts b/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts new file mode 100644 index 0000000000000..088b9b00838c2 --- /dev/null +++ b/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts @@ -0,0 +1,28 @@ +import { expect } from "e2e"; + +import { run } from "./shell.ts"; +import { runPromise } from "./t3.ts"; +import { IOS, test } from "./t3-mobile.ts"; + +// The Git menu shows 12 units, "…" and the last 11; each emoji straddles one cut. +const BRANCH = "feature/abc😀-long-branch-name-😀-for-menus"; + +test( + "The Git menu's branch title keeps whole characters at both cuts", + IOS, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + await runPromise(run("git", ["checkout", "--quiet", "-b", BRANCH], { cwd: project })); + await t3.thread({ project, title: "Branch work", messages: ["first"] }); + // A local simulator keeps the last run's pairing. + await app.clearState().catch(() => {}); + await t3.open(); + + await screen.getByText("Branch work", { exact: false }).first().tap({ timeout: 120_000 }); + await screen.getByRole("button", "Git controls").tap({ timeout: 60_000 }); + const title = screen.getByText("feature/abc", { exact: false }).first(); + await title.waitFor({ timeout: 30_000 }); + await app.screenshot("git-menu"); + await expect(title).toHaveText("feature/abc…-for-menus, Clean"); + }, +); From 3d9a14d4da9b17f2fe10c985103518af66727d84 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:42:18 -0600 Subject: [PATCH 282/288] fix(web): IME keys no longer trigger or close the prompt stash menu (#41875) Co-authored-by: Julius Marminge --- .../chat/ComposerStashMenu.browser.test.tsx | 27 +++++++++++++++++++ .../src/components/chat/ComposerStashMenu.tsx | 1 + 2 files changed, 28 insertions(+) diff --git a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx index 79e43bba74314..9b23e1360f201 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx @@ -108,3 +108,30 @@ it("leaves dialog, unrelated input and question button shortcuts alone while the expect(stash().element().textContent).toContain("second prompt"); await expect.element(editor()).toHaveValue("Unsent draft"); }); + +it("leaves IME composition keys in the composer alone while the stash is open", async () => { + for (const composing of [{ isComposing: true }, { keyCode: 229 }]) { + for (const key of ["ArrowDown", "Enter", "Escape"]) { + await using _screen = await render(); + const textarea = editor().element(); + await focus(textarea); + const event = new KeyboardEvent("keydown", { + key, + ...composing, + bubbles: true, + cancelable: true, + }); + await act(async () => { + textarea.dispatchEvent(event); + }); + expect(event.defaultPrevented, `${key} ${JSON.stringify(composing)}`).toBe(false); + await expect.element(stash()).toBeInTheDocument(); + await expect.element(editor()).toHaveValue("Unsent draft"); + } + } + + await using _control = await render(); + await focus(editor().element()); + await press("{Enter}"); + await expect.element(editor()).toHaveValue("first prompt"); +}); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 46e3fec307bf1..8aa139f84efcf 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -89,6 +89,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { }); const handleKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) return; const drawer = drawerRef.current; if (!drawer) return; const target = event.target; From 8a9e8d12a86fd5640a609ea277afba948a9470dd Mon Sep 17 00:00:00 2001 From: Omar Espinosa <77650361+OmarAlex24@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:42:31 -0600 Subject: [PATCH 283/288] fix(acp-registry): models show their own reasoning levels before their first session (#41850) Co-authored-by: Julius Marminge --- .../src/server/driver.test.ts | 277 ++++++++++++++++++ .../src/server/driver.ts | 228 +++++++++----- .../src/server/learnedModelOptions.ts | 231 +++++++++++++++ .../provider-acp-registry/src/server/probe.ts | 125 +++++++- 4 files changed, 768 insertions(+), 93 deletions(-) create mode 100644 packages/provider-acp-registry/src/server/learnedModelOptions.ts diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 684eb21d7456b..564486b9d8269 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { AcpRegistryOperationError, + DEFAULT_SERVER_SETTINGS, ProviderInstanceId, type ServerProvider, } from "@t3tools/contracts"; @@ -19,6 +20,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -949,6 +951,61 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); `; +// Reports `effort` levels for its current model only and logs each model switch. +const perModelEffortAgentSource = ` +import { appendFileSync, readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const [logPath, modelsPath] = process.argv.slice(2); +const levels = JSON.parse(readFileSync(modelsPath, "utf8")); +const modelIds = Object.keys(levels); +let current = modelIds[0]; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const configOptions = () => [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: current, + options: modelIds.map((value) => ({ value, name: value })), + }, + ...(levels[current] === null + ? [] + : [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[current][0], + options: levels[current].map((value) => ({ value, name: value })), + }, + ]), +]; +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method, params } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } }); + } else if (method === "session/new") { + send({ id, result: { sessionId: "probe-session", configOptions: configOptions() } }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + } else if (method === "session/set_config_option" && params.configId === "model") { + appendFileSync(logPath, params.value + "\\n"); + current = params.value; + send({ id, result: { configOptions: configOptions() } }); + } else { + send({ id, result: {} }); + } +}); +`; + const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), Layer.provideMerge(IdAllocator.layer), @@ -1188,4 +1245,224 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); }), ); + + const makePerModelEffortAgent = Effect.fn("makePerModelEffortAgent")(function* ( + levels: Readonly | null>>, + ) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); + const agentPath = path.join(directory, "agent.mjs"); + const logPath = path.join(directory, "switches.log"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, perModelEffortAgentSource); + yield* fileSystem.writeFileString(logPath, ""); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(levels)); + return { + spawn: { command: process.execPath, args: [agentPath, logPath, modelsPath] }, + modelSwitches: fileSystem + .readFileString(logPath) + .pipe(Effect.map((log) => log.split("\n").filter((line) => line.length > 0))), + }; + }); + const createRegistryInstance = ( + instanceId: ProviderInstanceId, + spawn: { readonly command: string; readonly args: ReadonlyArray }, + version: string, + ) => + AcpRegistryDriver.create({ + instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version, + distribution: "npx", + }), + resolve: () => Effect.succeed({ distribution: "npx" as const, spawn }), + }), + ); + const effortLevels = (snapshot: ServerProvider) => + snapshot.models + .map((model) => { + const effort = model.capabilities?.optionDescriptors?.find( + (option) => option.id === "effort", + ); + const levels = effort?.type === "select" ? effort.options.map((option) => option.id) : []; + return `${model.slug}:${levels.join("+")}`; + }) + .join(); + const refreshUntilEffortLevels = ( + instance: Effect.Success>, + expected: string, + ) => + Effect.gen(function* () { + const reached = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === expected), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(reached); + }); + + // A session's report: the model select plus the current model's own effort levels. + const liveSession = ( + models: ReadonlyArray, + model: string, + levels: ReadonlyArray, + ) => + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: model, + options: models.map((value) => ({ value, name: value })), + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[0]!, + options: levels.map((value) => ({ value, name: value })), + }, + ]); + + it.effect("reads each visible model's own reasoning levels before its first session", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_discovery"); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + favorites: [{ provider: instanceId, model: "fav" }], + providerModelPreferences: { [instanceId]: { hiddenModels: ["hidden"], modelOrder: [] } }, + }); + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + plain: null, + other: ["low", "high"], + hidden: ["low"], + fav: ["none", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + "default:medium+high,plain:,other:low+high,hidden:,fav:none+max", + ); + // Favorites first, hidden models skipped, then the agent's own model restored. + expect(yield* agent.modelSwitches).toEqual(["fav", "plain", "other", "default"]); + + // What a live session reports for a model outranks what discovery read for it. + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const models = ["default", "plain", "other", "hidden", "fav"]; + const live = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + effortLevels(snapshot) === "default:high,plain:,other:xhigh,hidden:,fav:none+max", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + expect(Option.isSome(yield* Fiber.join(live))).toBe(true); + }), + ); + + it.effect("reads every model of a catalog larger than one discovery batch in one refresh", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_large_catalog"); + const others = Array.from({ length: 30 }, (_, index) => `model-${index}`); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + providerModelPreferences: { + [instanceId]: { hiddenModels: [], modelOrder: [...others, "opus"] }, + }, + }); + const agent = yield* makePerModelEffortAgent({ + sonnet: ["medium"], + ...Object.fromEntries(others.map((slug) => [slug, ["low"]])), + opus: ["high", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + ["sonnet:medium", ...others.map((slug) => `${slug}:low`), "opus:high+max"].join(), + ); + expect(yield* agent.modelSwitches).toEqual([...others, "opus", "sonnet"]); + }), + ); + + it.effect("keeps discovered reasoning levels across restarts until the agent updates", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_persisted"); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + other: ["low", "high"], + }); + const runInstance = ( + version: string, + expected: string, + then: ( + instance: Effect.Success>, + ) => Effect.Effect = () => Effect.void, + ) => + Effect.scoped( + createRegistryInstance(instanceId, agent.spawn, version).pipe( + Effect.tap((instance) => refreshUntilEffortLevels(instance, expected)), + Effect.flatMap(then), + ), + ); + + yield* runInstance("1.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // Reused after a restart; a live session then replaces the stored levels. + yield* runInstance("1.0.0", "default:medium+high,other:low+high", (instance) => + Effect.gen(function* () { + const replaced = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === "default:high,other:xhigh"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const models = ["default", "other"]; + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + yield* Fiber.join(replaced); + // The session ends with this instance; only the stored levels remain. + yield* coordinator.clearLiveConfiguration(instanceId); + }), + ); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + yield* runInstance("1.0.0", "default:medium+high,other:xhigh"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // An agent update makes every stored level stale. + yield* runInstance("2.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default", "other", "default"]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 46d8ed3219aa4..33c5ab9a46663 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -53,6 +53,7 @@ import { type AcpRegistryConfigurationProbe, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, + type AcpRegistryModelDiscovery, deleteAcpRegistrySession, disableAcpRegistryProvider, listAcpRegistrySessions, @@ -65,6 +66,12 @@ import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistryAuth from "./auth.ts"; import * as AcpRegistryAuthenticationState from "./authenticationState.ts"; +import { + acpRegistryCurrentModelOptions, + acpRegistryModelsToDiscover, + makeAcpRegistryLearnedModelOptionsStore, + withAcpRegistryLearnedModelOptions, +} from "./learnedModelOptions.ts"; const DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const decodeSettings = Schema.decodeSync(AcpRegistrySettings); @@ -518,6 +525,9 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check readonly settings: AcpRegistrySettings; readonly cwd: string; readonly environment: NodeJS.ProcessEnv; + readonly modelDiscovery?: Omit & { + readonly onProbed: (provider: ServerProvider) => Effect.Effect>; + }; }, probeConfiguration: AcpRegistryConfigurationProbe, ): Effect.fn.Return { @@ -544,12 +554,25 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check inspection: inspected.success, }); } + const inspection = inspected.success; + const modelDiscovery = input.modelDiscovery; const probed = yield* Effect.result( probeConfiguration({ instanceId: input.instanceId, settings: input.settings, cwd: input.cwd, environment: providerProbeEnvironment(input.environment), + ...(modelDiscovery === undefined + ? {} + : { + modelDiscovery: { + onProbed: (probe) => + modelDiscovery.onProbed( + buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection, probe }), + ), + onDiscovered: modelDiscovery.onDiscovered, + }, + }), }), ); return Result.isFailure(probed) @@ -688,26 +711,31 @@ export const AcpRegistryDriver: ProviderDriver>([]); - const applyLiveConfiguration = ( + // reported by sessions and probe discovery are kept here and on disk. + const learnedModelOptions = yield* makeAcpRegistryLearnedModelOptionsStore({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId, + settings: effectiveConfig, + }); + const applyLiveConfiguration = Effect.fn("AcpRegistryDriver.applyLiveConfiguration")(function* ( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, - ) => - Ref.modify(learnedModels, (learned) => { - const next = applyAcpRegistryLiveConfiguration( - provider, - configuration, - effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - ); - return [next, next.models === provider.models ? learned : next.models]; - }); - const clearLearnedModels = Ref.set(learnedModels, []); + ) { + const reported = acpRegistryCurrentModelOptions(configuration); + if (reported !== undefined) { + yield* learnedModelOptions.learn(reported.modelId, reported.options, "live"); + } + return withAcpRegistryLearnedModelOptions( + applyAcpRegistryLiveConfiguration(provider, configuration, effectiveConfig.customModels), + yield* learnedModelOptions.get, + ); + }); + const clearLearnedModels = learnedModelOptions.clear; const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, ) { if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); + if (input.installed) yield* learnedModelOptions.setVersion(input.version); const provider = input.enabled && input.installed && @@ -715,26 +743,22 @@ export const AcpRegistryDriver: ProviderDriver { - const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(configuration, { - onNone: () => Effect.succeed(withCommands), - onSome: (liveConfiguration) => - applyLiveConfiguration(withCommands, liveConfiguration), - }).pipe( - Effect.map((withConfiguration) => - applyAcpRegistryUrlAuthAction(withConfiguration, authAction), - ), - ); - }), - ); + if (Option.isNone(runtimeCoordinator)) { + return withAcpRegistryLearnedModelOptions(provider, yield* learnedModelOptions.get); + } + const coordinator = runtimeCoordinator.value; + const withCommands = applyAcpRegistryAvailableCommands( + provider, + yield* coordinator.getAvailableCommands(instanceId), + ); + const configuration = yield* coordinator.getLiveConfiguration(instanceId); + const withConfiguration = Option.isSome(configuration) + ? yield* applyLiveConfiguration(withCommands, configuration.value) + : withAcpRegistryLearnedModelOptions(withCommands, yield* learnedModelOptions.get); + return applyAcpRegistryUrlAuthAction( + withConfiguration, + yield* coordinator.getUrlAuthAction(instanceId), + ); }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. const reportedLocalVersion = yield* Ref.make(null); @@ -751,19 +775,48 @@ export const AcpRegistryDriver: ProviderDriver
-<<<<<<< origin/main - {ctx.onOpenTurnDiff ? ( - - ) : null} -======= ->>>>>>> upstream/main {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index dd8f0ceda2aaf..e7535d11a30b0 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -381,14 +381,9 @@ export default function PdfViewer(props: { top: pdfRestoredScrollTop(ratios, width, initialView, initialView.width), left: initialView.left, }); -<<<<<<< origin/main restored.current = { top: node.scrollTop, left: node.scrollLeft }; - setScrollTop(node.scrollTop); - saveView(node, false); -======= setScrolled({ top: node.scrollTop, width, pdf }); - saveView(node); ->>>>>>> upstream/main + saveView(node, false); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits. useLayoutEffect(() => { @@ -583,9 +578,8 @@ export default function PdfViewer(props: { tabIndex={0} className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40" onScroll={(event) => { -<<<<<<< origin/main const top = event.currentTarget.scrollTop; - setScrollTop(top); + setScrolled({ top, width, pdf }); // The restore's own scroll event lands where the restore put the view. const echo = restored.current; restored.current = null; @@ -593,10 +587,6 @@ export default function PdfViewer(props: { event.currentTarget, echo?.top !== top || echo.left !== event.currentTarget.scrollLeft, ); -======= - setScrolled({ top: event.currentTarget.scrollTop, width, pdf }); - saveView(event.currentTarget); ->>>>>>> upstream/main }} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "f") { diff --git a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx index af72174a28980..d858608526063 100644 --- a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx +++ b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx @@ -110,7 +110,6 @@ function props(): Omit { turnDiffSummaries: [], runs: [], routeThreadKey: `environment-local:display-mode-${Math.random().toString(36).slice(2)}`, - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts index a0b8761592f29..0e20c9db867a7 100644 --- a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts +++ b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts @@ -34,6 +34,7 @@ const menuState: ThreadActionMenuState = { canSnoozeNow: true, isRegeneratingTitle: false, isRunning: false, + hasCompletedRun: true, supports: { settlement: true, autoSettleOptOut: true, diff --git a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx index fb4654c66c175..8840c1e4dcb0a 100644 --- a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx +++ b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx @@ -102,7 +102,6 @@ describe("whileIdle compaction in the timeline", () => { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-while-idle" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/singleTilde.browser.test.tsx b/apps/web/src/fork/singleTilde.browser.test.tsx index cf415cbc7404e..77511f698447e 100644 --- a/apps/web/src/fork/singleTilde.browser.test.tsx +++ b/apps/web/src/fork/singleTilde.browser.test.tsx @@ -133,7 +133,6 @@ function singleTildeTimeline(stage: Stage) { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-single-tilde" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/timelineReaderLine.browser.test.tsx b/apps/web/src/fork/timelineReaderLine.browser.test.tsx index 4cbbfbd8de2cd..8f00b86785fac 100644 --- a/apps/web/src/fork/timelineReaderLine.browser.test.tsx +++ b/apps/web/src/fork/timelineReaderLine.browser.test.tsx @@ -68,7 +68,6 @@ function props(listRef: TimelineProps["listRef"]): Omit {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/docs/internals/overview.md b/docs/internals/overview.md deleted file mode 100644 index e10a977a6bc3a..0000000000000 --- a/docs/internals/overview.md +++ /dev/null @@ -1,163 +0,0 @@ -# Architecture - -T3 Code keeps execution in the environment that owns the workspace. Web, desktop, and mobile -clients control it over authenticated RPC. A remote client must never substitute its own filesystem, -provider credentials, or machine state for the environment's. The desktop app bundles a server, -but its renderer follows the same boundary. - -## Ownership boundaries - -Provider processes, terminals, Git, and project files belong to the server. Shared connection and -domain state belongs in `packages/client-runtime`; clients supply platform services and UI. -Keeping that logic shared prevents reconnect and multi-environment behavior from diverging between -web and mobile. See [connection runtime](./connection-runtime.md) and -[remote environments](./remote.md). - -The [RPC contract](../../packages/contracts/src/rpc.ts) is the boundary between independently -versioned clients and servers. Subscriptions send the state a client needs, so a client viewing one -thread does not pay for every thread's history. Authentication of a socket does not authorize every -method on it. See [environment auth](./environment-auth.md). - -### Pull request linking compatibility - -Every protocol-2 environment advertises `threadPullRequests`. Once an environment's server config -has loaded, clients use persisted `pullRequests[]`, multi-link commands, stack UI, and reverse thread -lookup. Before that, they hide linking actions. - -Environments keep advertising `threadPullRequestLinking`, accepting legacy metadata commands, and -emitting the derived `linkedPullRequest` field, because older clients still read them. That -hostless field includes only links in the thread project's own repository. Retain the legacy wire -fields, projection column, and replay support. - -Provider-specific behavior belongs behind an adapter. Orchestration works with normalized commands -and events, so adding a provider should not require branches throughout the domain or clients. -See [provider constraints](./providers.md). - -## Settings ownership - -Client preferences stay in the current client; environment defaults and project overrides stay -on their owning server. The web and desktop settings target is URL state, resolved against current -connections and project membership. An unavailable target must not fall back to another environment. -**All environments** is an explicit bulk edit of connected, loaded servers, not a durable global -default or a promise to synchronize offline or future environments. Project-group targets similarly -select known environment-local checkouts; the group itself does not store inherited defaults. - -## Durable intent and side effects - -Orchestration state is decided as events, and projections are the source of truth once they apply -them. The [v2 orchestrator](../../apps/server/src/orchestration-v2/Orchestrator.ts) serializes commands and -decides events without performing provider or filesystem work. -[EventSink](../../apps/server/src/orchestration-v2/EventSink.ts) commits events, persisted projections, -the accepted command receipt, and outbox effects in one database transaction. Subscribers receive -events after that commit. This keeps command retries idempotent and prevents a persisted projection -from getting ahead of the event log. - -The [effect worker](../../apps/server/src/orchestration-v2/EffectWorker.ts) performs side effects -after intent has been recorded, then feeds results back into orchestration. A command acknowledgement -therefore means the intent committed, not that the provider, checkpoint, or other follow-up work -finished. Keep external I/O out of command decisions and the database transaction. Effects tied to -a lost provider process cannot simply replay; recovery retires them before admitting new work. - -A thread's effects run in outbox order: a pending effect, even one whose `available_at` is hours -away, blocks every later effect of its thread (title generation has its own lane). A long timer is -therefore a [Scheduler](../../apps/server/src/scheduling/Scheduler.ts) sweep, as in -[UsageLimitRecoveryWorker](../../apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts), not -a delayed outbox effect. - -The event log only keeps what live readers need: about a day of history for reconnect replay and -command-id retries. -[ProjectionMaintenance](../../apps/server/src/orchestration-v2/ProjectionMaintenance.ts) deletes -older events the projections cover, so projections cannot be rebuilt from the log. It keeps each -stream's newest event (high-water marks, stream versions, snapshot sequences), `thread.created` -(the legacy importer's marker), every `running` run update (Codex usage history reads the first -of each attempt), and prompt anchors that retained subagent rows reference. A client whose cursor -is below both its thread's newest event and the recorded pruned-through sequence missed pruned -events, so it resumes from a snapshot; an idle thread's cursor resumes without one. Resumes -recheck that sequence after reading the replay, since a pass can prune during the read. V2 command -receipts stay for idempotency: a retry older than the retained history is still deduplicated, -but its replay comes back without the pruned events. Receipts of imported legacy commands are -removed once their threads are imported. - -Retained events must remain decodable on replay. Changing a schema affects old environments at -startup as well as live RPC traffic. Compatibility work must account for stored history, not just -what the newest client sends. - -## Turn completion and checkpoints - -A provider turn ending and its follow-up work settling are separate milestones. Orchestration -records provider turn and run state independently from -[run finalization](../../apps/server/src/orchestration-v2/RunFinalizationService.ts). A late -checkpoint or diff must not extend the recorded provider duration or keep the client showing -provider work as active. PR discovery after completion also checks that the checkout still matches -the thread's non-default branch and that a newer run is not active. - -[Checkpoints](../../apps/server/src/checkpointing/CheckpointStore.ts) use hidden Git refs to -capture workspace state without adding commits to the user's branch. A revert must coordinate -workspace state with the provider conversation. A provider that cannot roll back its conversation -must reject that operation before changing the filesystem. - -A thread also gets one `repository` checkpoint scope per tracked Git folder it reaches, under its -root scope. A project can track dozens of repositories while a -turn touches a few, so these scopes are sparse: a turn costs one `git status` per repository, and -only a repository the turn changed gets a snapshot ref, a `checkpoint.captured` record and, the -first time, its `checkpoint-scope.created`. A missing record means the turn left the repository -alone, and a ref does not exist for every run ordinal. - -A file rewind restores the thread's folder and every repository a discarded run changed, or none -of them: each folder is snapshotted first and put back if a later restore fails. A repository -with no checkpoint at the target returns to the baseline taken before its first later change, -which `repositoryRewindCheckpoint` picks; one whose earlier state was never snapshotted is left as -it is. Run ordinals are never reused, so the snapshots of discarded runs are deleted rather than -overwritten. - -A worktree thread of a project that tracks Git folders works in a task folder: one directory under -the worktrees directory that holds the project folder and a worktree of each chosen repository at -the same relative places, all on the thread's branch. The record is keyed by that directory, not -by thread, because subagents, forks and reused worktrees share a path. Such a thread reaches only -those worktrees: a repository scope's `cwd` is the worktree and its `repositoryPath` the tracked -folder. A project folder that is not a repository root is never checked out; its entries are -linked, so they stay shared with the original. Its root checkpoints are `missing` by design, and -a file rewind there restores the repositories alone. `TaskFolders` owns every change to a task folder, -and removal keeps any checkout the single-worktree rules would keep. - -Thread settlement is server-owned. The -[settlement service](../../apps/server/src/orchestration-v2/ThreadSettlementService.ts) evaluates PR -and inactivity settings without a connected client. Merge notifications invalidate cached PR state -and trigger a check. A merge outside T3, such as an agent running `gh pr merge`, sends no -notification, so the [PR sync reactor](../../apps/server/src/orchestration-v2/PullRequestSyncReactor.ts) -re-reads a thread's open links when a run that ran a merge or close command ends. Each forge's -definition names its CLI's commands in `changeRequestCloseCommand`. The guarded -`thread.auto-settle` command rejects newer activity, explicit settlement overrides, and live or -blocked work. It records the activity timestamp for stable -sorting and detaches idle provider sessions. Clients render the persisted result; they do not -derive settlement from their own clocks or PR caches. - -## Waiting for asynchronous work - -Tests use [drainable workers](../../packages/shared/src/DrainableWorker.ts) to wait until both the -queue and its current item have finished. An empty queue alone does not prove the worker is idle. - -V2 tests also drain the effect worker or await a specific persisted event or receipt. Test signals -are separate from the durable command receipts that make dispatch idempotent. Production behavior -must use persisted state and events, not test instrumentation or assumptions about elapsed time. - -The Electron shell acquires `DesktopPreReadyPlatform.layer` synchronously before asynchronous -services. On Linux this sets the desktop-entry identity and global-shortcut portal flags before -Chromium initializes its portal connection. Setting the identity later in `DesktopAppIdentity` -is too late: Chromium caches the first registration, including failures. The identity must match -the installed entry managed by `DesktopLinuxUrlHandler`. Pre-ready setup also refreshes that entry's -`Exec` path before portal registration: AppImage updates can remove the previous executable, which -makes the old entry invalid even though its filename is correct. The later URL handler avoids -rewriting an identical entry while the portal may be reading it. On Wayland, Electron's synchronous -shortcut-registration result only confirms submission; it does not confirm desktop consent or -an active binding. - -Native modules never load in the Electron main process on the startup path, and the two the -snapshot feature keeps are isolated: `@crowecawcaw/xa11y` runs only in forked Node-mode children -(`SnapShotAccessibilityWorker`, `RegionSnapShotWorker`) and a worker thread, and `ffi-rs` loads -lazily inside `WindowsForeground.ts` for a handful of Win32 calls. macOS window lookup shells out -to `osascript` instead of a native addon. A crash or stall in any of these must not take the app -down, so new native capability goes in a child with a deadline, not an `import` in main. - -See the [glossary](./glossary.md) for shared terms and the -[development runbook](../operations/development.md) for setup and checks. diff --git a/docs/internals/providers.md b/docs/internals/providers.md deleted file mode 100644 index 735c5fbdcc12e..0000000000000 --- a/docs/internals/providers.md +++ /dev/null @@ -1,189 +0,0 @@ -# Provider constraints - -Orchestration records intent and state without knowing which provider runs a thread. Provider -protocols, account ownership, permissions, and capabilities belong at the -[adapter boundary](../../packages/provider-core/src/server/ProviderAdapter.ts). Normalize there -instead of spreading provider checks through orchestration and clients. - -A driver kind identifies an integration; an instance identifies one configuration and account -lifecycle. Route work by instance, so two accounts using the same driver do not share mutable -session or catalog state. For a new driver, start with [adding a provider](./adding-a-provider.md). - -## Process and account isolation - -The `opencode` driver probes the installed version and runs the 1.x or 2.x runtime. OpenCode's MCP -registrations are directory-scoped, while T3's MCP connection is thread-scoped, so threads in one -directory must not share one T3 MCP entry. - -- **1.x** uses one T3-managed chat server per thread, so threads cannot replace each other's - connection. Catalog and text-generation work can share the - [instance-owned helper](../../packages/provider-opencode/src/server/OpenCodeServerOwner.ts), which closes - after an idle period. See the [1.x adapter](../../packages/provider-opencode/src/server/adapter.ts). -- **2.x** serves every directory from one - [server per instance](../../packages/provider-opencode/src/server/v2/OpenCode2Server.ts). Each thread - registers its own `t3-code-` MCP entry, and session permission rules deny every other - thread's entry. See the [2.x adapter](../../packages/provider-opencode/src/server/v2/adapter.ts). - -External OpenCode servers remain externally owned and can require an external restart to pick up -configuration changes. OpenCode stores "always" approval grants for the whole project. Automatic -full-access replies use `once` so they cannot widen a supervised thread's permissions on a shared -server. On 2.x, a session-wide approval also replies `once` and becomes T3's own rule on that session. - -Pi runs the user's own `pi` install in RPC mode and owns native extension, package, and project -trust discovery. T3 injects only its namespaced MCP bridge, so a Pi session behaves as it does in -the Pi TUI. Pi session files back native resume, rollback, and same-instance thread forks. -Forks use Pi's CLI in the destination directory because RPC session switching retains the source -session's cwd. Provider switches still use portable handoff summaries. -See the [adapter](../../packages/provider-pi/src/server/adapter.ts). - -Antigravity separates account profiles per instance while sharing installed executables across the -environment. The 1.5 CLI keeps every profile's sign-in in one OS keyring entry and ignores -`AGY_ACP_FORCE_FILE_STORAGE`; only its SSH-session check stores the sign-in in the profile, so Google -account instances launch with `SSH_CONNECTION` set and sign in with `--login`. Gemini Enterprise -has no such sign-in and still shares the keyring entry. The launch environment removes ambient Google credentials, -so an instance cannot silently use another account or billing project. The agent also resolves -its user-global skill directories under that profile, so the profile links those two directories -back to the user's real `~/.gemini`; MCP servers, hooks, and rules there stay out of the profile. -See [profile isolation](../../apps/server/src/provider/antigravityAuthSupport.ts). - -The [Antigravity installer](../../apps/server/src/provider/AntigravityInstallation.ts) outlives -client connections and provider-instance rebuilds. Releases are immutable, with an atomic pointer -selecting the version for new processes. Running processes hold leases on their version. Updates -and removal must respect those leases instead of replacing executables under a running agent. - -A fixed MCP tool schema does not reach every stored Antigravity conversation. Before a turn in a -long conversation, `agy` runs context summarization with the tool declarations stored with that -conversation's last generation, not with the live MCP tool list. Only the last `gen_metadata` row of -`conversations/.db` in the agent's app folder holds the full request; `agy` shrinks the earlier -rows when it stores a new one. If that row declares a schema Gemini rejects, every later turn fails -with the same 400, logged by `agy` as `pre-invocation hook: context summarization:`, and stores no -new generation, so the conversation never recovers. A short conversation recovers on its next turn, -which skips summarization. While no turn can start on the thread, a SQLite `.backup` of the file and -then deleting that one row heals it, however many turns failed; the transcript in `steps` stays. -Keep advertised schemas within what Gemini accepts, as [the advertised schema -transform](../../apps/server/src/mcp/advertisedJsonSchema.ts) does. - -## Setup must not happen as a health-check side effect - -Opening a provider session can start MCP servers, run hooks, or launch a login browser. -[Grok probes](../../packages/provider-grok/src/server/status.ts) avoid authentication and -session creation for this reason. Antigravity likewise reserves authenticated catalog sessions for -explicit setup or model refresh; background checks use initialization only. - -[Antigravity sign-in](../../apps/server/src/provider/AntigravityAuth.ts) belongs to the initiating -T3 auth session. The client carries the return URL back to the environment because the provider's -loopback listener may be on another machine. Forward only the callback for the owned pending flow; -a successful callback HTTP request is not proof that provider authentication finished. The native -process owns token exchange and storage. - -Managed ChatGPT sign-in for a remote environment can finish on a local primary. The -[primary handoff](../../apps/server/src/provider/CodexChatGptHandoff.ts) uses an ephemeral -credential store and the destination's environment ID. It exchanges and verifies the code before -transferring the issued client registration and tokens. Only the destination persists and refreshes -that session; retaining a primary refresh session would race refresh-token rotation. Without a local -primary, the client uses the remote callback completion flow. - -Antigravity sign-out closes admission to new processes and stops existing processes before clearing account -metadata. Otherwise a helper or resumed session could retain the old account. Cached model lists -do not establish current access, and an authoritative empty catalog must clear the old list. - -Antigravity text-generation helpers deny tool requests, but native hooks and MCP configuration can -run before the prompt. They reject profiles with such configuration before launch. Prompt -instructions and tool denial do not create a native sandbox. -See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts). - -## Provider updates run only through the owning installer - -A package manager runs only when the resolved executable's path proves it owns the install. Homebrew -and npm are proven by the real path (symlinks followed): a versioned keg or cask under -`brew --prefix`, or `/lib/node_modules//` (Windows: the shim beside `node_modules`). -Native installer layouts and the global directories of pnpm, Bun, Yarn, and Vite+ may match on -either the resolved path or its real target, since those installers place real files or their own -symlinks there. Volta is proven by the package's image directory plus either its `volta-shim` link -or, on Windows, the exact cmd or bash forwarding script Volta generates; a custom script that merely -calls `volta run` does not qualify. When nothing is proven, Pi's and Grok's own updaters -(`pi update --self`, `grok update`) run instead, because each detects its installer itself; the -runner's version check catches an updater that exits 0 without updating. Claude, Codex, and OpenCode updaters only act on their own native layout, so -those providers stay manual-only unless that layout is proven. Mise is checked -first, since a `mise x` wrapper can sit at a native installer's path, and `MISE_DATA_DIR` can put -installs anywhere, so `mise which` is asked whenever mise is on `PATH`. Each driver names its fixed -mise tool; mise must resolve the binary and list it in an active install of that tool requested as -`latest`, which gets `mise upgrade `. T3 Code keeps launching the configured path, so that -path must be a shim or under the tool's `latest` link, which the upgrade repoints: a version -directory (including one `mise activate` put on `PATH`) would keep running the old binary until mise -prunes it. Everything else mise touches (fixed version paths, pinned tools, wrappers, OpenCode 1.x, -whose mise tool crosses into 2.x) stays manual-only, so T3 Code never edits mise config. Nix store installs stay manual-only too, since the store is read-only. `mise latest` supplies the version, because settings such as -`minimum_release_age` can hold mise behind npm. A Grok cask whose Homebrew prefix -cannot be verified also stays manual-only: `grok update` would install a second copy. npm updates pin `--prefix` because the -`npm` on `PATH` can belong to a different Node than the one that owns the provider. Homebrew -compares against `brew info` since casks trail npm by hours; native installs share npm's version -train, so the registry stays authoritative for them. A Chocolatey install of Claude stays -manual-only: its package directory is writable only by administrators, and `claude update` through -the shim installs a native copy elsewhere. The latest version comes from `choco search`, and the -card shows `choco upgrade claude-code` without running it. -See the [resolver](../../apps/server/src/provider/providerMaintenanceRunner.ts). - -Ownership is cached per instance and re-read immediately before an update runs. The -[runner](../../apps/server/src/provider/providerMaintenanceRunner.ts) refuses when the lock key -changed since the advisory, and reports success only when the refreshed provider is still installed -with a readable, current version. - -## Protocol traps - -Codex async questions arrive as notifications and are answered with a new user message. There is -no pending RPC response to send. The -[adapter](../../apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts) persists them as -`user_input_request` turn items and runtime requests with `responseCapability: { type: "message" }`. -Their execution nodes do not block the run. Web, desktop, and mobile use their normal question -panels, and requests remain pending after a turn finishes, a provider exits, or the server restarts. - -`runtime-request.respond` reads the persisted request and question item, validates required -answers, and commits the resolution and a user message in one transaction. Repeating the same -command returns its receipt without posting the answer twice. The normal message path starts or -resumes a run, queues behind active work, or steers when the adapter supports it. Blocking questions -retain the provider's live response path. Do not infer that a request has disappeared merely because -it is outside the recent history window. - -Native `/goal` state belongs to the provider and is mirrored on the provider thread. Codex starts -the next goal turn on its own milliseconds after the last one completes, so the -[adapter](../../apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts) keeps the run open -and adds that turn to it. One run can therefore own several native turns. `/goal` commands that -start no Codex turn settle on a provider turn without a native ref, which native rollback must -not count. Claude's SDK mode emits no goal events; its adapter reads goal state from the -synthetic command output and Stop hook feedback in the transcript. - -Capabilities must describe what the provider can actually do. Antigravity can capture workspace -checkpoints but cannot roll back its conversation. The [checkpoint boundary](./overview.md#turn-completion-and-checkpoints) -therefore rejects revert before touching files. Native permission and question option IDs must -also survive normalization; a display label is not necessarily a valid reply. - -## Attachments and stored history - -Attachments live outside the project workspace. The -[attachment boundary](../../apps/server/src/orchestration-v2/AttachmentClaims.ts) validates and claims -uploads for a thread; adapters choose native input formats for those environment-local files. -A path in the prompt does not grant filesystem access. Keep provider sandbox and approval rules -in force; copying uploads into the project to bypass them changes that boundary. - -File attachments introduced a replay compatibility limit. Image-only clients cannot decode -file-bearing messages, and an image-only server can fail the entire environment's startup when -replaying one such event. Rollouts and downgrades must account for persisted history as well as -current client support. - -## Provider diagnostics - -Native event logs retain lifecycle events, responses, and failures. Token deltas and duplicate raw -frames are filtered before adapters copy or redact payloads. The filter accepts both legacy native -events and v2 protocol envelopes; decode failures remain visible through diagnostic frames. - -Log payloads have a 64 KiB encoded budget. Large or deeply nested payloads become structural -summaries that retain routing identifiers, methods, status, and error fields. Traversal is bounded -before redaction and serialization, so logging a large response does not require several full -copies. These limits apply to diagnostics; provider event handling is unchanged. - -Codex resumes with metadata-only reads when it needs a thread's identity and update time. Its -initialization capabilities opt out of `turn/diff/updated`: T3 derives diffs from checkpoints. -The logger filters those notifications before traversal when an older provider still sends them. - -Model classification has its own [manifest constraints](./model-manifest.md). Assistant-reference -handling is documented under [citations](./assistant-citations.md). diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md deleted file mode 100644 index 0608c08a35c8b..0000000000000 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ /dev/null @@ -1,659 +0,0 @@ -# Orchestrator MCP Server - -## Purpose - -T3 exposes V2 orchestration through its app-owned MCP endpoint. A provider -agent can use this endpoint to: - -- create an app-owned sub-agent on any supported provider instance; -- wait for or poll the sub-agent's durable result; -- cancel an active delegated task; and -- create one or more ordinary top-level T3 threads; -- list a project's threads and incrementally read any thread; -- rename threads, regenerate titles, and link or unlink pull requests; -- send or steer follow-up messages; -- wait for or interrupt ordinary thread runs; and -- schedule recurring work that runs without an active turn. - -These are T3 orchestration operations, not provider-native sub-agent APIs. -Delegated tasks always create a T3 child thread and run. The child receives -only the supplied task prompt, plus an optional role instruction supplied in -the same tool call. Parent conversation history is not copied into the child. - -`ThreadManagementService` is the shared server application boundary for V2 -WebSocket commands and MCP. It owns thread lookup, listing, send-mode -selection, durable send postconditions, wait polling, and interrupt selection; -`OrchestratorV2` remains the lower-level command/event processor. Transport -adapters only authenticate, resolve transport-specific inputs, and shape -responses. - -## Transport And Authentication - -The orchestration tools share the existing authenticated HTTP MCP endpoint: - -```text -http://127.0.0.1:/mcp -``` - -The provider-visible server key is `t3-code`. The endpoint registers both the -preview toolkit and the orchestration toolkit. - -Before `ProviderSessionManager` opens a new V2 provider session, it asks -`McpSessionRegistry` for a credential scoped to: - -- the T3 environment; -- the parent T3 thread; -- the concrete provider instance; and -- the provider session. - -The credential grants `preview` and `orchestration` capabilities. Credentials -expire after a maximum lifetime, expire when idle, and are revoked when the -provider session is released. The raw token is not persisted in orchestration -state. - -The MCP HTTP server resolves the bearer token and supplies the resulting -`McpInvocationScope` to tool handlers. Orchestration handlers additionally -check the `orchestration` capability before reading or mutating state. - -## Provider Injection - -### Codex V2 - -Codex gets T3's MCP server in each thread's `thread/start`, `thread/resume`, -and `thread/fork` config, with the provider-session token in an -`Authorization` header. The same server is registered twice: - -- `t3-code`: every tool except `t3_thread_wait` and `delegate_task`. -- `t3-code-direct`: only `t3_thread_wait` and `delegate_task`, with - `omit_tools_from = ["code_mode", "deferred"]`. - -Code Mode yields a script after about 30 seconds, so the model polls a blocking -`t3_thread_wait` or `delegate_task` with `mode: "wait"`, resending its context -on each poll. The second entry makes both direct tool calls, like Codex's own -wait tools. Codex reports calls as `.`, so -`packages/shared/src/t3McpToolPresentation.ts` must resolve both server names. -Tool display and pending-work detection depend on it. - -### Claude Agent SDK V2 - -Claude receives an HTTP MCP server in its query options: - -```ts -{ - mcpServers: { - "t3-code": { - type: "http", - url: "http://127.0.0.1:/mcp", - headers: { - Authorization: "Bearer ", - }, - }, - }, - allowedTools: [ - // existing allowed tools - "mcp__t3-code__*", - ], -} -``` - -The adapter logs only whether MCP configuration exists; it does not log the -server headers or token. - -### Cursor Agent SDK V2 - -Cursor receives the same authenticated HTTP MCP endpoint through the SDK's -`mcpServers` on `Agent.create` / `Agent.resume` and each `send`. With -`@cursor/sdk` 1.0.39+, send-level servers replace only the create-time inline -set; ambient servers from `settingSources` (`project`, `user`, `team`, `mdm`, -`plugins`) stay available. The adapter passes the authorization header to the -SDK but projects only redacted option metadata into protocol diagnostics. - -### Grok ACP V2 - -Grok receives the authenticated HTTP MCP endpoint through the ACP -`session/new`, `session/load`, and `session/fork` `mcpServers` field. The shared -ACP adapter owns standard protocol behavior; the Grok flavor adds xAI extension -requests such as structured user questions. - -ACP does not define native subagents or active steering. Grok therefore uses -orchestrator-owned child threads and implements steering through -cancel-and-restart. Its current driver also lacks `session/fork`, so app forks -use portable context transfer. These are orchestrator policies, not -provider-specific MCP tools. - -### ACP Registry V2 - -The `acpRegistry` driver is the generic flavor of the same shared ACP adapter. -Each provider instance names an agent from the official ACP Registry. Settings -searches the registry through the connected server, then prepares a compatible -distribution before persisting the provider instance. Binary distributions use -a managed, versioned cache; declared checksums are verified when present. -Version-pinned `npx` packages install globally through `npm`; `uvx` packages use -`uv tool install`. ACP launches the resulting global command directly, so the -same command is available for terminal authentication. A local executable may -override the installed command without changing the registry-declared arguments -or environment. - -Search, preparation, provider status, and session startup share one -server-scoped catalog service. This keeps platform selection and registry -validation identical across settings and runtime use. Catalog inspection never -starts an ACP process, probes models, or performs authentication. The managed -provider snapshot creates a disposable `session/new` through the normal provider -refresh lifecycle, using success as the authentication-readiness proof and -projecting advertised models into the snapshot. Terminal-only login remains a -manual operation on the connected server. - -Capabilities such as session loading, session forking, models, modes, and MCP -transport are enabled only when the selected agent advertises them. Missing -features degrade through V2 policy: steering uses interrupt-and-restart, -forking uses portable context when native `session/fork` is unavailable, and -subagents use orchestrator-owned child threads. Registry agents do not receive -provider-specific extensions; those remain in flavors such as Grok. - -### Pi V2 - -T3 keeps a provider-session HTTP bridge even when Pi supports native MCP. -`mcp.json` entries override native registrations, and native MCP's default -60-second request timeout can interrupt long-running T3 tools. The bridge owns -the injected endpoint and credential and forwards Pi's cancellation signal. - -When a provider session credential exists, the adapter writes a T3-owned -extension into the server cache and spawns -`pi --mode rpc --extension /pi-t3-mcp-extension.ts` with: - -```text -T3_MCP_URL=http://127.0.0.1:/mcp -T3_MCP_BEARER_TOKEN= -``` - -The extension preserves public names under `mcp__t3-code__` for saved loadouts -and tool selectors. Modern Pi also receives `mcp__t3_code__` aliases, Pi's own -name for the server, which reserve it against configured MCP servers. They are -`model-only` and hide their own declarations, so the model can call them without -added declarations, search results, or codemode entries. An alias follows its -public tool: dropped when that tool is excluded, and off while a direct one is -off. Pi's `hidden` exposure would make them unreachable. On Pi 0.99+, -`orchestrator_capabilities`, `delegate_task`, and `task_status` remain directly -available; optional tools are discovered through Pi's builtin `tool_search`. -On older Pi or without builtin search, all tools remain directly available. -The bridge calls the original MCP tool name over HTTP. Follow-up requests send -`mcp-protocol-version: 2025-06-18`; Effect's MCP transport returns 400 -without it. The first turn of a session also receives the shared T3 -orchestration instructions. - -Pi keeps ownership of native extension discovery. T3 does not replace Pi's -`subagent` tool or reproduce Pi's package and project-trust loader. Durable -delegation goes through the namespaced T3 MCP `delegate_task` tool and the -shared orchestration child-thread lifecycle. When Pi's example `subagent` -extension is installed, the adapter observes its documented `details.results` -shape and projects task cards with no child thread id. Unknown result shapes -remain ordinary dynamic tool output. - -### Provider Support - -A provider instance can run child tasks when its live `ProviderInstance` -exposes a V2 `orchestrationAdapter` — the same registration the orchestrator -resolves when a `delegated_task.request` executes. That covers Codex, Claude -Agent SDK, Cursor Agent SDK, Grok, generic registry agents over ACP, OpenCode, -OpenCode 2, Pi, Antigravity, and any future driver that builds an adapter. -Capability discovery still reports other registered provider instances, but -marks them unavailable for orchestration when no adapter resolves. This keeps -provider selection model-visible without allowing a request that cannot run. - -## Tool Surface - -`OrchestratorToolkit` in -[`toolkits/orchestrator/tools.ts`](../../apps/server/src/mcp/toolkits/orchestrator/tools.ts) -is the authoritative list of orchestration tools. The sections below cover -delegation and thread tools. `t3_thread_launch` is documented with them but -registered by the project toolkit in -[`toolkits/project/tools.ts`](../../apps/server/src/mcp/toolkits/project/tools.ts). - -### `orchestrator_capabilities` - -Returns: - -- the inherited provider instance and model; -- the parent runtime and interaction modes; -- registered provider instances and advertised models; -- whether each provider can run a child task; and -- feature flags for polling, cancellation, and batch thread creation. - -Unavailable providers include model-visible constraints such as missing V2 -adapter support, disabled state, missing executable, or missing authentication. - -The model list is short on purpose: catalogs such as OpenCode can hold hundreds -of models, and every call lands in the agent's context. Each provider lists -custom, favorite, and the caller's own models, plus all current (non-legacy) -models for Codex, Claude, Muse, and Grok, or the first 8 current models in the -user's model order for other providers. `omittedModels` counts the rest, and the -`search` input finds them, legacy models included. `delegate_task` still accepts -any catalog model. - -### `delegate_task` - -Creates a T3-owned child thread and immediately dispatches the supplied task -prompt. - -The [shared contract](../../packages/contracts/src/orchestratorMcp.ts) is authoritative for -inputs and results, including target options and linked-environment fields. - -```ts -import type { - OrchestratorMcpDelegateTaskInput as DelegateTaskInput, - OrchestratorMcpDelegateTaskResult as DelegateTaskResult, -} from "@t3tools/contracts"; -``` - -For local delegation, provider, model, runtime mode, and interaction mode inherit -from the parent when omitted. A driver-only target inherits the parent's provider instance -when it can run child tasks, and otherwise selects an available instance of -that driver; an explicit `providerInstanceId` is honored exactly and fails -when unavailable. Selecting a different provider without a model uses that -provider's first advertised model. - -Set `target.options` using the options returned by `orchestrator_capabilities`, such as -`{effort: "max"}`. Supplied values override inherited selections; `{}` or `[]` clears them. -For local delegation, use `isolation: "worktree"` for a separate prepared checkout from -the parent's commit; the default `"shared"` uses the parent's checkout. Uncommitted parent -edits are not copied. A linked-environment target (`target.environmentId`) runs in the remote -project's checkout and rejects worktree isolation. To launch an isolated thread there, use -`t3_thread_launch` with `environmentId` and a worktree `workspaceStrategy`. - -A provider runs a runtime mode it does not offer as `approval-required`, so a -child would ask for approval on every command. `orchestrator_capabilities` -lists `runtimeModes` only for a provider that offers some of the modes, and -omits it for a provider that offers all of them. When the target lists -`runtimeModes`, an explicit `runtimeMode` outside that list is refused, and an -inherited mode steps down to the broadest mode the target offers. - -Each independent delegated review round uses a new `delegate_task` call with the -original brief, prior findings, responses, and unresolved objections. Track each -round by its own `taskId` and use a distinct `clientRequestId` per round, stable -across retries of that round. -A follow-up that needs the same child's conversation goes through `t3_thread_send` -on its `childThreadId`. After the original task completes, that follow-up runs as a -fresh task in the child thread; it does not reopen the completed task or change its -published result. - -Delegation requires an active parent run owned by the MCP credential's -provider session. The request becomes the V2 command -`delegated_task.request`. - -`mode: "async"` returns the current durable state immediately. -`mode: "wait"` waits for the task result, including nested work and completion follow-ups, or until -the timeout expires. A wait timeout does not cancel the child; the result sets -`waitTimedOut: true`. When the result includes `next`, completion wakes the parent: -do not wait on the task or poll it; continue other work, and end the turn when none is -left. A pending blocking question also ends the wait with `hasPendingQuestion: true` and -`waitTimedOut: false`. -If `hasPendingQuestion`, pass `threadId=childThreadId` to `t3_pending_request` with -action `list`, `read` (with `requestId`), or `respond`, or ask the user; the task's completion still wakes this thread. A pending live approval for the -task's own unfinished work also ends the wait. Its identity appears in `pendingApproval`; -it grants no approval authority. Read the fresh full request in the child thread before -responding, since the durable record can outlive its provider callback. Async questions -do not end the wait. - -### `task_status` - -Reads a delegated task from the parent thread's durable projection. A task ID -from another parent thread is rejected. `childRunId` identifies the original -run. `status: "starting"` means the child's provider has not started its turn -yet, so a task that stays there has not begun work. A task in a linked -environment reads its run's status there for this. `workState` distinguishes -active work, a finished turn waiting for children, and an available result. The -task remains nonterminal until its known work finishes. Its published `summary` -and result transfer then remain stable across later follow-ups. -`hasPendingChildRuns` reports later queued or executing turns; `latestTerminal*` -exposes later executed, non-monitor results without replacing the published task -result. - -### `task_cancel` - -Stops every task the child delegated, then the child thread with the internal -`thread.stop` command, cancels the task's own queued turn, and disposes automatic -parent delivery. Like a user Stop, `thread.stop` interrupts the running turn, holds -queued turns, and ends pull request watches. The task's own queued turn is cancelled -even if Stop already held it, so a task that is only queued can be cancelled; other -queued turns in the child stay held for Resume. A nonterminal task is rejected when -it has no interruptible run, no queued turn of its own, and its finished turn no -longer waits on background work or delegated tasks. Once a cancelled task's turn -ends, a completed result settles as `interrupted` and a failed one stays `failed`. A -terminal task returns its existing status, and its child thread still stops, -including later runs and watch wakes. In both cases, a follow-up that lost its child -run but still shows as running on the parent is cancelled there and reported as -`cancelled`. Published task results remain available. It accepts an -optional cancellation reason. - -### `create_threads` - -Creates between one and twenty ordinary top-level T3 threads: - -```ts -import type { OrchestratorMcpCreateThreadsInput as CreateThreadsInput } from "@t3tools/contracts"; -``` - -Each entry independently resolves provider, model, and modes. The new threads -inherit the parent's project, branch, and worktree path, but they have no -sub-agent lineage. Entries with a prompt immediately dispatch a run; entries -without a prompt remain idle. `create_threads` is local-only: `target.environmentId` and -`target.projectId` are ignored even though the shared target contract accepts them. Use -`t3_thread_launch` with `environmentId` and `projectId` to select another environment or project. - -### `t3_thread_launch` - -Launches one ordinary top-level thread through the app's launch service. Use an -explicit `workspaceStrategy` to create a new worktree (`worktree` with `baseRef`), -attach an existing checkout (`existing_worktree` with `worktreePath`), or use the -project root (`root`, also the default). The thread is bound to that workspace -before the agent starts. Creating a worktree in the task prompt does not update -this binding. - -Pass the task in `message`. Project, model, and modes inherit when omitted; -workspace does not. `scratch: true` launches without a project, in a folder of -its own under the environment's Scratch project. A new worktree with `startFromOrigin` omitted follows the new-worktree setting. For stacked PRs, use the parent branch as `baseRef` with -`startFromOrigin: false`. The new thread may not run with broader runtime or -interaction modes than the caller. As for `delegate_task`, a runtime mode the -provider does not offer is refused, and an inherited or default one steps down -to the broadest mode it offers. `create_threads` remains the batch option for a -shared checkout. - -Set `clientRequestId` on the initial launch to make it retryable. After an error -or a lost reply, resend the same request with the same key from the same -provider session. This reuses any thread already created by that request. If the -initial request had no key, check for the thread before launching again. - -### `t3_thread_list` - -Lists durable thread shells in one project, newest first: `projectId` when -given, else the calling thread's project. Callers can filter by title, run -status, and whether app-owned sub-agent threads are included. Results are -bounded and offset-paginated. Deleted threads are never listed. - -### `t3_thread_read` - -Reads the durable state, recent runs, and visible timeline of any thread in -the environment by thread ID. A deleted thread returns `thread_not_found`. The -default `messages` view returns user messages, assistant -messages, and proposed plans. The `activity` view also returns summarized tool, -reasoning, checkpoint, handoff, and runtime-request items. Large item text is -bounded and reports whether it was truncated. An agent in a T3 thread that -reads without a cursor gets the newest items, and `beforePosition=earlierPosition` -reads older ones. Client callers (the CLI, linked environments, outside MCP -clients) start at the oldest item instead, because the CLI and linked -environments on older versions read that way and follow only `hasMore`. -`afterPosition=-1` starts any read at the oldest item, and -`afterPosition=nextPosition` reads newer items. The server stops adding items once the result reaches about 30,000 characters and -reports the rest through `earlierPosition` or `hasMore`. Claude Code saves MCP -results over its token limit to a file instead of showing them, so a read has -to fit whatever `limit` an agent asks for. - -Thread and message results include required `createdBy` and `creationSource` -provenance. MCP-created threads and user-role messages use `createdBy: "agent"` -and `creationSource: "mcp"`; provider output uses `creationSource: "provider"`. -Actor and ingress are separate so agent-authored user-role messages remain -distinguishable from human-authored messages. - -Agents mention another thread by the `link` its result carries, -`/>`, so they never format an id or -write a title, which goes stale when the user renames the thread. The -environment that owns the thread builds the link, so forwarded results and tasks -delegated to a linked environment name that environment. Clients open only that -environment's thread and show its current title; a link to a thread they do not -know renders as a label that opens nothing. Older `t3-thread://v1/` -links name no environment: clients resolve them in the message's environment, -then by a unique match in another enabled environment. An outside OAuth client, -one that is not a linked environment, cannot render `t3-thread://` links, so it -gets the link Copy thread copies, `https://app.t3.codes/threads//` -on the server's `T3CODE_HOSTED_APP_URL`, for threads in this environment. The -hosted app offers the desktop app, the mobile app, or itself. - -List and read results report `snoozed`, `snoozedUntil`, and `pinned`, and -`t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows the -client's `effectiveSnoozed`, so agents and the sidebar agree: a snoozed thread -wakes early only when it has a pending request or fails after snoozing. Completed -runs, background wakes, and delegated completions keep it snoozed. - -They also report `blockedOnThreadWait` and `pendingBackgroundTasks`, the shell -fields behind the sidebar's Waiting label, so an agent can see what a thread -still waits on after its run completed. A subagent or `background_task` holds -the thread. A command or monitor holds it only with `awaited: true`, since agents -often leave a dev server running. - -### `t3_thread_update` - -Updates metadata for the calling thread or any other thread in the environment. -The typed actions are `rename`, which requires `title`, and `regenerate_title`, -which rejects one. Pull request links go through the separate -`link_pull_request` and `unlink_pull_request` tools. Branch and workspace -changes are outside this tool. - -The result includes the command ID and durable event sequence together with the -resultant title, title-regeneration marker, and linked pull request. Reusing a -`clientRequestId` for the same action and thread replays the same command -receipt. Thread list and read results expose the linked pull request, and thread -detail also exposes an in-flight title regeneration. - -### `t3_thread_send` - -Sends a message to any ordinary or delegated thread in the environment: - -- `auto` starts an idle thread, steers a fully active turn, or queues behind a - turn that is not yet steerable; -- `queue` creates a separate follow-up run after active work; -- `steer` requires a steerable active provider turn; -- `restart` requires an active provider turn and uses the orchestrator's - interrupt-and-restart path. On a provider that can stop a turn and queue - messages but not restart a turn with new input, it stops the turn and queues - the message ahead of other queued messages; an unheld delegated-task result - that survives the stop still runs first. It is rejected when neither path - applies: the provider cannot stop a turn, Stop has already reached the turn, - or the turn or the new message is `/compact` or `/logout`; and -- `fyi` starts no turn and returns `delivery: "held"` with no run. The - thread's next turn start adds the waiting FYI messages to that turn's input, - and a running Claude Code turn also gets them as context once its tool calls - resolve, before its next model request. An FYI counts as delivered only when - the turn that carries it completes; a turn that fails, is interrupted, - restarts or is rolled back gives it back, so the agent may see it twice. A - thread with a waiting FYI gets a quiet wake turn once it has been idle 6 - hours, counted from the latest of its creation, its runs' last activity, and - the reset of a usage limit that failed its latest run on the provider the - thread still uses (or that limit's snooze end, when later), and not before - its snooze ends. No wake reaches a thread that is settled or archived, has a - run that has not ended (a queued one included), has a runtime request that - waits for an answer, or whose provider is disabled. A wake carries waiting - FYIs up to the 16,000-character turn budget; FYIs it does not carry, or gives - back because it failed or was stopped, get another wake after 6 more idle - hours. `fyi` with `freshContext`, or with more than 16,000 characters, is - rejected. `t3_thread_read` marks each FYI item `fyi: "waiting"`, `"sent"`, - `"delivered"`, or `"unknown"` when its run cannot be found. - -The target runtime and interaction modes may not be broader than the caller's. -Stable command and message IDs are derived from `clientRequestId` for -idempotent retries. - -`outputSchema` (also on `t3_thread_launch`) asks the run for a result as data. -The run stores the schema, the turn's prompt ends with how to hand the result -back, and the agent calls `t3_submit_output`. The server checks the value -against the schema before storing it, so the caller never parses a reply. A send -that asks for a result is queued instead of steered: the result belongs to one -whole turn. A turn can end without submitting; the caller sees a finished run -with no `output`. - -### `t3_submit_output` - -Stores the calling thread's result on its running turn, once it fits the schema -that turn was sent with. A turn that was asked for nothing answers for the -newest turn that was asked and has not answered yet, which is how an agent that -ended its turn to wait gives its result after it is woken. A rejection names what did not fit, so the agent can -correct it and call again; a later accepted submission replaces an earlier one. - -### `t3_thread_wait` - -Waits for a selected run to become `completed`, `failed`, `cancelled`, -`interrupted`, or `rolled_back`. Without `runId`, it pins the latest run at call -time; an idle thread returns immediately. A timeout reports the latest durable -status and does not cancel work. `output` carries what the run submitted -against its `outputSchema`; with `untilOutput`, a completed run that has not -submitted yet is waited on until it has. - -### `t3_workflow` - -Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and -lists the questions runs ask a person. It is advertised to clients outside a thread only, such as -the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows -through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. - -### `t3_thread_interrupt` - -Interrupts a selected active run through the normal V2 `run.interrupt` command. -Without `runId`, it selects the newest interruptible run. A terminal run is -returned unchanged, and a thread with no active provider turn returns -`no_active_run`. - -### Scheduled tasks - -`schedule_task`, `list_scheduled_tasks`, and `delete_scheduled_task` manage -recurring work in the app scheduler; `schedule_task` with a `scheduledTaskId` -updates an existing task. A schedule -runs its prompt on an interval, at a fixed time in the server's local time -zone, or on each qualifying webhook request, even when no turn is active. -Without a signature, anyone with the webhook URL can trigger a run. -Signature checks, filters, and dedupe can skip a webhook request. -`bindToCurrentThread` defaults to `true` only when the caller has a thread in -the task's project; otherwise it defaults to `false`. Bound runs post into -that thread; unbound runs each launch a fresh thread in the task's project. -Explicit `bindToCurrentThread: true` without a caller thread in that project -is rejected. Pausing uses `schedule_task` with `scheduledTaskId` and `enabled: false`; -deletion is permanent. - -## Delegated Task Lifecycle - -The MCP server is a command ingress into V2. It does not call provider adapters -directly. - -```text -provider model - -> MCP tools/call delegate_task - -> authenticated OrchestratorMcpService - -> shared ThreadManagementService - -> V2 delegated_task.request command - -> child thread + child run - -> parent app_owned subagent projection - -> parent/child execution nodes - -> consumed subagent_spawn context transfer - -> normal provider effect and runtime ingestion - -> child run reaches a terminal state - -> parent subagent/node/turn item finalized - -> consumed subagent_result context transfer - -> wait result or later task_status result -``` - -The child thread has lineage relationship `subagent` and points back to the -parent node. The parent gets an `app_owned` sub-agent projection and a -sub-agent turn item so the existing debug UI can render progress. - -Terminal provider events trigger finalization. The event stream first replays -persisted events and then follows live events, so finalization also runs after -a server restart. An existing `subagent_result` transfer makes finalization -idempotent. - -Users rarely watch child threads, so a child question would otherwise go -unanswered. When a child opens a pending `user_input` request, the parent gets -a notification message telling it to answer with the pending request tools or -ask the user. The message says whether the child is blocked or, for a Codex -async question, still working. If the parent's turn is running and its provider -can steer without interrupting tools, the notification steers into that turn, -like a background task's completion. A queued notice would wait behind a -long-running orchestrator turn that may never end. Otherwise it queues. If the -question is answered or dismissed before a queued notification starts a turn, -that queued turn is cancelled. Approvals are not -routed, because those tools cannot answer them. -A parent still blocked in a `delegate_task` wait gets the blocking question -through that wait instead. -If the provider cuts that wait short, a still-pending live question wakes the -parent when its launching run completes, fails, or waits for post-turn work. -Stopping or interrupting the parent prevents this catch-up. - -A failed run exposes its provider error before any progress text. Successful -results use the latest assistant content from the final work turn. - -## Policy And Idempotency - -- A child runtime mode may stay equal to or become narrower than the parent - mode. It may not escalate privileges. -- A child interaction mode may stay equal to or narrow from `default` to - `plan`. It may not escalate from `plan` to `default`. -- Thread tools take any thread in the environment as a target. For a thread - caller, list and search cover one project: its own unless `projectId` is given. -- A tool that changes another thread needs the calling thread's live run, and - the target's runtime and interaction modes may not be broader than the - caller's. This is the same privilege ceiling as child creation. -- Provider instances must be enabled, installed, available, authenticated, and - backed by a V2 adapter. -- A requested model must be advertised by the selected provider when the - provider publishes a model list. -- `clientRequestId` derives stable command, thread, and message IDs within the - provider session. Retrying the same call returns the same durable work. -- Calls without `clientRequestId` receive a generated request key and create - new work. - -Expected denials use the typed `OrchestratorMcpFailure` result: - -```text -capability_denied -parent_not_active -provider_unavailable -model_unavailable -runtime_mode_escalation_denied -interaction_mode_escalation_denied -task_not_found -task_not_cancellable -thread_not_found -run_not_found -thread_not_sendable -thread_not_interruptible -invalid_request -orchestration_error -``` - -## Code Ownership - -- Shared schemas: `packages/contracts/src/orchestratorMcp.ts` and - `packages/contracts/src/threadMetadataMcp.ts` -- MCP services: `apps/server/src/mcp/OrchestratorMcpService.ts` and the focused - `apps/server/src/mcp/ThreadMetadataMcpService.ts` -- Tool definitions and handlers: - `apps/server/src/mcp/toolkits/orchestrator/` -- HTTP registration and authentication: - `apps/server/src/mcp/McpHttpServer.ts` -- Credential lifecycle: `apps/server/src/mcp/McpSessionRegistry.ts` -- Provider injection: - `apps/server/src/orchestration-v2/ProviderSessionManager.ts` and V2 adapters -- Durable delegated-task command and finalization: - `apps/server/src/orchestration-v2/Orchestrator.ts` - -## Verification - -The integration test uses the real MCP toolkit registration, V2 orchestrator, -SQL persistence, event ingestion, projections, and checkpoints. Only the -external provider adapters are deterministic test implementations. - -Coverage includes: - -- capability discovery; -- cross-provider delegated completion; -- prompt-only child context; -- parent and child lineage projections; -- spawn and result context transfers; -- async status polling; -- cancellation; -- batch ordinary-thread creation; -- thread listing and timeline reads, including another project's threads; -- ordinary-thread send, wait, steering, and interruption; -- inheritance and per-thread provider overrides; and -- idempotent retries. - -Provider adapter tests separately verify Codex, Claude, Cursor, Grok, and ACP -Registry behavior and MCP injection. The provider-session manager test verifies -that credentials exist before an adapter opens and are revoked when it closes. diff --git a/fork/docs/internals.md b/fork/docs/internals.md new file mode 100644 index 0000000000000..057fde866b37a --- /dev/null +++ b/fork/docs/internals.md @@ -0,0 +1,66 @@ +# Fork internals + +These notes document internals of changes this fork carries on top of upstream T3 Code. + +## Outbox order and long timers + +A thread's effects run in outbox order. A pending effect blocks every later effect of its thread, +even when its `available_at` time is hours away. Title generation has its own lane. Use a +[Scheduler](../../apps/server/src/scheduling/Scheduler.ts) sweep for a long timer, as in +[UsageLimitRecoveryWorker](../../apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts), not +a delayed outbox effect. + +## Antigravity context summarization + +A fixed MCP tool schema does not reach every stored Antigravity conversation. Before a turn in a +long conversation, `agy` runs context summarization with the tool declarations stored with that +conversation's last generation, not with the live MCP tool list. + +Only the last `gen_metadata` row of `conversations/.db` in the agent's app folder holds the full +request. When `agy` stores a new row, it shrinks the earlier rows. If that last row declares a +schema that Gemini rejects, every later turn fails with the same 400 error. `agy` logs the failure +as `pre-invocation hook: context summarization:`. Because the failed turn stores no new generation, +the conversation never recovers. A short conversation skips summarization and recovers on its next +turn. + +While no turn can start on the thread, take a SQLite `.backup` of `conversations/.db` and delete +that last `gen_metadata` row. Deleting that one row heals the conversation no matter how many turns +failed, and the transcript in `steps` stays. + +Keep advertised schemas within what Gemini accepts, as +[the advertised schema transform](../../apps/server/src/mcp/advertisedJsonSchema.ts) does. + +## The `fyi` mode of `t3_thread_send` + +The `fyi` mode of `t3_thread_send` starts no turn and returns `delivery: "held"` with no run. +`t3_thread_send` rejects `fyi` with `freshContext` or with more than 16,000 characters. + +When the thread starts its next turn, that turn adds the waiting FYI messages to its input. A +running Claude Code turn also receives waiting FYI messages as context after its tool calls resolve +and before its next model request. + +An FYI counts as delivered only when the turn that carries it completes. A turn that fails, is +interrupted, restarts, or is rolled back gives the FYI back, so the agent may see it twice. + +A thread with a waiting FYI gets a quiet wake turn after 6 idle hours. Idle time starts from the +latest of these timestamps: + +- the thread's creation, +- the last activity of its runs, and +- the reset of a usage limit that failed the thread's latest run on the provider the thread still + uses, or that limit's snooze end when later. + +A wake does not happen before the thread's snooze ends. No wake reaches a thread if any of these +conditions holds: + +- the thread is settled or archived, +- the thread has a run that has not ended, including a queued run, +- the thread has a runtime request that waits for an answer, or +- the thread's provider is disabled. + +A wake carries waiting FYIs up to the 16,000-character turn budget. Waiting FYIs that a wake does +not carry, or gives back because the wake failed or was stopped, get another wake after 6 more idle +hours. + +`t3_thread_read` marks each FYI item `fyi: "waiting"`, `"sent"`, `"delivered"`, or `"unknown"` when +its run cannot be found. diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ff0047faf8092..86623f3bfc31c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -4956,7 +4956,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } if (recoveredOutput !== undefined) { context.claimedToolResults.set(callInputKey, recoveredOutput); - output = recoveredOutput; + // Fork: an empty record (a Chat-mode send) adds nothing to what the provider reported. + if (Object.keys(recoveredOutput ?? {}).length > 0) output = recoveredOutput; } } } From b47a5cf107556d7e9580d611c98cb6ad046faefb Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 15:18:58 +0000 Subject: [PATCH 286/288] test(server): cover a run whose turn ends while a steer restarts it A steer can read a run as running, and the run's provider turn can then end before the steer commits its restart. The restarted attempt must give the run its checkpoint, and a Stop that lands before the restarted turn starts must keep the first attempt's checkpoint. Today the restarted attempt's capture is dropped, so the run ends with no checkpoint. Co-Authored-By: Claude Opus 5.5 --- ...steerRestartCheckpoint.integration.test.ts | 346 ++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts diff --git a/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts b/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts new file mode 100644 index 0000000000000..9fbcaabbfd218 --- /dev/null +++ b/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts @@ -0,0 +1,346 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + ThreadId, +} from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectWorker from "../../orchestration-v2/EffectWorker.ts"; +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as ThreadCommandExecutor from "../../orchestration-v2/ThreadCommandExecutor.ts"; + +const driver = ProviderDriverKind.make("codex"); +const instanceId = ProviderInstanceId.make("codex"); +const runSelection = { + instanceId, + model: "test-model", + options: [{ id: "effort", value: "xhigh" }], +}; +const composerSelection = { + ...runSelection, + options: [...runSelection.options, { id: "fastMode", value: false }], +}; + +// A provider that steers by interrupt-restart; the steer waits in planSelectionTransition. +const steerRestartHarness = Effect.fn("steerRestartHarness")(function* ( + name: string, + beforeSelectionTransition: Effect.Effect, +) { + const cwd = yield* checkpointWorkspace(name); + const events = yield* Queue.unbounded(); + const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = []; + const capabilities = { + ...CodexProviderCapabilitiesV2, + turns: { + ...CodexProviderCapabilitiesV2.turns, + supportsActiveSteering: false, + supportsSteeringByInterruptRestart: true, + }, + }; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(capabilities), + planSelectionTransition: () => + beforeSelectionTransition.pipe(Effect.as({ type: "apply_on_next_turn" as const })), + openSession: (input) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const turnUpdated = ( + turn: ProviderAdapter.ProviderAdapterV2TurnInput, + status: "running" | "interrupted", + ) => + Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: { driver, nativeId: `native:${turn.attemptId}`, strength: "strong" }, + ordinal: turn.providerTurnOrdinal, + status, + startedAt: now, + completedAt: status === "running" ? null : now, + }, + }); + const startTurn = (turn: ProviderAdapter.ProviderAdapterV2TurnInput) => + Effect.gen(function* () { + started.push(turn); + yield* turnUpdated(turn, "running"); + }); + return { + instanceId, + driver, + providerSessionId: input.providerSessionId, + providerSession: { + id: input.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: runSelection.model, + capabilities, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: input.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn, + compactThread: startTurn, + steerTurn: () => Effect.die("unused"), + interruptTurn: ({ providerTurnId }) => + Effect.forEach( + started.filter( + (turn) => ProviderTurnId.make(`provider-turn:${turn.attemptId}`) === providerTurnId, + ), + (turn) => + turnUpdated(turn, "interrupted").pipe( + Effect.andThen( + Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThread.id, + providerTurnId, + runOrdinal: turn.runOrdinal, + status: "interrupted", + failure: null, + threadDisposition: "reusable", + }), + ), + ), + { discard: true }, + ), + respondToRuntimeRequest: () => Effect.void, + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layer = ProviderReplayHarness.layerWithRegistry( + { name }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { runEffectWorker: false }, + ); + const startFirstTurn = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make(`thread:${name}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make(`project:${name}`), + title: "Steer restart at turn end", + modelSelection: runSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("message:first"), + text: "first", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); + return threadId; + }); + return { cwd, events, started, layer, startFirstTurn }; +}); + +it.effect.each(["completed", "interrupted", "stopped before it starts"] as const)( + "checkpoints a run whose turn ended while a steer restarted it (restart %s)", + (restartEnd) => + Effect.gen(function* () { + const steerReadRunning = yield* Deferred.make(); + const letSteerCommit = yield* Deferred.make(); + const { cwd, events, started, layer, startFirstTurn } = yield* steerRestartHarness( + `steer-restart-after-turn-end-${restartEnd}`, + Deferred.succeed(steerReadRunning, undefined).pipe( + Effect.andThen(Deferred.await(letSteerCommit)), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const runId = started[0]!.runId; + const endTurn = ( + turn: ProviderAdapter.ProviderAdapterV2TurnInput, + status: "completed" | "interrupted", + ) => + Effect.gen(function* () { + const providerTurn = (yield* orchestrator.getThreadProjection( + threadId, + )).providerTurns.find((candidate) => candidate.runAttemptId === turn.attemptId)!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === runId && + event.payload.status === status, + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...providerTurn, status, completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: providerTurn.providerThreadId, + providerTurnId: providerTurn.id, + runOrdinal: turn.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + }); + const writeWorkspaceFile = (name: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(`${cwd}/${name}`, `${name}\n`); + }).pipe(Effect.provide(NodeServices.layer), Effect.orDie); + // The first turn's capture finds the run restarting and retries with backoff. + const drainWithRetries = Effect.forEach( + [1, 2, 3, 4, 5], + () => TestClock.adjust("1 second").pipe(Effect.andThen(worker.drain())), + { discard: true }, + ); + const checkpointFiles = Effect.gen(function* () { + const projection = yield* orchestrator.getThreadProjection(threadId); + const run = projection.runs.find((candidate) => candidate.id === runId); + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.id === run?.checkpointId, + ); + assert.equal(checkpoint?.status, "ready"); + return { status: run?.status, files: checkpoint?.files.map((file) => file.path) }; + }); + + // The steer reads the run as running, then the turn ends before it commits its restart. + const steer = yield* orchestrator + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer-at-turn-end"), + threadId, + messageId: MessageId.make("message:steer-at-turn-end"), + text: "also check the logs", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: runId }, + createdBy: "agent", + creationSource: "mcp", + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(steerReadRunning); + yield* writeWorkspaceFile("first-attempt.txt"); + yield* endTurn(started[0]!, "completed"); + yield* Deferred.succeed(letSteerCommit, undefined); + yield* Fiber.join(steer); + + if (restartEnd === "stopped before it starts") { + yield* worker.runOnce(); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-before-restart-starts"), + threadId, + }); + yield* drainWithRetries; + assert.equal(started.length, 1); + const { status, files } = yield* checkpointFiles; + assert.equal(status, "interrupted"); + assert.include(files ?? [], "first-attempt.txt"); + return; + } + + const restartRunning = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "provider-turn.updated" && + event.payload.status === "running" && + event.payload.runAttemptId !== started[0]!.attemptId, + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* drainWithRetries; + yield* Fiber.join(restartRunning); + yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); + assert.equal(started.length, 2); + assert.equal(started[1]!.runId, runId); + + yield* writeWorkspaceFile("restarted-attempt.txt"); + yield* endTurn(started[1]!, restartEnd); + yield* worker.drain(); + const { status, files } = yield* checkpointFiles; + assert.equal(status, restartEnd); + assert.includeMembers(files ?? [], ["first-attempt.txt", "restarted-attempt.txt"]); + }).pipe(Effect.provide(layer)); + }), +); From 75d3faaca2dd512df69d43f7599f2f379930ebae Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 15:20:03 +0000 Subject: [PATCH 287/288] fix(server): a run restarted at turn end gets its restarted attempt's checkpoint The turn-end checkpoint capture used the run id as its outbox effect id. When a late steer restarted a run whose turn had just ended, the restarted attempt's capture reused that id and the outbox dropped it, so the run ended with no checkpoint and was not offered as the latest fork point. Key the capture effect id by run attempt, at turn end and at Stop. The command id stays per run, so the capture's commit receipt and startup recovery are unchanged, and the readers added with run completion at turn end now find a run's unsettled capture by that command id, which also finds rows queued before this change. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 31 ++++++++++++------- .../orchestration-v2/RunExecutionService.ts | 2 +- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index aff0021d6c61c..b00b08ec32c83 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3578,22 +3578,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // completed, and one Stop dropped cancelled. It runs next, in its place among waiting messages. // A run completes before its turn-end checkpoint capture. Steers and queued turns advance when // the capture commits and repeats the update, after the deliveries ahead of it on the lane. - const awaitsCheckpointCapture = (run: OrchestrationV2Run) => + const unsettledCheckpointCapture = (run: OrchestrationV2Run) => run.status !== "completed" || run.checkpointId !== null - ? Effect.succeed(false) - : effectOutbox.get(`effect:checkpoint.capture:${run.id}`).pipe( - Effect.map( - Option.exists((effect) => effect.status === "pending" || effect.status === "running"), - ), - Effect.orElseSucceed(() => false), - ); + ? Effect.succeed(Option.none()) + : effectOutbox + .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`)) + .pipe( + Effect.map((effects) => + Option.fromNullishOr( + effects.find((effect) => effect.status === "pending" || effect.status === "running") + ?.id, + ), + ), + Effect.orElseSucceed(() => Option.none()), + ); + const awaitsCheckpointCapture = (run: OrchestrationV2Run) => + Effect.map(unsettledCheckpointCapture(run), Option.isSome); const awaitLatestRunCapture = Effect.fn("Orchestrator.awaitLatestRunCapture")( function* (threadId: ThreadId) { const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"]); const latest = latestStartedRun(runs); - if (latest === undefined || !(yield* awaitsCheckpointCapture(latest))) return; - yield* effectOutbox.awaitSettled(`effect:checkpoint.capture:${latest.id}`); + if (latest === undefined) return; + const capture = yield* unsettledCheckpointCapture(latest); + if (Option.isNone(capture)) return; + yield* effectOutbox.awaitSettled(capture.value); }, (effect) => Effect.ignore(effect), ); @@ -13579,7 +13588,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* Ref.update(input.effects, (effects) => [ ...effects, { - id: `effect:checkpoint.capture:${run.id}`, + id: `effect:checkpoint.capture:${attempt.id}`, commandId: CommandId.make(`command:effect:checkpoint.capture:${run.id}`), threadId: input.command.threadId, request: { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 46e0485d4014b..eec3a8cce0a3f 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -883,7 +883,7 @@ export const layer: Layer.Layer< input.terminal.status === "cancelled" ? [ { - id: `effect:checkpoint.capture:${input.run.id}`, + id: `effect:checkpoint.capture:${input.attempt.id}`, commandId: checkpointCaptureCommandId, threadId: input.run.threadId, request: { From 51c47827dfc98a9fec5825826713173236ba8ff3 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Tue, 24 Nov 2026 08:25:37 +0000 Subject: [PATCH 288/288] feat(web): file links show one folder by default and stop at ~/ or / File link folders now default to 2 (one folder + file name). The walk goes up the full folded path and stops early at the thread machine's home (`~/`), at POSIX root (`/`) or at a Windows drive root (`C:/`), showing fewer folders than the setting there. The server reports its home in a new optional ServerConfig.homeDirectory; the web client reads it per environment through an atom holding only that string. Workspace files no longer stop at the workspace root, but a link written relative to the workspace (which may open a search match) shows only the folders it names. Unexpanded `~/` links are read against the reported home, and on a Windows server Git Bash `/c/...` paths are read as `C:/...`. Links ending in `.`, `..` or a bare `~`, and any copy of a repeated file name, get no prefix; a home at `/` or a drive root draws the root marker. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/server/src/ws.ts | 1 + apps/web/src/components/ChatMarkdown.tsx | 2 +- apps/web/src/fork/FileLinkPathPrefix.tsx | 30 ++- .../fork/fileLinkPathDepth.browser.test.tsx | 104 ++++++++-- apps/web/src/fork/fileLinkPathDepth.test.ts | 192 +++++++++++++++--- apps/web/src/fork/fileLinkPathDepth.ts | 154 ++++++++++++-- .../src/fork/fileLinkPathDepth.test.ts | 20 +- .../contracts/src/fork/fileLinkPathDepth.ts | 8 +- packages/contracts/src/server.ts | 2 + 10 files changed, 430 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index 150b95487b10a..fadaa965a63b9 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - **FYI messages between agents:** an agent can send another thread an FYI, a note of at most 16,000 characters that needs no action and starts no turn. The receiving agent gets it with its next turn; a running Claude Code thread gets it at its next tool call. An FYI counts as delivered only when the turn that carries it finishes: a turn that fails, is stopped, restarts or is reverted gives it back, so the agent may see it twice. When a thread has an FYI waiting and has been idle for 6 hours, T3 Code wakes it to deliver its FYIs, unless the thread is settled, archived, waiting for your answer or holds queued messages; a snoozed thread waits until its snooze ends. The 6 hours count from the thread's last turn, or from the reset of a usage limit that stopped it on the provider it still uses (or from the end of a snooze that ends after that reset), so an FYI to a thread that has been idle longer wakes it within minutes. A thread whose usage limit has no known reset time, or whose provider fails every turn, gets a failed wake every 6 hours while an FYI waits. A wake carries up to 16,000 characters of FYIs. The rest, and any that a wake gives back because it failed or you stopped it, get another wake after 6 more idle hours. A wake is a new turn, so **Resume** no longer continues a turn that ended before it. Settle or archive a thread to stop its wakes. The timeline marks these messages "FYI · waiting", "FYI · sent" while the turn that carries them runs, and "FYI" once it finished. - **Open server files by their path:** in a browser signed in to T3 Code at its own address, open `/` (such as `https://t3.example.com/home/ana/work/report.html`) to see that file read-only, for files under the server user's home folder and temp folder. A session needs the `filesystem:read` permission, and a signed-out browser gets a sign-in page. Text and code of any type show as plain text, and images, PDFs, audio and video show as themselves. A folder shows its `index.html`, or else a list of its files. Links ending in `:line` or `:line:col` open the file. Names that start with `.`, and T3 Code's own data folder, are not served. An HTML page runs in a sandboxed frame at the same address: its scripts run but cannot act as you in T3, and it loads files from its own folder and below for an hour, though its scripts cannot fetch them. A page directly in the home or temp folder loads no other files. An HTML page linked from another site, or any HTML page over plain HTTP, first shows an Open link. - **HTML pages from disk block their own network calls:** an HTML file that the file viewer, "Open in browser" or a server file path shows from disk runs its own scripts and loads scripts, styles, fonts and images over HTTPS. It cannot use fetch, XHR, WebSocket, EventSource, beacons or form posts, its frames cannot load other addresses, and audio and video play only from its own files or inline data. A page that fetches its data while it runs needs that data inline. An allowed load can still carry data in its URL, so these limits do not make an untrusted page safe. -- **Folders on file links:** Settings → Appearance → File link folders shows up to four folders before the file name on file links in messages and Markdown previews, such as `review-pipeline/glossary.md`, so you need not hover a link to see where the file is. Each browser, and the desktop app, keeps its own choice. A file name that repeats in one message keeps its folder hint after the name. +- **Folders on file links:** By default, file links in messages and Markdown previews show one folder before the file name, such as `docs/guide.md`. Settings → Appearance → File link folders lets you pick the file name alone or up to four folders. When you show folders, the prefix stops at the thread machine's home folder with `~/` or at filesystem root with `/`, as in `~/notes.md` and `/etc/hosts`. On Windows, when the prefix reaches a drive root, it shows the drive, such as `C:/`. A link written relative to the project without a leading `./` shows only the folders it names, because it may open a matching file in another folder. Each browser and the desktop app keeps its own choice. If a browser or the desktop app already saved its settings, it keeps the saved value. The setting's reset button gives the new default. A file name that repeats in one message keeps its folder hint after the name. - Enabling math rendering by default. - Other small fixes. diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1254e9efbeada..b6c58a145b761 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1911,6 +1911,7 @@ export const layerWsRpc = ( auth, cwd: config.cwd, hostname: yield* HostProcess.Hostname, + homeDirectory: yield* HostProcess.HomeDirectory, keybindingsConfigPath: config.keybindingsConfigPath, keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index d7e806b244eca..ca98f29dcf727 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -819,7 +819,7 @@ function useChatMarkdownState( const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null, fileLinkPeerPaths, hostFileOrigins)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); - const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath); + const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath, environmentId); const resolveThreadPullRequest = ( href: string, ): (ThreadPullRequestKey & { readonly url: string }) | null => { diff --git a/apps/web/src/fork/FileLinkPathPrefix.tsx b/apps/web/src/fork/FileLinkPathPrefix.tsx index 2604a8f409de4..99537e8f53ec2 100644 --- a/apps/web/src/fork/FileLinkPathPrefix.tsx +++ b/apps/web/src/fork/FileLinkPathPrefix.tsx @@ -1,9 +1,33 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + import { useClientSettings } from "../hooks/useSettings"; -import { type FileLinkPathMeta, fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { serverEnvironment } from "../state/server"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; + +// Only the home string and the OS flag, so other config updates do not re-render every message. +const serverHomeAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => get(serverEnvironment.configValueAtom(environmentId))?.homeDirectory || null, + ).pipe(Atom.withLabel(`file-link-server-home:${environmentId}`)), +); +const serverWindowsAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => + get(serverEnvironment.configValueAtom(environmentId))?.environment.platform.os === "windows", + ).pipe(Atom.withLabel(`file-link-server-windows:${environmentId}`)), +); -export function useFileLinkPrefix(parentSuffixByPath: ReadonlyMap) { +export function useFileLinkPrefix( + parentSuffixByPath: ReadonlyMap, + environmentId: EnvironmentId | null, +) { const depth = useClientSettings((settings) => settings.fileLinkPathDepth); - return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, parentSuffixByPath, depth); + const home = useAtomValue(serverHomeAtom(environmentId)); + const windows = useAtomValue(serverWindowsAtom(environmentId)); + const view = { depth, home, windows, repeatedNames: repeatedFileNames(parentSuffixByPath) }; + return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, view); } /** diff --git a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx index 44e3ed546c4f1..7eb9e95bbf89f 100644 --- a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx +++ b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx @@ -1,5 +1,10 @@ -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; -import { expect, it } from "vite-plus/test"; +import { + DEFAULT_CLIENT_SETTINGS, + EnvironmentId, + type EditorId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; @@ -9,34 +14,67 @@ import ChatMarkdown from "../components/ChatMarkdown"; import { collectThreadFindRanges } from "../components/chat/threadFindHighlights"; import { __setClientSettingsForTests, persistClientSettingsPatch } from "../hooks/useSettings"; +const SERVER_HOME_ENVIRONMENT = vi.hoisted(() => "server-home"); + +// One environment reports a home folder that its thread's cwd does not reveal. +vi.mock(import("../state/server"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + const config = Atom.make({ + availableEditors: [] as readonly EditorId[], + environment: { platform: { os: "linux" }, capabilities: {} }, + homeDirectory: "/srv/me", + }); + const configValueAtom = actual.serverEnvironment.configValueAtom; + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + configValueAtom: ((environmentId: EnvironmentId | null) => + environmentId === SERVER_HOME_ENVIRONMENT + ? config + : configValueAtom(environmentId)) as never, + }, + }; +}); + const TEXT = [ - "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts) and [readme](README.md).", + "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts), [readme](README.md) and [hosts](/etc/hosts).", "The review is done.", ].join("\n\n"); -it("draws the chosen folders before file names, outside the label text", async () => { +function withDefaultSettings(): Disposable { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); - using _settings = { - [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS), - }; + return { [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS) }; +} + +function chipPrefixes(container: HTMLElement) { + return [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { + const prefix = chip.querySelector("[data-file-link-prefix]"); + return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; + }); +} + +it("draws the chosen folders before file names, outside the label text", async () => { + using _settings = withDefaultSettings(); await using screen = await render(
, ); - const chips = () => - [...screen.container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { - const prefix = chip.querySelector("[data-file-link-prefix]"); - return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; - }); - const labels = ["glossary.md · L12", "index.ts · src/web", "index.ts · src/server", "README.md"]; - expect(chips()).toEqual(labels.map((label) => [null, label])); - - await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 2 }, async () => {})); - - expect(chips()).toEqual([ + const labels = [ + "glossary.md · L12", + "index.ts · src/web", + "index.ts · src/server", + "README.md", + "hosts", + ]; + expect(chipPrefixes(screen.container)).toEqual([ ['"review-pipeline/"', labels[0]], - ...labels.slice(1).map((label) => [null, label]), + [null, labels[1]], + [null, labels[2]], + [null, labels[3]], + ['"/etc/"', labels[4]], ]); await expect .element( @@ -60,4 +98,32 @@ it("draws the chosen folders before file names, outside the label text", async ( position: { x: word.left - box.left + 4, y: word.top - box.top + word.height / 2 }, }); expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim()); + + await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 1 }, async () => {})); + + expect(chipPrefixes(screen.container)).toEqual(labels.map((label) => [null, label])); +}); + +it("draws ~/ at the home folder the thread's server reports", async () => { + using _settings = withDefaultSettings(); + const text = "See [a](/srv/me/notes/a.md) and [b](/srv/other/notes/b.md)."; + await using screen = await render( + <> + + + , + ); + expect(chipPrefixes(screen.container)).toEqual([ + ['"~/notes/"', "a.md"], + ['"notes/"', "b.md"], + ['"notes/"', "a.md"], + ['"notes/"', "b.md"], + ]); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.test.ts b/apps/web/src/fork/fileLinkPathDepth.test.ts index 189bc91934497..cd335702e4ddd 100644 --- a/apps/web/src/fork/fileLinkPathDepth.test.ts +++ b/apps/web/src/fork/fileLinkPathDepth.test.ts @@ -1,45 +1,177 @@ import type { FileLinkPathDepth } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; -type Meta = Parameters[0]; - -const inWorkspace = (workspaceRelativePath: string): Meta => ({ - filePath: `/home/me/project/${workspaceRelativePath}`, +const HOME = "/home/me"; +const inWorkspace = ( + workspaceRelativePath: string, + root = "/home/me/project", +): FileLinkPathMeta => ({ + filePath: `${root}/${workspaceRelativePath}`, workspaceRelativePath, + workspaceLookupPath: null, +}); +// A link written relative to the workspace, which may open a search match elsewhere. +const written = (workspaceRelativePath: string, root = "/home/me/project"): FileLinkPathMeta => ({ + ...inWorkspace(workspaceRelativePath, root), + workspaceLookupPath: workspaceRelativePath, +}); +const outside = (filePath: string): FileLinkPathMeta => ({ + filePath, + workspaceRelativePath: null, + workspaceLookupPath: null, }); -const outside = (filePath: string): Meta => ({ filePath, workspaceRelativePath: null }); const collisions = new Map([ ["/home/me/project/src/web/index.ts", "src/web"], ["C:/repo/src/server/index.ts", "src/server"], ]); describe("fileLinkPathPrefix", () => { - it.each<[string, Meta, FileLinkPathDepth, string | undefined]>([ - ["depth 1 shows no folder", inWorkspace("docs/review-pipeline/glossary.md"), 1, undefined], - ["depth 2", inWorkspace("docs/review-pipeline/glossary.md"), 2, "review-pipeline/"], - ["depth 3", inWorkspace("docs/review-pipeline/glossary.md"), 3, "docs/review-pipeline/"], - ["a workspace root file", inWorkspace("README.md"), 3, undefined], - ["fewer folders than the depth", inWorkspace("docs/glossary.md"), 5, "docs/"], - [ - "an absolute path outside the workspace", - outside("/etc/nginx/sites/app.conf"), + it.each< + [string, FileLinkPathMeta, FileLinkPathDepth, string | null, string | undefined, boolean?] + >([ + // Home and root examples at the default depth. + ["a file in home", outside("/home/me/a.md"), 2, HOME, "~/"], + ["a folder in home", outside("/home/me/dir/a.md"), 2, HOME, "~/dir/"], + ["a file at root", outside("/a.md"), 2, HOME, "/"], + ["a folder at root", outside("/etc/a.conf"), 2, HOME, "/etc/"], + ["past home", outside("/home/me/x/dir/a.md"), 2, HOME, "dir/"], + ["reaching home after two folders", outside("/home/me/x/dir/a.md"), 3, HOME, "~/x/dir/"], + ["past root", outside("/etc/x/a.conf"), 2, HOME, "x/"], + ["fewer folders than the depth at home", outside("/home/me/a.md"), 5, HOME, "~/"], + ["fewer folders than the depth at root", outside("/etc/nginx/a.conf"), 5, HOME, "/etc/nginx/"], + ["depth 1 shows no folder", outside("/home/me/dir/a.md"), 1, HOME, undefined], + ["depth 1 shows no root", outside("/a.md"), 1, HOME, undefined], + ["another user's home", outside("/home/bob/a.md"), 2, HOME, "bob/"], + ["another user's home reaching root", outside("/home/bob/a.md"), 3, HOME, "/home/bob/"], + ["a folder that only starts like home", outside("/home/me2/a.md"), 2, HOME, "me2/"], + ["the folder above home", outside("/home/a.md"), 2, HOME, "/home/"], + ["home unknown", outside("/home/me/a.md"), 2, null, "me/"], + ["home at /root", outside("/root/notes/a.md"), 2, "/root", "~/notes/"], + ["a home at root", outside("/etc/hosts"), 2, "/", "/etc/"], + ["a home at a drive root", outside("C:\\x\\a.md"), 2, "C:\\", "C:/x/"], + ["home given with a trailing slash", outside("/home/me/dir/a.md"), 2, "/home/me/", "~/dir/"], + // An unexpanded `~/` link. + ["a literal ~ file", outside("~/a.md"), 2, null, "~/"], + ["a literal ~ folder", outside("~/notes/a.md"), 2, null, "~/notes/"], + ["past a literal ~", outside("~/x/notes/a.md"), 2, null, "notes/"], + ["a literal ~ with home known", outside("~/notes/a.md"), 3, HOME, "~/notes/"], + // The workspace no longer stops the walk. + [ + "a workspace file", + inWorkspace("docs/review-pipeline/glossary.md"), + 2, + HOME, + "review-pipeline/", + ], + [ + "a workspace file, deeper", + inWorkspace("docs/review-pipeline/glossary.md"), + 3, + HOME, + "docs/review-pipeline/", + ], + ["a workspace root file", inWorkspace("README.md", "/home/me/code/proj"), 2, HOME, "proj/"], + [ + "a workspace root file reaching home", + inWorkspace("README.md", "/home/me/code/proj"), + 3, + HOME, + "~/code/proj/", + ], + ["a workspace in home", inWorkspace("README.md", "/home/me/proj"), 2, HOME, "~/proj/"], + ["a workspace at home", inWorkspace("README.md", HOME), 2, HOME, "~/"], + ["a workspace at home, one folder", inWorkspace("notes/a.md", HOME), 2, HOME, "~/notes/"], + ["a workspace at root", inWorkspace("a.md", ""), 2, null, "/"], + ["a POSIX folder named like a drive", inWorkspace("C:/a.md", ""), 2, null, "/C:/"], + ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, HOME, "C:/docs/"], + // `..` and `.` fold before the walk. + ["a .. reaching home", outside("/home/me/proj/../a.md"), 2, HOME, "~/"], + ["a .. outside home", outside("/home/me/proj/../x/y/a.ts"), 2, HOME, "y/"], + ["a .. past root", outside("/a/../../b/c.md"), 3, HOME, "/b/"], + ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, HOME, "docs/"], + ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, HOME, "shared/lib/"], + ["a dot folder", outside("./src/./app.ts"), 3, HOME, "src/"], + // Windows. + ["a Windows drive root file", outside("C:\\a.md"), 2, null, "C:/"], + ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 2, null, "me/"], + [ + "a Windows drive path reaching the drive", + outside("C:\\Users\\me\\notes.md"), + 4, + null, + "C:/Users/me/", + ], + ["a Windows home", outside("C:\\Users\\me\\notes.md"), 2, "C:\\Users\\me", "~/"], + [ + "a Windows home in another case", + outside("c:\\users\\ME\\d\\notes.md"), + 2, + "C:\\Users\\me", + "~/d/", + ], + [ + "a Windows path on another drive", + outside("D:\\Users\\me\\notes.md"), 3, - "nginx/sites/", - ], - ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, undefined], - ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, "C:/docs/"], - ["a slash-prefixed Windows drive path", outside("/C:/Users/me/notes.md"), 3, "Users/me/"], - ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 4, "Users/me/"], - ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, "share/docs/"], - ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, "shared/lib/"], - ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, "docs/"], - ["a .. past the folders", outside("/a/../../b/c.md"), 3, "b/"], - ["a dot folder", outside("./src/./app.ts"), 3, "src/"], - ["a colliding path", inWorkspace("src/web/index.ts"), 3, undefined], - ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, undefined], - ])("%s", (_name, meta, depth, expected) => { - expect(fileLinkPathPrefix(meta, collisions, depth)).toBe(expected); + "C:\\Users\\me", + "D:/Users/me/", + ], + ["a POSIX home for a Windows path", outside("C:\\home\\me\\a.md"), 2, HOME, "me/"], + ["a .. at a drive root", outside("C:\\..\\a.md"), 2, null, "C:/"], + ["a slash-prefixed Windows drive", outside("/C:/Users/me/notes.md"), 3, null, "C:/Users/me/"], + ["a slash-prefixed Windows home", outside("/C:/Users/me/notes.md"), 3, "C:\\Users\\me", "~/"], + ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, null, "share/docs/"], + [ + "a UNC path shows its server", + outside("\\\\server\\share\\docs\\a.md"), + 5, + null, + "server/share/docs/", + ], + // A written workspace link shows only the folders it names. + [ + "a written workspace link", + written("docs/review-pipeline/glossary.md"), + 5, + HOME, + "docs/review-pipeline/", + ], + ["a written file name", written("README.md"), 3, HOME, undefined], + ["a written file name at home", written("README.md", HOME), 2, HOME, undefined], + [ + "a written ./ link walks on", + { ...written("./docs/a.md"), filePath: "/home/me/project/docs/a.md" }, + 3, + HOME, + "~/project/docs/", + ], + // An unexpanded `~/` link and a Windows server's Git Bash path use the reported home. + ["a literal ~ with home at root", outside("~/notes.md"), 2, "/", "/"], + ["a literal ~ with a .. past home", outside("~/../notes.md"), 2, "/srv/me", "/srv/"], + [ + "a Git Bash path on a Windows server", + outside("/c/Users/alex/notes.md"), + 2, + "C:\\Users\\alex", + "~/", + true, + ], + ["a Git Bash drive root", outside("/d/a.md"), 2, "C:\\Users\\alex", "D:/", true], + ["a Git Bash path with no reported home", outside("/d/a.md"), 2, null, "D:/", true], + ["a /c folder on a POSIX server", outside("/c/a.md"), 2, HOME, "/c/"], + ["a written link past its own folders", written("docs/../../notes.md"), 5, HOME, undefined], + ["a link to home itself", outside("~/"), 2, "/srv/me", undefined], + // No prefix. + ["a root file named like a repeated file", outside("/home/me/index.ts"), 2, HOME, undefined], + ["a link to a parent folder", outside("/home/me/one/project/../"), 2, HOME, undefined], + ["a link to a current folder", outside("/home/me/one/."), 2, HOME, undefined], + ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, HOME, undefined], + ["a colliding path", inWorkspace("src/web/index.ts"), 3, HOME, undefined], + ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, null, undefined], + ])("%s", (_name, meta, depth, home, expected, windows = false) => { + const repeatedNames = repeatedFileNames(collisions); + expect(fileLinkPathPrefix(meta, { depth, home, windows, repeatedNames })).toBe(expected); }); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.ts b/apps/web/src/fork/fileLinkPathDepth.ts index 171c1c49bf3fe..ac19bb975901c 100644 --- a/apps/web/src/fork/fileLinkPathDepth.ts +++ b/apps/web/src/fork/fileLinkPathDepth.ts @@ -3,29 +3,145 @@ import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/ import type { MarkdownFileLinkMeta } from "../markdown-links"; -export type FileLinkPathMeta = Pick; +export type FileLinkPathMeta = Pick< + MarkdownFileLinkMeta, + "filePath" | "workspaceRelativePath" | "workspaceLookupPath" +>; -/** The last `depth - 1` folders of a file link as `a/b/`, or undefined when there are none to show. */ +export interface FileLinkPathView { + readonly depth: FileLinkPathDepth; + readonly home: string | null; + // The server runs on Windows, where Git Bash writes `C:\x` as `/c/x`. + readonly windows: boolean; + // File names that repeat in the message, from `repeatedFileNames`. + readonly repeatedNames: ReadonlySet; +} + +/** The file names of a message's repeated-name folder hints. */ +export function repeatedFileNames(parentSuffixByPath: ReadonlyMap): Set { + return new Set([...parentSuffixByPath.keys()].map(lastName)); +} + +type PathKind = "posix" | "relative" | "drive" | "unc"; + +interface FoldedPath { + readonly kind: PathKind; + // `.` dropped and `..` folded; a drive path starts with its drive (`C:`), a UNC path with its server. + readonly names: readonly string[]; + // The walk shows no folder before this index. + readonly floor: number; +} + +function foldPath(raw: string): FoldedPath { + const kind: PathKind = raw.startsWith("\\\\") + ? "unc" + : isWindowsAbsolutePath(raw) + ? "drive" + : raw.startsWith("/") + ? "posix" + : "relative"; + const windows = kind === "drive" || kind === "unc"; + // `..` never climbs above a drive or a UNC share. + const top = kind === "drive" ? 1 : kind === "unc" ? 2 : 0; + const names: string[] = []; + for (const part of raw.split(windows ? /[\\/]/ : "/")) { + if (part === "" || part === ".") continue; + if (part !== "..") names.push(part); + else if (names.length > top && names.at(-1) !== "..") names.pop(); + else if (kind === "relative") names.push(part); + } + // A UNC path shows its server and share like folders, as before; it draws no root marker. + const floor = kind === "relative" ? names.lastIndexOf("..") + 1 : 0; + return { kind, names, floor }; +} + +// How many leading names of `path` are the home folder; undefined when it is not under home. +function homeLength(path: FoldedPath, home: string | null): number | undefined { + if (path.kind === "relative") return path.floor === 0 && path.names[0] === "~" ? 1 : undefined; + if (home === null) return undefined; + const homePath = foldPath(home); + // A home at `/` or at a drive root is that root, which draws its own marker. + if (homePath.names.length <= (homePath.kind === "drive" ? 1 : 0)) return undefined; + if (homePath.kind !== path.kind || homePath.names.length > path.names.length) return undefined; + const same = + path.kind === "posix" + ? (a: string, b: string) => a === b + : (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + return homePath.names.every((name, i) => same(name, path.names[i]!)) + ? homePath.names.length + : undefined; +} + +/** + * Returns the path prefix before a file link's name, with up to `depth - 1` folders, ending in `/`. + * Stops early at home with `~/`, at POSIX root with `/`, or at a Windows drive root such as `C:/`. + * Returns `undefined` at depth 1, for a repeated file name, or when there is nothing to show. + */ export function fileLinkPathPrefix( meta: FileLinkPathMeta, - parentSuffixByPath: ReadonlyMap, - depth: FileLinkPathDepth, + view: FileLinkPathView, ): string | undefined { - if (depth === 1 || parentSuffixByPath.has(meta.filePath.replaceAll("\\", "/"))) return undefined; - // Workspace-relative paths already use `/`; a POSIX name may contain `\`. - const path = meta.workspaceRelativePath ?? stripSlashPrefixedWindowsDrive(meta.filePath); - const windows = meta.workspaceRelativePath === null && isWindowsAbsolutePath(path); - const segments = path - .split(windows ? /[\\/]/ : "/") - .filter((segment) => segment !== "" && segment !== "."); - if (windows && /^[A-Za-z]:$/.test(segments[0] ?? "")) segments.shift(); + if (view.depth === 1) return undefined; + // A repeated file name keeps its folder hint after the name instead. The hint map leaves out a + // copy that has no folder above it, so the check goes by name. + const name = lastName(meta.filePath); + if (view.repeatedNames.has(name)) return undefined; + // The label of a link ending in `.`, `..` or a bare `~` is that name, not the folder it + // reaches, so any folders drawn before it would name another path. + if (name === "." || name === ".." || /^~[\\/]*$/.test(meta.filePath)) return undefined; + const path = foldPath(hostPath(meta, view)); // The label names such a file by its last `\` part, so folders before it would misname the path. - if (!windows && segments.at(-1)?.includes("\\")) return undefined; - const resolved: string[] = []; - for (const segment of segments) { - if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") resolved.pop(); - else resolved.push(segment); + if ((path.kind === "posix" || path.kind === "relative") && path.names.at(-1)?.includes("\\")) { + return undefined; + } + const folders = path.names.length - 1; + const home = homeLength(path, view.home); + // A link written relative to the workspace may open a search match in another folder, so only + // the folders it names are sure, and no marker is drawn above them. + const lookup = meta.workspaceLookupPath; + const written = + lookup !== null && !/^(?:\.{1,2}|~)[\\/]/.test(lookup) && !/[\\/]$/.test(lookup) + ? foldPath(lookup) + : null; + // Names before any leading `..` the link keeps are not folders it names. + const unsure = written === null ? -1 : path.names.length - (written.names.length - written.floor); + // `above` counts the folders still hidden; the walk moves up one folder at a time. + let above = folders; + let marker = ""; + while (above > unsure) { + if (above === home) marker = "~/"; + else if (path.kind === "posix" && above === 0) marker = "/"; + else if (path.kind === "drive" && above === 1) marker = `${path.names[0]}/`; + if (marker !== "" || above <= path.floor || folders - above === view.depth - 1) break; + above -= 1; + } + const shown = path.names.slice(Math.max(above, unsure), folders); + const prefix = marker + shown.map((folder) => `${folder}/`).join(""); + return prefix === "" ? undefined : prefix; +} + +function lastName(path: string): string { + return ( + path + .split(/[\\/]/) + .filter((part) => part !== "") + .at(-1) ?? "" + ); +} + +// The file's path as the server reads it, as far as display needs it. +function hostPath(meta: FileLinkPathMeta, { home, windows }: FileLinkPathView): string { + // An unexpanded `~/` link names the reported home. + if (/^~[\\/]/.test(meta.filePath) && home) { + return `${home.replace(/[\\/]+$/, "")}/${meta.filePath.slice(2)}`; + } + // Only a path outside the workspace may be a Windows drive written after a slash; inside a + // workspace at `/`, `/C:/a.md` names a POSIX folder `C:`. + if (meta.workspaceRelativePath !== null) return meta.filePath; + // A Windows server reads Git Bash's `/c/x` as `C:/x`. + if (windows) { + const drive = /^\/([a-zA-Z])(?=\/|$)/.exec(meta.filePath); + if (drive !== null) return `${drive[1]!.toUpperCase()}:${meta.filePath.slice(2) || "/"}`; } - const folders = resolved.slice(resolved.lastIndexOf("..") + 1, -1).slice(1 - depth); - return folders.length === 0 ? undefined : `${folders.join("/")}/`; + return stripSlashPrefixedWindowsDrive(meta.filePath); } diff --git a/packages/contracts/src/fork/fileLinkPathDepth.test.ts b/packages/contracts/src/fork/fileLinkPathDepth.test.ts index b0248f4f5b6e5..c4ad81cca6aee 100644 --- a/packages/contracts/src/fork/fileLinkPathDepth.test.ts +++ b/packages/contracts/src/fork/fileLinkPathDepth.test.ts @@ -7,22 +7,24 @@ const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema); const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema); describe("fileLinkPathDepth", () => { - it("defaults to the file name alone", () => { - expect(decodeClientSettings({}).fileLinkPathDepth).toBe(1); + it("defaults to one folder and the file name", () => { + expect(decodeClientSettings({}).fileLinkPathDepth).toBe(2); }); - it.each([9, 0, 2.5, "2", null, { depth: 2 }])( - "a bad stored depth %j decodes to 1 and keeps the other settings", + it.each([9, 0, 2.5, "3", null, { depth: 3 }])( + "a bad stored depth %j decodes to 2 and keeps the other settings", (fileLinkPathDepth) => { const settings = decodeClientSettings({ fileLinkPathDepth, wordWrap: false }); - expect(settings.fileLinkPathDepth).toBe(1); + expect(settings.fileLinkPathDepth).toBe(2); expect(settings.wordWrap).toBe(false); }, ); - it("round-trips a valid depth", () => { - const settings = decodeClientSettings({ fileLinkPathDepth: 3 }); - expect(settings.fileLinkPathDepth).toBe(3); - expect(decodeClientSettings(encodeClientSettings(settings)).fileLinkPathDepth).toBe(3); + it.each([1, 3] as const)("round-trips a saved depth %j", (fileLinkPathDepth) => { + const settings = decodeClientSettings({ fileLinkPathDepth }); + expect(settings.fileLinkPathDepth).toBe(fileLinkPathDepth); + expect(decodeClientSettings(encodeClientSettings(settings)).fileLinkPathDepth).toBe( + fileLinkPathDepth, + ); }); }); diff --git a/packages/contracts/src/fork/fileLinkPathDepth.ts b/packages/contracts/src/fork/fileLinkPathDepth.ts index efc4ff724c3e2..44b61a31a574b 100644 --- a/packages/contracts/src/fork/fileLinkPathDepth.ts +++ b/packages/contracts/src/fork/fileLinkPathDepth.ts @@ -5,8 +5,10 @@ import * as Schema from "effect/Schema"; export const FileLinkPathDepth = Schema.Literals([1, 2, 3, 4, 5]); export type FileLinkPathDepth = typeof FileLinkPathDepth.Type; -/** The stored field: a bad value decodes to 1, so it can never fail the client settings. */ +const DEFAULT_FILE_LINK_PATH_DEPTH: FileLinkPathDepth = 2; + +/** Stored file link depth. A missing or invalid value defaults to 2 so client settings never fail. */ export const StoredFileLinkPathDepth = FileLinkPathDepth.pipe( - Schema.catchDecoding(() => Effect.succeedSome(1 as const)), - Schema.withDecodingDefault(Effect.succeed(1 as const)), + Schema.catchDecoding(() => Effect.succeedSome(DEFAULT_FILE_LINK_PATH_DEPTH)), + Schema.withDecodingDefault(Effect.succeed(DEFAULT_FILE_LINK_PATH_DEPTH)), ); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 1e70426001495..b4424e2382c8f 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -713,6 +713,8 @@ export const ServerConfig = Schema.Struct({ cwd: TrimmedNonEmptyString, /** The machine's own name, which file URIs from its shells may carry. Older servers omit it. */ hostname: Schema.optionalKey(Schema.String), + /** The server machine's home folder, which chat file links shorten to `~/`. Older servers omit it. */ + homeDirectory: Schema.optionalKey(Schema.String), keybindingsConfigPath: TrimmedNonEmptyString, keybindings: ResolvedKeybindingsConfig, issues: ServerConfigIssues,